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

2019/6/6

Asteroids

efe3onYT efe3onYT

2019/6/6

#
I was wondering what the code would be if I wanted a big asteroid to spawn 2 small ones when shot, and a medium spawn 3 small asteroids when shot (all layered on each other)
efe3onYT efe3onYT

2019/6/6

#
@danpost
Super_Hippo Super_Hippo

2019/6/6

#
(I guess the big one is spawning two medium ones and not just two small ones?) You can have a size variable in your asteroid class:
private size; //3=big, 2=medium, 1=small
When creating an Asteroid, you pass the size it should have:
public Asteroid(int type)
{
    size = type;
    GreenfootImage img = new GreenfootImage("Asteroid.png");
    img.scale(size*img.getWidth(), size*img.getHeight()); //just an idea here
    setImage(img);
    setRotation(Greenfoot.getRandomNumber(360));
}
Then you need a method to split the Asteroid. It will spawn two Asteroids with a size one less than its size and then it is removed from the world:
public void damage()
{
    if (--size>0) //prevent spawning of Asteroid when this was already small
    {
        for (int i=0; i<4-size; i++) //4-size means a big one spawn 2 while a medium one spawn 3.
        {
            getWorld().addObject(new Asteroid(size), getX(), getY());
        }
    }
    getWorld().removeObject(this);
}
Then, the only thing which is missing is calling the method when the Bullet is touching it:
public void act()
{
    move(2);
    Asteroid asteroid = (Asteroid) getOneIntersectingObject(Asteroid.class);
    if (asteroid != null)
    {
        asteroid.damage();
        getWorld().removeObject(this);
    }
}
You need to login to post a reply.