Hi,
Is there a way to set a random angle (either 90, 180, 270, or 0/360) for my worm so that it moves it that direction at start-up but is controlled by the arrow keys afterwards when they are pressed? Possibly something like 'setRotation( Greenfoot.getRandomNumber(4) * 90 );' or a 'switch' statement? Also, where would I put this piece of code? Thanks for the help. My code for the worm class is shown below.
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
public class Worm extends Actor
{
private static final int EAST = 0;
private static final int SOUTH = 90;
private static final int WEST = 180;
private static final int NORTH = 270;
private int counter = 0;
public Worm()
{
GreenfootImage img = new GreenfootImage(Ground.CELL_SIZE,Ground.CELL_SIZE);
img.drawRect(0,0,Ground.CELL_SIZE,Ground.CELL_SIZE);
img.fillRect(0,0,Ground.CELL_SIZE,Ground.CELL_SIZE);
setImage(img);
}
public void act()
{
checkKeys();
moveForward();
changeDirection();
if( atEdgeOfWorld() ) {
getWorld().removeObject(this);
Greenfoot.stop();
}else{
Actor food = getOneIntersectingObject(Food.class);
if(food!=null) {
getWorld().addObject(new Tail(),getX(),getY());
getWorld().addObject(new Food(),Greenfoot.getRandomNumber(40),Greenfoot.getRandomNumber(30));
getWorld().removeObject(food);
}
}
}
public void moveForward()
{
counter++;
if( counter == 3 ) {
move(1);
counter = 0;
}
}
public void checkKeys()
{
if( Greenfoot.isKeyDown("right") ) {
setRotation(EAST);
}
if( Greenfoot.isKeyDown("down") ) {
setRotation(SOUTH);
}
if( Greenfoot.isKeyDown("left") ) {
setRotation(WEST);
}
if( Greenfoot.isKeyDown("up") ) {
setRotation(NORTH);
}
}
private boolean atEdgeOfWorld()
{
return getX()<=-1 || getY()<=-1 || getX()>=getWorld().getWidth()+0|| getY()>=getWorld().getHeight()+0;
}
}
