+ 1
How to get angle of a line between two points? (Javascript)
Привет, I have been playing around making little games in JavaScript, and one I have made is a 2d battle game. While it functions well, I would like to be able to implement trigonometry (or whatever the line maths is called) to make items turn towards the location they are moving. Since I have the location of the item (x and y ) as well as where it is moving (x and y), I know there is some way I can calculate the angle that the line between the two items creates. Does anyone have a tutorial or knowledge of how to calculate this stright line's angle (in radiants or degrees is fine since I can convert)? (I'm using canvas btw but I assume this maths would work with any program thing)
2 Respostas
+ 11
I received a message saying this post does not look like it has an explanation and it looks like SPAM so it will be deleted...so now I am editing to add an explanation...albeit, if you know JavaScript, this should be self-explanatory...it's 2 lines...1) a function to calculate the angle between to two point, and 2) a command demonstrating the function by sending parameters to it and printing the result.
/**
* angle2P - Returns angle between two points.
*
* @param {Object} p1 Object with x & y property for numeric values of the Cartesian coordinate for point 1.
* @param {Object} p2 Object with x & y property for numeric values of the Cartesian coordinate for point 2.
* @return {Number} Angle, in degrees, between p1 & p2.
*/
const angle2P = (p1, p2) => Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180 / Math.PI
console.log(angle2P({ x: -3, y: 5 }, { x: 6, y: -1 }));
// -33.690067525979785
0
Thank you, this theorem works but my thing doesn't so it must be another problem of mine I didn't notice