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

2015/10/29

i need help with having my actor move along the y axis continuously

nobody123 nobody123

2015/10/29

#
import greenfoot.*;

public class L1 extends Lighthouse
{
    
    public void act() 
    {
       
        int direction = 1;
        if(getY() < 550  && direction == 1)
        {
            moveDown();
        }
        
        else
        
        if(direction == 0)
        {
            moveUp();
        }
    }
    
    public void moveUp()
    {
        setLocation(getX(), getY() - 2);
    }
    
    public void moveDown()
    {
        setLocation(getX(), getY() + 2);
    }
 }  
danpost danpost

2015/10/29

#
Let us start with line 9. It does the following: * declares an int variable named 'direction' * is assigned a value of one * its value is never changed after being initially set * its scope only lasts for as long as the method is executing With the above information on the variable, the act method given is equivalent to the following:
public void act()
{
    if (getY() < 550) moveDown();
}
To elaborate on the 'direction' variable. Each time the act method is executed, a new 'direction' variable is declared and its value is set to one. Its value is accessible only for as long as the method is executing. Each time the act method is exited, the variable declared during that execution of the method is lost. To have the value be maintained from one act cycle to the next, it must be declared outside the method (move line 9 to line 5). Then, you must change its value when the right conditions are met and use its value in determining whether to move up or down.
You need to login to post a reply.