Question

I'm making pretty simple game. You have a sprite onscreen with a gun, and he shoots a bullet in the direction the mouse is pointing. The method I'm using to do this is to find the X to Y ratio based on 2 points (the center of the sprite, and the mouse position). The X to Y ratio is essentially "for every time the X changes by 1, the Y changes by __".

This is my method so far:

public static Vector2f getSimplifiedSlope(Vector2f v1, Vector2f v2) {
    float x = v2.x - v1.x;
    float y = v2.y - v1.y;

    // find the reciprocal of X
    float invert = 1.0f / x;
    x *= invert;
    y *= invert;

    return new Vector2f(x, y);
}

This Vector2f is then passed to the bullet, which moves that amount each frame.

But it isn't working. When my mouse is directly above or below the sprite, the bullets move very fast. When the mouse is to the right of the sprite, they move very slow. And if the mouse is on the left side, the bullets shoot out the right side all the same.

When I remove the invert variable from the mix, it seems to work fine. So here are my 2 questions:

  1. Am I way off-track, and there's a simpler, cleaner, more widely used, etc. way to do this?
  2. If I'm on the right track, how do I "normalize" the vector so that it stays the same regardless of how far away the mouse is from the sprite?

Thanks in advance.

Was it helpful?

Solution

Use vectors to your advantage. I don't know if Java's Vector2f class has this method, but here's how I'd do it:

return (v2 - v1).normalize(); // `v2` is obj pos and `v1` is the mouse pos

To normalize a vector, just divide it (i.e. each component) by the magnitude of the entire vector:

Vector2f result = new Vector2f(v2.x - v1.x, v2.y - v1.y);
float length = sqrt(result.x^2 + result.y^2);

return new Vector2f(result.x / length, result.y / length);

The result is unit vector (its magnitude is 1). So to adjust the speed, just scale the vector.

OTHER TIPS

Yes for both questions:

  • to find what you call ratio you can use the arctan function which will provide the angle of of the vector which goes from first object to second object
  • to normalize it, since now you are starting from an angle you don't need to do anything: you can directly use polar coordinates

Code is rather simple:

float magnitude = 3.0; // your max speed
float angle = Math.atan2(y,x);
Vector2D vector = new Vector(magnitude*sin(angle), magnitude*cos(angle));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top