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

2011/6/4

Keeping direction

Is it possible that an object keeps going in the same direction it was going before? I'm working on a pacman game and the ghost are moving with Greenfoot.getRandomNumber when there are 3 or more paths to go, but I can't use this method when there are just 2 possibilities like forward and backward, because it would keep moving one step forward and one step backward.
danpost danpost

2011/6/5

#
Do your checks in this order: 1) Are there any routes to continue on without reversing; if not, reverse. 2) Is there only one route to continue on; if so, continue in that direction. 3) If neither of the above, then there are multiple routes to continue on (without reversing); randomly select one. It might be best to: 1) Count all direction from location (excluding reverse) 2) Do a switch on the count a) case 0: reverse b) case 1: that one way c) case 2 and 3: randomly select one of those multiple ways
I understand what you mean and I would do it in this way, too, but I don't know how define the "reversing". So that I would define your first and second step in the same way
danpost danpost

2011/6/5

#
Set up a private variable, say 'currentDirection', in your mover classes, possibly int for {0, 1, 2, and 3} or String for {"north", "east", "south", and "west"} (for int you could set up 4 public static final int North = 0, East = 1, South = 2, and West = 3); the mover would have its variable set to the direction it is currently moving; then, reference it, add 2, and then get the remainder after dividing by 4: int reverseDirection = (currentDirection + 2) % 4; Do not forget to change the 'currentDirection' variable when changing the mover's direction. Also, the other directions would be: int leftDirection = (currentDirection + 3) % 4; int rightDirection = (currentDirection + 1) % 4; int forwardDirection = currentDirection;
You need to login to post a reply.