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

2019/6/6

Only getRandomNumber Once

ButerWarior ButerWarior

2019/6/6

#
I'm here creating a game very similar to galaxy attack, and I just finished creating the explosion animation when a monster is killed. Now, I'm trying to let it drop a powerup by a 10% chance when its hp==0, but sometimes it would drop a ton at once. I suspected that this was because there is no delay to the Greenfoot.getRandomNumber and it repeatedly gets a random number. Here is my code for the monsters:
    int hp = 10;
        public void collisionWithLaser()
    {
        hp = hp - 1;
    }
    private static  GreenfootImage[] explosionImages = new GreenfootImage[16];
    static
    {
        for (int i=1; i<explosionImages.length+1; i++)
        {
            explosionImages[i-1] = new GreenfootImage("explosion"+i+" img.png");
        }
    }
    private int explosionTimer = -1; //-1 = not active
    public void startExplosion()
    {
        if (explosionTimer < 0) explosionTimer = 0;
    }
    public void act()
    {
        Actor laser;
        if (!getObjectsInRange(40, laser.class).isEmpty())
        {
            collisionWithLaser();
            getWorld().removeObject(getObjectsInRange(40,laser.class).get(0));
        }
        if(hp==0)
        {
            startExplosion();
            Greenfoot.getRandomNumber(11);
            if(Greenfoot.getRandomNumber(11)==1)
            {
                powerups powerups =new powerups();
                getWorld().addObject(powerups, getX(), getY());
            }
        }
        if (explosionTimer > -1)
        {
            if (explosionTimer == explosionImages.length)
            {
                getWorld().removeObject(this);
                return;
            }
            setImage(explosionImages[explosionTimer++]);
            return;
        }
        if (!getObjectsInRange(100, spaceship.class).isEmpty())
        {
            getObjectsInRange(100, spaceship.class).get(0);
            startExplosion();
        }
    }
Super_Hippo Super_Hippo

2019/6/6

#
You could move lines 27-36 to after 46. If you don't mind the power up to spawn after the explosion is gone, you could move lines 31-35 to right before 41 instead.
ButerWarior ButerWarior

2019/6/6

#
Those methods didn't seem to work for me, but I found a solution. All I had to do was make a powerup dissappear if they overlap.
ButerWarior ButerWarior

2019/6/7

#
Nvm, the overlap thingy didn't work either
danpost danpost

2019/6/7

#
Too be sure, the powerups class should extend Actor. Also, you could add an additional condition to spawn a powerups object, namely: if (getWorld().getObjects(powerups.class).isEmpty() && Greenfoot.getRandomNumber(11) == 1)
You need to login to post a reply.