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

2018/10/23

how to make actor keep walking on a square?

jc5879 jc5879

2018/10/23

#
This is a code, but I don't know how to fix it. /** * A boy who is supposed to walk on a square. */ public class Boy extends Actor { private int steps; private int edgeLength; // The length of the sides on the square public Boy(){ steps = 0; edgeLength = 100; } public void act() { if (steps == edgeLength){ setRotation(getRotation()+90); } else{ moveForward(); steps++; } } public void moveForward(){ int rotation = getRotation(); if (rotation == 0){ setLocation(getX() + 1, getY()); } else if (rotation == 90){ setLocation(getX(), getY()+1); } else { setLocation(getX() - 1, getY()); } } }
danpost danpost

2018/10/23

#
A couple of things about your current code. First, you are only showing movement in 3 directions -- not 4 (missing "up"). Then, the value of steps is only incremented -- it is only going to be equal to edgeLength once. So, reset it to zero when turning and add the other movement direction (or, instead of moveForward(); use move(1); (in act method) and remove the moveForward method.
jc5879 jc5879

2018/10/23

#
    private int steps;
    private int edgeLength; // The length of the sides on the square

    public Boy(){
        steps = 0;    
        edgeLength = 100;
    }

    public void act() 
    {

        if (steps == edgeLength){
            setRotation(getRotation()+90);
        }
        else{
            move(1);
            steps++;
        }
    }    

    public void move(){
        int rotation = getRotation();
        if (rotation == 0){ 
            setLocation(getX() + 1, getY());
        }
        else if (rotation == 90){
            setLocation(getX(), getY()+1);
        }
        else if (rotation == -90){
            setLocation(getX(), getY()-1);
        }
        else {
            setLocation(getX() - 1, getY());
        }
    }
}
like this way?
danpost danpost

2018/10/23

#
jc5879 wrote...
<< Code Omitted >> like this way?
You got the 4th direction in; but, you still need to reset steps to zero when turning. There is also now a problem that getRotation returns a value between 0, inclusive, and 360, exclusive. It will never be -90, as your new condition compares it to.
You need to login to post a reply.