开发者

Getting screen coordinates based on triangles

开发者 https://www.devze.com 2023-02-06 09:07 出处:网络
If I have the length of the hypotenuse and its angle, how do I find the adjacent and opposite? I\'m writing this in JavaScript and I\'m just trying to find the screen coordinates (x/y) where the hypo

If I have the length of the hypotenuse and its angle, how do I find the adjacent and opposite?

I'm writing this in JavaScript and I'm just trying to find the screen coordinates (x/y) where the hypotenuse ends given a length and angle. So, additionally, I need to know how to convert from a cartesian coordinates to screen coordinates.

Sorry, this is probably 开发者_JAVA技巧a pretty dumb question.

Here is a sketch if I'm being unclear:

Getting screen coordinates based on triangles

So something like this:

function getLineEndCoords(originX, originY, hypotenuse, angle){
    // Probably something to do with tangents and cosines.
    return [x,y]
}

Additionally, if anyone knows any good JS libraries for this sort of stuff (isometric drawings, display related math) that would be convenient.


Using soh cah toa:

sin(A) = o/h
cos(A) = a/h

therefore:

x = hypotenuse*sin(angle) + origionX
y = hypotenuse*cos(angle) + origionY

It is usually easier to memorise that one axis is the sine of the angle multiplied by the length, and the other is the cosine of the angle times the length.

EDIT:

Sorry, I forgot to include adding the origin.


Here you go:

function getLineEndCoords(originX, originY, hypotenuse, angle){
  return [originX+Math.cos(angle)*hypotenuse,originY-Math.sin(angle)*hypotenuse];
  }

The code above has angle relative to the right x axis (as was in your sketch). For example, angle 0 would be number 3 on a clock. Angle PI/2 in radians (90 in degrees) would be 12 o'clock. The function also returns the coordinates as screen coordinates, where Y increases as you go down, not up as on a Cartesian plane.

Please note that the javascript trigonometry functions only accept radians, not degrees. Your angle argument must be in radians. Here is the code to convert from degrees to radians:

function deg2rad(deg){
  return deg*Math.PI/180;
  }
0

精彩评论

暂无评论...
验证码 换一张
取 消