Minimalist Semantic Markup

Welcome Guest
Please Login or Register

If you have registered but not recieved your activation e-mail in a reasonable amount of time, or have issues with using the registration form, please use our Contact Form for assistance. Include both your username and the e-mail you tried to register with.

Author Topic: JavaScript: distance and angle between two points  (Read 572 times)

Jason Knight

  • Administrator
  • Hero Member
  • *****
  • Posts: 919
  • Karma: +171/-1
    • CutCodeDown -- Minimalist Semantic Markup
JavaScript: distance and angle between two points
« on: 24 Oct 2019, 07:59:28 pm »
It's actually funny how much this comes up when people message me directly for help. Usually it's for between a fixed point in the document or in the canvas and the mouse.

You know that geometry and trigonometry you always thought would be useless in high school? Yeah, that.

Code: [Select]
function vectorBetween(point1, point2) {
result = {
distanceX = point2.x - point1.x,
distanceY = point2.y - point1.y
result.distance = Math.sqrt(
result.distanceX * result.distanceX +
result.distanceY * result.distanceY
result.angle = Math.atan2(result.distanceX, result.distanceY);
return result;

Assuming your "points" are an object of { x, y }. YES, I know that technically the points are vectors, but "normal" people know them as points so I wrote it for the normies, not those of us who know how to use the terminology correctly... because the correct terminology scares the straights.

Oh and the angle is in radians, since that's what's useful for Math.sin and Math.cos. If you need it in degrees, add a line before the return reading:

Code: [Select]
result.degrees = result.angle * 180 / Math.PI;

Arctangents are your friend.

I actually use them in OpenGL / Vulcan programming for manual projections rather than dividing by "z". You lose hardware projection handling, but gain a lot more control over FOV -- to the point you can do a 360 degree projection with ease to any render target. "The ultimate fisheye".
I'll fix every flaw, I'll break every law, I'll tear up the rulebook if that's what it takes. You will see, I will crush this cold machine.


SMF spam blocked by CleanTalk