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

2014/11/29

Spawning cars that travel across the world left and right?

DiplomatikCow DiplomatikCow

2014/11/29

#
I need to spawn cars at two locations, one on the left side, and the other on the right side. There is two lanes, so Y coordinate varies. They, of course, need to drive to the opposite side of the screen. Please help.
public class Car extends Actor
{    
    private GreenfootImage car1 = new GreenfootImage("car01.png");
    private GreenfootImage car2 = new GreenfootImage("car02.png");
    private GreenfootImage car3 = new GreenfootImage("car03.png");
    private int speed = 4;
    int whichImage;
    int direction;
    public Car()
    {
        whichImage = Greenfoot.getRandomNumber(100);
        if(whichImage<33)
        {
            setImage("car01.png");
        }else if(whichImage<66)
        {
            setImage("car02.png");
        }else if(whichImage<100)
        {
            setImage("car03.png");
        }
    }
    public void act()
    {
        setLocation(getX()+speed, getY());
        if(isAtEdge())
        {
            getWorld().removeObject(this);
        }
    }
}
That was the Car class, and here is the World class:
public class Road extends World
{
    Scoreboards scoreboards = new Scoreboards();
    public Road()
    {    
        super(800, 600, 1); 
        addObject(scoreboards, 75, 550);
        addObject(new MotherShip(), getWidth()/2, 500);
        addObject(new Greep(), 300, 500);
        addObject(new Tomato(), 100, 55);
        addObject(new Tomato(), 250, 112);
        addObject(new Tomato(), 400, 74);
        addObject(new Tomato(), 550, 143);
        addObject(new Tomato(), 700, 89);
        setPaintOrder(Car.class, Greep.class, Tomato.class, MotherShip.class, Scoreboards.class, Road.class);
    }
    public Scoreboards getScoreboards()
    {
        return scoreboards;
    }
    public void addACar()
    {
        if(Greenfoot.getRandomNumber(100)<50)
        {
            addObject(new Car(), 25, 265);
        }else
        {
            addObject(new Car(), 745, 360);
        }
    }
}
danpost danpost

2014/11/29

#
Where is 'addACar' called from? In the Car class, line 6 gives all cars a speed of 4 and line 25 will make all of them go to the right. You will probably want those cars spawned on the right that move left to be facing left (or rotated to face left). When the rotation matches the direction of movement, it is usually better to use 'move(int)' instead of 'setLocation(int, int)'. There are two places where you can rotate those cars spawned on the right. One is when you create the car (in the world class) and the other is when it is added into the world (in the car class).
You need to login to post a reply.