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

2017/3/22

Problems with bullets

macho_horse macho_horse

2017/3/22

#
I have a game where new enemies gradually appear and shoot at you. Each one is identical. I'm having a problem, however, where only the original enemy will fire bullets, and no other enemy will. The bullets fire randomly. The enemy's code looks like this
Actor ninja;
ninja = getOneObjectAtOffset(0, 0, Ninja.class);

int ninX = ((Ninja) getWorld().getObjects(Ninja.class).get(0)).getX();
int ninY = ((Ninja) getWorld().getObjects(Ninja.class).get(0)).getY();

if(Greenfoot.getRandomNumber(500) < 2)
{
            getWorld().addObject(new Bullet(), ninX, ninY);
}
Super_Hippo Super_Hippo

2017/3/22

#
Is the Ninja the enemy? In any case, you should create the bullet from the class which shoots them. Then you can use the getX and getY methods to get to coordinates of the actor which shoots instead of trying to find a Ninja from the world.
danpost danpost

2017/3/23

#
The code is executed for each enemy object. As it executes for each one, the keyword 'this' will refer to the particular enemy object that the code is currently executing for. Therefore:
if (Greenfoot.getRandomNumber(500) < 2)
{
    this.getWorld().addObject(new Bullet(), this.getX(), this.getY());
}
or more simply (since 'this' is implicitly implied when no object is explicitly given to call a method on):
if (Greenfoot.getRandomNumber(500) < 2)
{
    getWorld().addObject(new Bullet(), getX(), getY());
}
You need to login to post a reply.