The character will hit the wall from the left side or from the top but the right and bottom side of the wall do not work and the character can walk through them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | import greenfoot.*; /** * Write a description of class Bob here. * * @author (your name) * @version (a version number or a date) */ public class Bob extends Actor { public int speed = 3 ; public void act() { checkMovement(); checkCollision(); } public void checkCollision() { if (getOneIntersectingObject(Wall. class ) != null ) setLocation(getX()-speed,getY()-speed); } public void checkMovement() { if (Greenfoot.isKeyDown( "w" )) { setLocation(getX(),getY()-speed); setImage( "bobback.png" ); } if (Greenfoot.isKeyDown( "s" )) { setLocation(getX(),getY()+speed); setImage( "bob.png" ); } if (Greenfoot.isKeyDown( "a" )) { setLocation(getX()-speed,getY()); setImage( "bob.png" ); } if (Greenfoot.isKeyDown( "d" )) { setLocation(getX()+speed,getY()); setImage( "bob.png" ); } } } |