Calculating degrees between 2 points with inverse Y axis

前端 未结 4 1242
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-31 17:45

I\'m creating a simple 2D game in javascript/canvas. I need to figure out the angle of a certain object relative to my position.

So: say I\'m at (10,10) and the object i

4条回答
  •  难免孤独
    2021-01-31 18:40

    If your coordinates are (xMe, yMe) and their coordinates are (xThem, yThem), then you can use the formula:

    arctan((yMe-yThem)/(xThem-xMe))

    Normally it'd be arctan((yThem-yMe)/(xThem-xMe)), but in this case the sign of the y-axis is reversed.

    To convert the result from radians to degrees multiply by 180/pi.

    So in JavaScript, this would look like: Math.atan((yThem-yMe)/(xThem-xMe))*180/Math.PI

    atan gives a value between -pi/2 and pi/2 (that is, between -90 and 90 degrees). But you can look at what quadrant your (xThem - xMe, yMe - yThem) vector is in and adjust accordingly.

提交回复
热议问题