Finding direction between two points in java

Started by
2 comments, last by pulpfist 16 years, 11 months ago
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
Advertisement
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).
[TheUnbeliever]
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);
}

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
Ring3 Circus - Diary of a programmer, journal of a hacker.
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.

This topic is closed to new replies.

Advertisement