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

2017/12/9

how to make space for automatic shooting

kogen kogen

2017/12/9

#
how to make space for automatic shooting
Super_Hippo Super_Hippo

2017/12/9

#
Basic code:
if (Greenfoot.isKeyDown("space"))
{
    Bullet b = new Bullet(); //create a new bullet
    getWorld().addObject(b, getX(), getY()); //add the bullet at the position of the shooting object
    b.setRotation(getRotation()); //set the bullet's rotation the the shooter's rotation
    b.move(5); //move it a little bit so the bullet does not start in the middle of the shooter
}
You will notice that it will constantly shoot when you press space. To avoid that, you need a timer.
private int shootDelay=20, shootTimer=0;

//...
if (--shootTimer<1 && Greenfoot.isKeyDown("space"))
{
    shootTimer = shootDelay;
    //rest of code above
}
You need to login to post a reply.