Question

I'm making a game where you have a sprite that shoots bullets in the direction of the mouse. So far, it works fine with 1 bullet. I have this method that gets a slope, and then normalizes the vector:

    public static Vector2f getSimplifiedSlope(Vector2f v1, Vector2f v2) {
    Vector2f result = new Vector2f(v2.x - v1.x, v2.y - v1.y);
    float length = (float)Math.sqrt(result.x * result.x + result.y * result.y);

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

However, now I'm making a shotgun that fires several bullets, with a "spread". My plan is, I'll take the base slope, convert it to degrees, add or subtract a couple to create a deviation, then convert the degrees back to a slope, and pass it to the bullet.

However, I don't know how to do this. It'd be great if someone could show me how to convert a 2D slope to degrees, and vice versa.

Thanks in advance!

Was it helpful?

Solution

The simplest way is to use the trigonometry method Math.atan2 to compute the angle in radians, convert it to degrees with Math.toDegrees, perform your adjustment, convert it back to radians with Math.toRadians, then use the trigonometry method Math.tan to convert a radian value back to a slope. You'll want to watch out for a potentially infinite slope coming back from the tan method.

Here's the Javadocs on the Math class.

OTHER TIPS

Use Math.atan2(), and remember that the result is in radians, not in degrees.

Math.atan2() will do this and give you the result in radians.

Returns the angle theta from the conversion of rectangular coordinates (x, y) to polar coordinates (r, theta). This method computes the phase theta by computing an arc tangent of y/x in the range of -pi to pi.

Math.toDegrees() will perform your radian/degree conversion.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top