- 
            
      
        
      
    Star
      
          
          (350)
      
  
You must be signed in to star a gist  - 
              
      
        
      
    Fork
      
          
          (41)
      
  
You must be signed in to fork a gist  
- 
      
 - 
        
Save conorbuck/2606166 to your computer and use it in GitHub Desktop.  
| var p1 = { | |
| x: 20, | |
| y: 20 | |
| }; | |
| var p2 = { | |
| x: 40, | |
| y: 40 | |
| }; | |
| // angle in radians | |
| var angleRadians = Math.atan2(p2.y - p1.y, p2.x - p1.x); | |
| // angle in degrees | |
| var angleDeg = Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180 / Math.PI; | 
Omg thank you!!!
Would love a version of this that has 0 degrees at due north if anyone knows how to do that...
Would love a version of this that has 0 degrees at due north if anyone knows how to do that...
There are probably more elegant solutions to this but I achieved the desired behavior in p5.js using its map function which maps a value from one number range to another with the following syntax map(value, min1, max1, min2, max2)
My updated getAngle() function looks like this:
function getAngle(x1, y1, x2, y2){
  var a = Math.atan2(y2 - y1, x2 - x1) * (180 / Math.PI) + 90;
  a = (a < 0) ? map(a, -90, 0, 270, 360) : a;
  return a;
}The map() function (always handy to have around) works like this under the hood:
function map(value, min1, max1, min2, max2) {
  return min2 + (max2 - min2) * ((value - min1) / (max1 - min1));
}Thanks @timjuedemann but I actually wrote a function for this eventually that allows you to change where zero is, and even calculates distance from cursor to the element too.
Check it out here: https://github.com/funkhaus/fuxt/blob/master/utils/angleDistanceToCursor.js
thank you so much <3