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

2013/7/15

How to move after faced a certain direction

lweave14 lweave14

2013/7/15

#
I am making a game with controls similar to Frogger. I have finally gotten the frog to face the four directions I want to but now cannot think of the right way to type out how it should move when it is facing that direction. Another way to say this would be by pressing left to face to the left, and then left again to move in that direction. I set up an if statement but don't know where it went wrong. Maybe I am just too tired to see something simple, but please help. Below is my code for this. The angles may seem weird, but it's only because the picture I used faced up to begin with so it's actually alright.
public void checkKeys()
    {
       String key = Greenfoot.getKey(); 
       rotation = getRotation();
       if ("right".equals(key))
       {
           if ("0".equals(rotation))
           {setLocation(getX() + 20, getY());}
           else {setRotation(90);}
       }               
       if ("left".equals(key))
       {
           if ("270".equals(rotation))
           {setLocation(getX() - 20, getY());}
           else {setRotation(270);}
       }               
           if ("up".equals(key))
       {
           if ("0".equals(rotation))
          {setLocation(getX(), getY() + 20);}
          else {setRotation(0);}
       }
       if ("down".equals(key))
       {
           if("180".equals(rotation))
           {setLocation(getX(), getY() - 20);}
       }
    }
Gevater_Tod4711 Gevater_Tod4711

2013/7/15

#
The problem is that you use a string to check the rotation like in line 7 (I think in line 7 the "0" should be "90"). The problem is that rotation is an int and "0" is a string. And the check for string.equals(int) will always be false. If you just use: if (rotation == 0) { ... it should work. And in lines 5, 11, ... it would be a bit easyer to use: if (Greenfoot.isKeyDown("keyname")) { ... instead of comparing the current pressed key. But your solution also would work.
You need to login to post a reply.