[solved] Java2D Projectile System (Movement logic)

Hey JGO, I’m trying to figure out how to go about firing a projectile from my players position to the coordinates that were tagged when the fire button is pressed.
(Game is static tiles for now, no movement)

I’m not sure about how I should do this so I’m coming here asking for help as I don’t have that much experience with angles/vectors.

I think I’ll be able to figure out the collision, I just need help with the actual logic for moving at an angle :slight_smile:

When fire button is clicked:


public static void update() {

	// firing button is down
	if (leftClickDown){
		// TODO: Implement delay system.
		final int velocity = 5;
		bullets.add(new Bullet(playerX, playerY, mouseX, mouseY, velocity));
	}

	// update every bullet. (Move)
	for (Bullet b : bullets) {
		b.update();
	}
}

Bullet class:


package org.game.core.player;

public class Bullet {

	// actual position of bullet.
	private int x, y;

	// the destination of the bullet.
	private int destinationX, destinationY;

	// handles x/y velocity
	private int velocity;

	public Bullet(int x, int y, int destX, int destY, int velocity) {
		this.velocity = velocity;
		this.x = x;
		this.y = y;
		destinationX = destX;
		destinationY = destY;
	}
	
	public void update() {
		// HERE IS WHAT I NEED TO IMPLEMENT.
	}

}

Thanks for any help/feedback :slight_smile:

Searched “bullet direction”

Some code, some math/programming lessons, good reads either way.


http://www.java-gaming.org/topics/my-bullet-missile-magic-doesn-t-want-to-go-to-mouse-x-y-solved/33905/view.html

Thanks alot!
The first link helped me with everything I needed :3

First there was a bug where if the player moved the bullets would move but I made that integer final so that bugs gone.

I’m getting concurrent modification exceptions now lols, i’ll try and figure it out.
Only adding bullets so far not removing so dunno why.

Thanks <3

Don’t use enhanced for loops and that error should go away.

CopyableCougar4

That fixed it, thanks :slight_smile:

No problem :slight_smile:

I posted a topic about concurrent modification exception a month or so ago.

CopyableCougar4

Although it’s already solved, I’d like to share my 2 cents.

I’d use two vectors, one for the mouse position (in world space if you have a camera) and one for the starting position. Then you subtract the starting position from the mouse position vector, normalize it, and then maybe multiply it with the amount of speed per tick. Then you can add the vector to the current position each tick, and there you go, the bullet will move in the right direction.

Reading about vectors and some other math may help you with this kind of stuff.