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

2018/1/29

How to make Object turn before touching edge.

Nordine Nordine

2018/1/29

#
I created the following code to make a car go around the scene/world. The car starts from the left, has to turn before touching the right Edge, go down, turn before touching the bottom Edge, and turn again to go up. Somehow I can't get the car to turn and go up. Any help appreciated.
public class Car2 extends Actor
{
    /**
     * Act - do whatever the Car2 wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
 public void act() 
    { move(2);
       //if(getY()>510)
       {
        if(getX()>=510 & getY()<510)
        {
           setRotation(90);
           setLocation(getX(), getY()+1);
        }
         
        if(getY()>510 & getX()>510)
        {
           setRotation(180);
           setLocation(getX()-1, getY());
        }
         
        if(getX()==510 & getY()<510 & getY()>510)
        {
            setRotation(270);
            setLocation(getX(), getY()-1);
        }
            }   
       
   }
}
danpost danpost

2018/1/29

#
Use dual conditions for each turn:
public void act()
{
    move(2);
    if (getRotation() == 0 && getX() >= 510
        || getRotation() == 90 && getY() >= 510
        || getRotation() == 180 && getX() <= 90
        || getRotation() == 270 && getY() <= 90)
            turn(90);
}
Nordine Nordine

2018/1/29

#
Thank you Danpost for the quick reply. I did not think of that one. I appreciate the help.
You need to login to post a reply.