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

2015/5/26

falling randomly

laettney laettney

2015/5/26

#
does anyone know how to make an object fall randomly? Like I'm making a game and I want stuff to move down randomly
Super_Hippo Super_Hippo

2015/5/26

#
What is meant with 'move down randomly'? Should it spawn at a random position (right to left) on top and fall down?
laettney laettney

2015/5/26

#
yes. Like I just want it to be able to fall down randomly. My teacher says that it needs to be one object, and that object needs to generate itself so it can become more than one. I don't know if that make sense...
Super_Hippo Super_Hippo

2015/5/26

#
I think your teacher means that it needs to one class. Let's say the object which is falling down is a Block. In your world subclass:
public void WorldName()
{
    //add this 'false', so objects can be outside the world boundaries
    super(/*x*/, /*y*/, 1, false);
}

public void act()
{
    if (Greenfoot.getRandomNumber(100)) 
    {
        addObject(new Block(), 5+Greenfoot.getRandomNumber(getWidth()-6), -5);
    }
}
In the Block class:
public Block()
{
    GreenfootImage img = new GreenfootImage(11,11);
    img.fill();
    setImage(img);
}

public void act()
{
    setLocation(getX(), getY()+1); //higher number = faster falling
    if (getY() > getWorld().getHeight()) removeObject(this);
}
You need to login to post a reply.