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

2012/10/4

Help with moving backwards

Codeguy221 Codeguy221

2012/10/4

#
In my crab game, the crab only moves forwards. I was wondering if it is possible to also make it move backwards. This is the code used to allow the crab to move forwards: private static final double WALKING_SPEED = 5.0; public void move() { double angle = Math.toRadians( getRotation() ); int x = (int) Math.round(getX() + Math.cos(angle) * WALKING_SPEED); int y = (int) Math.round(getY() + Math.sin(angle) * WALKING_SPEED); setLocation(x, y); } Please help and explain! Thank you! :D
Morran Morran

2012/10/4

#
Try this:
 
public void move()
 { 
double angle = Math.toRadians( getRotation() ); 
int x = (int) Math.round(getX() - Math.cos(angle) * WALKING_SPEED); 
int y = (int) Math.round(getY() - Math.sin(angle) * WALKING_SPEED); 
setLocation(x, y);
 } 
To move forward, you are adding the cosine of the crab's rotation times the walking speed to the x, and adding the sine of the crab's rotation times the walking speed to the y. To make it go backwards, you simply reverse it. You subtract walkingspeed * cos(angle) from the x, and subtract walkingspeed * sin(angle) from the y. Basically, if forward uses pluses, use minuses.
Morran Morran

2012/10/4

#
Do you also want an explanation of how "move()" moves in the direction of rotation, or did you simply want to know how to make it go backwards?
Codeguy221 Codeguy221

2012/10/5

#
An explanation is great, thanks! I'm new to coding, so any help you can provide would be awesome. And thank you for the code you provided, it works well!
You need to login to post a reply.