This site requires JavaScript, please enable it in your browser!
Greenfoot back
d4|\|i31
d4|\|i31 wrote ...

2013/5/5

Moving one actor on the x-axis for- and backwards

d4|\|i31 d4|\|i31

2013/5/5

#
Hi everybody, i want to make an actor move on the x-axis 163 steps for- and backwards, but i dont know how to do it. First i tried it this way:
int steps = 0;
long lastAdded = System.currentTimeMillis();  
  
    public void act()  
    {  
        long curTime  = System.currentTimeMillis();  
        if (curTime >= lastAdded + 5){//5000ms = 5s  
            setLocation(getX()+1, getY());
            steps ++;
        if (schritte == 163){
            while (schritte >=0){
                if (curTime >= lastAdded + 5){
                steps--;
                setLocation(getX()-1, getY());
                lastAdded = curTime;
            }
           }
        }
        lastAdded = curTime;
    }  
}
But every time he reaches the 163 steps Greenfoot crashes. I just want him to move slowly on this line. Anybody who can help me?
d4|\|i31 d4|\|i31

2013/5/5

#
Sorry, made a mistake in the first code, translated the variables from German and forgot one:
int steps = 0;
long lastAdded = System.currentTimeMillis();  
  
    public void act()  
    {  
        long curTime  = System.currentTimeMillis();  
        if (curTime >= lastAdded + 5){
            setLocation(getX()+1, getY());
            steps ++;
        if (steps == 163){
            while (steps >=0){
                if (curTime >= lastAdded + 5){
                steps--;
                setLocation(getX()-1, getY());
                lastAdded = curTime;
            }
           }
        }
        lastAdded = curTime;
    }  
}
danpost danpost

2013/5/5

#
The 'act' method will create the loop for you. All you need to do is count to 163 and turn around to move back. The following code presumes the actor starts at the left-most position.
int steps = 0;
int direction = 1;

public void act()
{
    if ((steps == 163 && direction == 1) || (steps == 0 && direction == -1))
    { // when set to move past either end
        direction = -direction; // change direction
    }
    setLocation(getX()+direction,, getY()); // move
    steps = steps + direction; // adjust step count
}
d4|\|i31 d4|\|i31

2013/5/5

#
Thank you, danpost! You are my hero of the day! I have to finish this game until tomorrow and didn't had figured it out until now! :) Thanks you a lot!
You need to login to post a reply.