Greenfoot

Simple Movement

if (Greenfoot.isKeyDown("up"))
{
    move(3);
}

Turning

if (Greenfoot.isKeyDown("left"))
{
    turn(-3);
}

Random Movement

This code tells a character to move and turn occasionally.

move(1);
if (Greenfoot.getRandomNumber(10) ==1) if a random number between 1 and 10 is 1
{
     turn(Greenfoot.getRandomNumber(360));turn a random amount
}

This code tells the character to bounce off the edges.

Bouncing

Alternative Movement

Sometimes you may want the character to move up/ down/ left and right without turning. To do this we use the setLocation function.

The setLocation function simply requires the 2 coordinates – x and y. Normally it looks like this:

setLocation(5,3)

However, we must first get the x and y coordinates using getX()and getY(). We can insert these into the function like this: setLocation(getX(),getY())

This sets the location as the current location.Alt Movement

To move right, simply add 1 to x:

setLocation(getX()+1,getY())

To move down, simply add 1 to y:

setLocation(getX(),getY()+1)

Collision Detection & Sound

Add this to the character that is destroying/ eating other characters

Actor collide; You first create an actor called collide (or other suitable name)
collide = getOneIntersectingObject(Asteroid.class);  get the intersecting object 
if(collide != null) if collide is not equal to nothing
{
     getWorld().removeObject(collide); In the current world, remove collide
     Greenfoot.playSound("Explosion.wav"); play sound

}

Counter

1 Import a new counter

2 Add the code –  the code should be added inside the if statement

((Counter)getWorld().getObjects(Counter.class).get(0)).add(1);

Counter
Advertisement
%d bloggers like this: