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

2011/12/16

How to let pacman stop moving when he face a wall

Rexsar Rexsar

2011/12/16

#
I have programmed most of the game now but I stucked on how to let the pacman stop at a wall. I have these so far: public void act() { if(direction == 0) { setLocation(getX()+1, getY()); } if(direction == 1) { setLocation(getX()-1, getY()); } if(direction == 2) { setLocation(getX(), getY()+1); } if(direction == 3) { setLocation(getX(), getY()-1); } movement(); abilityToEat(); } public boolean foundWalls() { Actor walls = getOneObjectAtOffset(10, 10, Walls.class); if(walls != null) { return true; } else { return false; } } I am wondering if my "foundWall" method is right, in addition of how to use it if it was correct. Thank you.
davmac davmac

2011/12/16

#
You're using a fixed offset for you getOneObjectAtOffset(...) call - 10,10 - but you probably want to use a different offset depending on which way the player is travelling. If right, the offset should perhaps be 10,0. If left, it should be -10,0. If up, it should be 0,-10, and if down it should be 0,10. As for how to call it: use it as the condition inside an "if" statement: if (foundWalls()) { // code inside the curly brackets is only executed if we found a wall } or: if (! foundWalls()) { // code inside the curly brackets is only executed if we didn't find a wall }
Rexsar Rexsar

2011/12/21

#
Is there any good stop method I can use? or a good way to create one?
davmac davmac

2011/12/21

#
There is no "stop" method. The way to stop moving is to not move any more! In the act() method, you should check if there is a wall in front of pacman and if so, don't move.
ManiacalPenguin ManiacalPenguin

2012/12/22

#
First thing to do is to create a variable to store X and Y values. private int x; private int y; you can use any method to move that you want, for example: if (Greenfoot.isKeyDown("right")) { setLocation(getX() + 5, getY()); } the stop at walls method should look like this public void stopAtWalls() { if (getOneIntersectingObject(Wall1.class) != null || getOneIntersectingObject(Wall2.class) != null) { setLocation(x,y); } else { x = getX(); y = getY(); } }
You need to login to post a reply.