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

2015/10/2

Moving worms "up" or "down" on keyboard

Mack Mack

2015/10/2

#
So I'm using the scenario little-crab 5 and I need to give the worms a chance to survive. I need to have the worms respond to the "up" and "down" arrow keys on the keyboard by moving the worms up or down a random number of steps between 0-3 This is the code I have for the worm already but I don't know what I'm doing wrong because the worms aren't responding to "up" or "down" PLEASE HELP
/**
 * Worm. A sand worm. Very yummy. Especially crabs really like it.
 */
public class Worm extends Actor
{
    public void act()
    {
    
    if ( isAtEdge() )
      {  turn(3);
        }
      
        if ( Greenfoot.getRandomNumber(100) < 10)
      {
          turn(Greenfoot.getRandomNumber(60) - 18);
         
    }
    move(3);
    
}



public void checkKeypress()
    {
        if (Greenfoot.isKeyDown("down")) 
        {
            turn(-3);
        }
        if (Greenfoot.isKeyDown("up")) 
        {
            turn(3);
        }
    }
}

letin letin

2015/10/3

#
Try this. Hopefully it helps! /** * Check whether there are any key pressed and react to them. */ public void checkKeypress() { if(Greenfoot.isKeyDown("up")) { setLocation(getX(),getY()-Greenfoot.getRandomNumber(3)); } if(Greenfoot.isKeyDown("down")) { setLocation(getX(),getY()+Greenfoot.getRandomNumber(3)); } }
Mack Mack

2015/10/3

#
Thank you so much Letin!!!! I have another question..... Would you also know how to make the crab play a sound when he turns more than 18 degrees??
You need to login to post a reply.