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

2017/4/22

Splitting objects, creating new objects when others are destroyed?

icantstudy995 icantstudy995

2017/4/22

#
I am working on an asteroids game and I would like my asteroid to split, creating two smaller asteroids when it gets hit by a bullet. I am stumped because in my code, the bullet gets destroyed when it hits an asteroid and an asteroid gets destroyed when it gets hit by a bullet. If I put my addObject code into Actor Asteroid, my game gets stuck because it doesn't know where to create it. In my act method for Bullet class, I have
if(foundAsteroid()) {
           destroyAsteroid();           
            }   
    public boolean foundAsteroid() {
        Actor asteroid = getOneObjectAtOffset(0, 0, Asteroid.class);
        if(asteroid != null) {
            return true;
        }
        else {
            return false;
        }
        }
        
    public void destroyAsteroid() {
        Actor asteroid = getOneObjectAtOffset(0, 0, Asteroid.class);
        if(asteroid != null) {
            int x = getX();
            int y = getY();
            Actor smallAsteroid1 = new SmallAsteroid();
            getWorld().addObject(smallAsteroid1, x, y);
            Actor smallAsteroid2 = new SmallAsteroid();
            getWorld().addObject(smallAsteroid2, x, y);    
            getWorld().removeObject(asteroid);
        }
    }    
Any ideas why it isn't working and how I can fix this? Thanks in advance.
danpost danpost

2017/4/22

#
Only have one of the two objects detect collision with the other. Remove both at the same time AFTER creating and adding the smaller asteroids into the world.
icantstudy995 icantstudy995

2017/4/22

#
How do I create and add smaller asteroids before destroying the big one and the bullet? // edit I fixed it by switching around the line order. Thanks alot!!
You need to login to post a reply.