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

2013/2/3

Still and Moving Objects

Gingervitis Gingervitis

2013/2/3

#
Is there a way I could have a still object move after it eats something? For example I want my rocket to stay still when it spawns, but when it eats my turtle, it will move vertically upward towards the top edge as if the turtle is riding the rocket.
public void act()   
    {  
        ifCanSeeTurtle();  
    }      
      
    public void ifCanSeeTurtle()  
    {  
        if (canSee(Turtle.class))  
        {  
            eat(Turtle.class);  
            setImage("rocketCopy02.png");  
            move(4);  
        }  
    }
This is what I have so far, but it doesn't work.
danpost danpost

2013/2/3

#
In most cases, anytime there is an option between two choices (in this case, 'sit still' or 'move'), you should add a boolean field to the class to indicate which is currently chosen. Here, you can call it something like 'moving'.
private boolean moving; // defaults to initial state of 'false'

public void act()
{
    if (!moving) ifCanSeeTurtle(); else move(4);
}

public void ifCanSeeTurtle()
{
    if (canSee(Turtle.class))
    {
        eat(Turtle.class);
        setImage("rocketCopy02.png");
        moving=true;
    }
}
Gingervitis Gingervitis

2013/2/3

#
Ok. I did that and it worked, but it made my rocket move horizontally. How could I make it move vertically upward?
danpost danpost

2013/2/3

#
Since you are using 'move', the object must face the direction you want it to proceed. Therefore, you need to turn the object before moving it and then turn it back each act cycle.
public void act()
{
    if (!moving)
    {
        ifCanSeeTurtle();
    }
    else
    {
        setRotation(270);
        move(4);
        setRotation(0);
    }
}
As an alternative, you could use 'setLocation(getX(), getY()-4);' instead of 'rotate-move-rotate'.
Gingervitis Gingervitis

2013/2/3

#
Thank you!
You need to login to post a reply.