Sign in to follow this  

Finding direction between two points in java

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
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 B
float 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 B
float 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 this post


Link to post
Share on other sites
Quote:
Original post by TheUnbeliever
// Gives angle from A to B
float angleFrom(int APositionX, int APositionY, int BPositionX, int BPositionY)
{
int dx = BPositionX - APositionY;
int dy = BPositionY - APositionY;

return atan2(dy, dx);
}[/code]

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.

Admiral

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this