Public Group

# Finding direction between two points in java

This topic is 4198 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I want to make the enemy shoot the bullet to the player however I am weak in maths and do not know how to get the angle between two points Can anyone help me thx

##### Share on other sites
It depends exactly on how you're storing the positions and may the number of dimensions you're working with. I'll assume you're working in 2D:

#include <cmath>// Gives angle from A to Bfloat angleFrom(int APositionX, int APositionY, int BPositionX, int BPositionY){    int dx = BPositionX - APositionY;    int dy = BPositionY - APositionY;    return atan2(dy, dx);}

Obviously, if you're storing the positions as vectors then you can replace that with something like

#include <cmath>// Gives angle from A to Bfloat angleFrom(Vector2D APosition, Vector2D BPosition){    Vector2D delta = BPosition - APosition;    return atan2(delta.y, delta.x);}

This code is C++, but it should be easily transferrable to Java (just need to find where the atan2 function is located in Java).

##### Share on other sites
Quote:
 Original post by TheUnbeliever// Gives angle from A to Bfloat angleFrom(int APositionX, int APositionY, int BPositionX, int BPositionY){ int dx = BPositionX - APositionY; int dy = BPositionY - APositionY; return atan2(dy, dx);}

Just to be clear, this returns the anticlockwise angle, in radians, subtended from a horizontal line through A (parallel to the x-axis, positively oriented) to the straight line connecting A and B.

##### Share on other sites
Your question implies that you want the computer to calculate a "bullseye" hit for you. Im not sure that is what you want...

If you already have an angle variable in your player object you could simply copy this angle into your bullet object and move it like this (using radians rather that degrees):

bullet.x += cos(bullet.angle) * bullet.velocity
bullet.y += sin(bullet.angle) * bullet.velocity

This will move the bullet in a straight line, no matter if it is a hit or not.

1. 1
Rutin
27
2. 2
3. 3
4. 4
5. 5

• 11
• 9
• 9
• 9
• 14
• ### Forum Statistics

• Total Topics
633312
• Total Posts
3011312
• ### Who's Online (See full list)

There are no registered users currently online

×