This site requires JavaScript, please enable it in your browser!
Greenfoot back
r0b75hg7
r0b75hg7 wrote ...

2023/5/22

Aquarium Lab

r0b75hg7 r0b75hg7

2023/5/22

#
I want the seahorse to rotate in a circle while always facing right, and not spinning while it moves. import greenfoot.*; public class Seahorse extends Actor { private static final int RADIUS = 200; private static final int ANGLE_INCREMENT = 1; private int angle; public Seahorse() { setImage("seahorse.png"); angle = 0; } public void act() { rotateAndMove(); } private void rotateAndMove() { setRotation(angle); // Set the rotation angle to face right move(1); angle += ANGLE_INCREMENT; if (angle >= 360) { angle = 0; } } }
danpost danpost

2023/5/22

#
r0b75hg7 wrote...
I want the seahorse to rotate in a circle while always facing right, and not spinning while it moves.
The best way to travel in a circle is to retain (1) center point of circle; (2) radius; and (3) current angle:
private static final int RADIUS = 200;
private static final int ANGLE_INCREMENT = 1;

private int angle;
private int[] center = new int[2];

protected void addedToWorld(World world) {
    center[0] = getX();
    center[1] = getY();
    move(RADIUS);
}

public void act() {
    angle = (angle+ANGLE_INCREMENT)%360;
    setLocation(center[0], center[1]);
    setRotation(angle);
    move(RADIUS);
    setRotation(0);
}
With this code, the seahorse needs to be placed (added to the world) at the center of the circle it is to trace.
r0b75hg7 r0b75hg7

2023/5/22

#
Thanks, I got it.
You need to login to post a reply.