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

2016/5/7

Object Movement Help

StoveAteMe StoveAteMe

2016/5/7

#
I'm trying to code the movement for my Alien actor, and they are gonna be placed at the top left of the screen, and when they encounter an edge, (the left and right boundaries, in my situation). Once the objects fulfill my Boolean condition, I want them to move down, turn, and move in the opposite direction of which they were traveling. (Fyi my world size is 600, 400, 1);
public class Aliens extends Actor
{
    /**
     * Act - do whatever the Aliens wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
        public Aliens()
    {
        GreenfootImage image = getImage();
        image.scale(image.getWidth() - 10,  image.getHeight()- 10);
        setImage(image);
    }
    public void act() 
    {
        if(Greenfoot.getRandomNumber(1000) < 3){
           getWorld().addObject(new Rocket(), this.getX(), this.getY());
        }
        move(1);
        if (getX() > 590) {
           turn(90);
           move(2);
           turn(90);
        }
        if (getX() < 10) {
           turn(-90);
           move(2);
           turn(-90);
        
        }
        
    }   
}
The first boolean seems to do its job correctly, with the exception of the objects image being upside down, but when the objects are on the left hand side of the screen, they don't move as I initially want them to. Any assistance would be greatly appreciated.
danpost danpost

2016/5/7

#
Add the alien into the world at an x-coordinate value of 9 or more. Any less and they will jump back and forth between two pixel locations. The same thing will happen if you add them at any value greater than 590. A better way to program this type of movement is by using an instance field of int type for the current direction of movement ('1' for moving right and '-1' for moving left). Then line 18 can be simply:
move(direction);
With the conditions to turn around, you can use the value of the direction with the x-coordinate location together:
if ((getX() >= 590 && direction == 1) || (getX() <= 10 && direction == -1)){
    direction = -direction;
    setLocation(getX(), getY()+2);
}
This could actually be simplified with a little trick:
if ((getX()-300)*direction >= 290)
You need to login to post a reply.