Basically, I'm here to sum it up:
Let's assume you have a player position and a mouse - or better - target position:
1 2
| Vec2 playerPos; Vec2 targetPos; |
's simply store
s.
To get the degree angle between those two vectors:
1 2
| float degrees = Math.toDegrees(Math.atan2(targetPos.x - playerPos.x, targetPos.y - playerPos.y)); |
You can then use the degrees to translate the x and y position of the bullet:
1 2 3 4 5 6
| Vec2 bulletPos; float deltaX = Math.cos(Math.toRadians(degrees)) * speed; float deltaY = Math.sin(Math.toRadians(degrees)) * speed;
|
Finally we can optimize it by removing the
at the atan2 and the
from the sine and cosine.
Now instead of converting from
delta vector -> direction (radians) -> direction (degrees) -> direction (radians) -> delta*, we now do
delta vector -> direction (radians) -> delta*.
Marvel at the mighty code:
1 2 3 4 5 6 7 8 9 10 11 12
| public float getDirectionRad(Vec2 v0, Vec2 v1) { return Math.atan2(v1.x - v0.x, v1.y - v0.y); } float directionInRadians = getDirectionRad(playerPos, targetPos); float deltaX = Math.cos(directionInRadians); float deltaY = Math.sin(directionInRadians); bulletPos.x += deltaX; bulletPos.y += deltaY; |
I hope I summed it up so people understand it
