Shooting/Moving Towards coordinates?

Hey, I was wondering if anyone could help me with a small problem.

I want to be able to shoot/walk towards a point(in a top-down perspective, as nooby “AI” and to shoot with the mouse), but I’m not sure how to do it.

Could someone please explain it to me? That’d be amazing.

Thanks!

bullet.setX(bullet.getX() + stepSizePerFrame * Math.cos(Math.toRadians(bullet.getAngle())));
bullet.setY(bullet.getY() + stepSizePerFrame * Math.sin(Math.toRadians(bullet.getAngle())));

This shows you how can you can move a bullet with a fixed angle. Same for your character, you just need a dynamic angle, you can change the angle of the character by rotating him (for example let him look at the mouse pointer) then just calculate the angle. For the angle of a bullet you can take the angle of the character, when you press the shoot button.

I use Pythagoras:


float dx = targetX - startX;
float dy = targetY - startY;
double h = Math.sqrt(dx * dx + dy * dy);
float dn = (float)(h / sqrt2);
      
Vector bulletHeading = new Vector(dx / dn, dy / dn, 0);

bulletHeading is the ratio between x- and y-movement for the bullet to approach the target from the start position.

Thanks, this seems semi-simple, except I have no idea how to use a vector. How would one use a vector for movement?

You don’t need no vector.

Important are the ratios or how its called the vector gets.
For horizonzal movement the x-fraction is +1/-1, y-fraction 0, for vertical movement vice versa.
For diagonal movement you get ~0.7 = sqrt(2) for both.

These values are then used to calculate the x and y values for each game loop turn.

Or he can use my approach. He just needs to put the code lines to the game update loop to set the position, and then to read it in the rendering loop.

Well, he needs 2 classes. One for the bullet, one for the character. Each of them needs the x and y value to set the position and the angle. The angle of a bullet is fixed, just take the direction of the character when you shoot. The angle of the character is dynamic. I don’t know how you want to move the character but that’s easy. Just rotate the character by pressing left or right keys or let rotate him by the mouse and calculate the angle. That’s it.