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

2017/9/7

Greenfoot.isKeyDown only working sometimes

dan_fred dan_fred

2017/9/7

#
Hey guys. I just started using Greenfoot, and I was trying to make a code where you move a turtle with w,a,s, and d. And instead of just an image moving around, I wanted it to turn and face the direction it was going. I wrote the code, and it worked, for a little bit and then it stopped. Now it doesn't work. If I restart Greenfoot it works sometimes and then stops again. I've tried rewriting it a couple times and making it more efficient, but nothing works. Here's my code. Thanks in advance for any help.
if (Greenfoot.isKeyDown("w")){
           if (getRotation() != 270){
               setRotation(270);
            }   
            move(5);
        }
     
         if (Greenfoot.isKeyDown("s")){
        if (getRotation() != 90){
               setRotation(90);
            }   
            move(5);
        }
        
         if (Greenfoot.isKeyDown("d")){
           if (getRotation() != 0){
               setRotation(0);
            }   
            move(5);
        }
        
         if (Greenfoot.isKeyDown("a")){
          if (getRotation() != 180){
               setRotation(180);
            }   
            move(5);
        }
Super_Hippo Super_Hippo

2017/9/7

#
I don't really see anything wrong with the code. I don't know how it could stop working. Maybe something else in your code is causing that behavior. The rotation checks are not really needed. You can simplify it to this:
int dx=0, dy=0;
if (Greenfoot.isKeyDown("w")) dy--;
if (Greenfoot.isKeyDown("s")) dy++;
if (Greenfoot.isKeyDown("a")) dx--;
if (Greenfoot.isKeyDown("d")) dy++;
if (dx != 0 || dy != 0)
{
    turnTowards(getX() + dx*5, getY() + dy*5);
    setLocation(getX() + dx*5, getY() + dy*5);
}
Note that this can also turn in 45° steps.
danpost danpost

2017/9/7

#
You can eliminate the diagonal movement by changing line 6 in the code supplied by Hippo to this:
if (dx*dy == 0 && dx+dy != 0)
This says one of the two, of 'dx' and 'dy', must be zero and one must not be zero.
dan_fred dan_fred

2017/9/11

#
I don't really understand the code that you suggested, but thank you. I think it's a problem with the intallation of Greenfoot. I' using it on a school computer so I think it has something to do with that. My code should work. Thank you for your help.
You need to login to post a reply.