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

2015/5/10

How to stop Actors moving off the world?

Adam2323 Adam2323

2015/5/10

#
In my World, I put (600,400,1,false), so that actors can move off the edge of the world. (For example)
public AvoiderWorld()
    {    
        super(600, 400, 1, false); 
        prepare();
    }
Is there a way to stop certain actors from moving off the edge? (An actor called Avatar needs to be unable to move off the edge., but an actor called Enemy needs to be able to do it.)
danpost danpost

2015/5/10

#
At the end of the act method in the Avatar classes, check the location to see if it may be off any edge and adjust if needed.
Adam2323 Adam2323

2015/5/10

#
This is my code for the Avatar. What code do I put in and where?
import greenfoot.*;
public class Avatar extends Actor
{
    public void act() 
    {
        hitDetection();
        moveOnKeyPress();
    }    
    public void moveRight()
    {
        int x = (getX() + 5);
        int y = (getY());

        setLocation(x, y);
    }
    public void moveLeft()
    {
        int x = (getX() - 5);
        int y = (getY());
        setLocation(x, y);
    }
    public void moveOnKeyPress()
    {
        if(Greenfoot.isKeyDown("left")) {
            moveLeft();
        }
        if(Greenfoot.isKeyDown("right")) {
            moveRight();
        }
    }
    public void hitDetection()
    {
        Actor enemy; 
        enemy = getOneIntersectingObject(Enemy.class);
        if(enemy != null)
        {
            AvoiderWorld world = (AvoiderWorld)getWorld();
            world.endGame();
        }
        Actor enemy2;
        enemy2 = getOneIntersectingObject(Enemy2.class);
        if(enemy2 != null)
        {
           AvoiderWorld world = (AvoiderWorld)getWorld();
            world.endGame();
        }
        Actor enemy4;
        enemy4 = getOneIntersectingObject(Enemy4.class);
        if(enemy4 !=null)
        {
          AvoiderWorld world = (AvoiderWorld)getWorld();
            world.endGame();
        }
    }   
}
danpost danpost

2015/5/10

#
Inserted at line 19 in the 'moveLeft' could be:
if (x < 5) x = 5;
and similar code could be used in the 'moveRight' method.
Adam2323 Adam2323

2015/5/10

#
What should I put for moveRight? I tried:
 if(x <395) x = 395;
but the Actor just teleports to the right.
danpost danpost

2015/5/10

#
Adam2323 wrote...
What should I put for moveRight? I tried:
 if(x <395) x = 395;
but the Actor just teleports to the right.
Look at the condition you are using. You do not need to adjust the location if less than 395, but if greater than 395.
Adam2323 Adam2323

2015/5/10

#
Ohhhhh thank you :) It all works now.
You need to login to post a reply.