[JAVA]Bullet shooting logic

How do I make a bullet move upward from the player position from when the key spacebar is pressed. I set up a bullet class that holds an image. in my class extending JPanel or canvas that actually draws it, how do I make a for loop or whatever else you use for drawing it.

Basicly help me understand how bullet logic works and how you use it

I don’t remember much Java2D, but the concept is easy to understand.

So basically, you have two methods called inside your bullet code each loop.

  • Render - Sets image location, draws the image
  • Update - Updates the image location relative to whatever. (Handles calculations for bullet speed, and stuff).

So lets start on the Bullet class
(Were using floats because their just numbers, but with decimal points)

public class Bullet {
     public float x, y; //Adds two coordinates; X and Y
     public float bulletSpeed = 0.5f;
}

Then we call this from our bullet class each loop

public void render (Graphics g){
     g.drawImage(bulletImage, x, y); //Draw an image 
}

Then put this under render inside of our loop.

public void update(){
     y += bulletSpeed;
}

Remember, I dont really remember how your java2D works, but heres how to make it into a loop.

public Bullet bullet = new Bullet();
public void loopGame(Graphics g){
     bullet.render(g);
     bullet.update();
}

Oh so I had the right idea