So, I have been following tutorials on a Slick API 2D Game Java tutorial, and I got the basics of how to use the API. But then, when I was playing around and trying to make a game. I tried to implement a bullet/firing system into my 2D space shooter game. And I can't seem to find a way to do it!
I've tried looking around on Google and YouTube, but it's not helping at all...! All my game does right now is move a ship right to left. I want to be able to make it so that the a bullet-like object is fired every time the space bar is pressed. I am just not sure how to go about it... I'm hoping someone can explain it simply to a new programmer !
Assuming you're using polling for input, you'll need to add a check to your update
method for the spacebar. If the spacebar is pressed, then add a new instance of Bullet
to an array of bullets and pass the initial x
, y
, and velocity
in the constructor.
Your Bullet
class may look something like:
public class Bullet
{
public static float VELOCITY;
private Vector2f position;
public Bullet(float x, float y, float velocity)
{
position = new Vector2f(x, y);
VELOCITY = velocity;
}
public void update(float delta, boolean vertical)
{
if(vertical)
{
y += VELOCITY * delta;
}
else
{
x += VELOCITY * delta;
}
}
}
You'll also want to call the update method for the bulelts in your update
method. Do this with something like:
for(Bullet bullet : bullets)
{
bullet.update(delta, true);
}