Get angle in terms of 360 degrees - javascript

I would like to get an angle in terms of 360 degrees... for my game, I need to know which direction the player is heading in...
The code here gets the proper angles, but only in terms of 90 degree increments: (meaning, when I click in upper left quadrant, I get angle from 0 to 90 degrees... bottom left is 0 to -90 degrees, etc...)
var dY = this.pos.y-e.gameY; //opposite
var dX = this.pos.x-e.gameX; //adjacent
var dist = Math.sqrt((dY*dY)+(dX*dX)); //hypotenuse
var sin = dY/dist; //opposite over hypotenuse
var radians = Math.asin(sin);
var degrees = radians*(180/Math.PI); //convert from radians to degrees
this.calculatedAngle = degrees;
How can I get it in terms of 360 degrees?
Here is another example: The top two represent the issue... when I click in the upper/lower left quadrant, it keeps drawing a right triangle from the x axis...
I need it to be like the lower 2 pictures, where it keeps drawing the angle around:

You can do this directly from the coordinates, without computing extra information like the hypotenuse, by using the atan2 function, which was designed in the early days of FORTRAN for situations exactly like yours.
Note two important things:
that the atan2 function has been created to automatically handle all but one case of the many possible cases, and
it will output a range of (-PI, PI].
The case where both coordinates are (0, 0) is left undefined (all angles are equivalent when the magnitude of a vector is zero), so I'm arbitrarily setting the angle to zero degrees in that case. And in order to obtain the desired range, some simple logic and addition is needed.
var Vx = this.pos.x - e.gameX;
var Vy = this.pos.y - e.gameY;
var radians;
if (Vx || Vy) {
radians = Math.atan2(Vy, Vx);
} else {
radians = 0;
}
if (radians < 0) {
radians += 2*Math.PI;
}
var degrees = radians * 180 / Math.PI;
this.calculatedAngle = degrees;
The result will be an angle defined for all cases and within the range [0, 360°), as desired.
Example
function showDegrees(e, svg) {
var rectangle = svg.getBoundingClientRect();
var targetX = (rectangle.left + rectangle.right)/2;
var targetY = (rectangle.top + rectangle.bottom)/2;
var Vx = Math.round(e.clientX - targetX);
var Vy = Math.round(targetY - e.clientY);
var radians = Math.atan2(Vy, Vx);
if (radians < 0) radians += 2*Math.PI;
var degrees = Math.round(radians*180/Math.PI);
var textBox = document.getElementById('showdegrees');
textBox.innerHTML = degrees + '°' + ' (' + Vx + ', ' + Vy + ')';
textBox.setAttribute('x', Math.round(100 + Vx));
textBox.setAttribute('y', Math.round(100 - Vy));
}
<svg width="200" height="200" viewBox="0 0 200 200" onmousemove="showDegrees(evt, this)">
<text x="0" y="0" fill="red" style="font-size: 12px" id="showdegrees">Info</text>
<line x1="100" y1="0" x2="100" y2="200" style="stroke: black; stroke-width: 1" />
<line x1="0" y1="100" x2="200" y2="100" style="stroke: black; stroke-width: 1" />
</svg>

Try this:
var dY = this.pos.y - e.gameY, // opposite
dX = this.pos.x - e.gameX, // adjacent
radians = Math.atan(dY/dX); // wrong, in [-1/2 pi, 1/2 pi]
if(1/dX < 0) radians += Math.PI; // fixed, in [-1/2 pi, 3/2 pi]
if(1/radians < 0) radians += 2*Math.PI; // fixed, in [+0, 2 pi]
var degrees = radians*180/Math.PI; // from radians to degrees
Explanation:
Better calculate the radians with Math.atan and the tangent. Calculating the hypotenuse using Math.sqrt is expensive.
Math.atan gives an angle between -1/2 pi and 1/2 pi, that is, the right half circle. To fix it, just sum pi in case dX was negative.
Then we get an angle between -1/2 pi and 3/2 pi. So, in case it's negative, we sum 2 pi in order to obtain an angle between 0 and 2 pi.
Note that we must consider -0 negative in order to make it work properly. So, instead of checking dX < 0 and radians < 0, we check their inverse.
Note the final result will be NaN in case both dX and dY are 0 (or -0).

You need to use a little bit more information than just the arcsin to figure this out. The reason for this is that arcsin will only return values between -π/2 and π/2 (-90 degrees and 90 degrees), as you already know.
So, to figure out the other part, you need to be aware of what quadrant you are in.
In quadrant 2, arcsin is between 90 and 0, the real angle is between 90 and 180. So if you are in quadrant 2, 180-calculated angle=real angle. (180-90=90, 180-0=180).
In quadrant 3, arcsin is between 0 and -90. The real angle is between 180 and 270. so again, 180-calculated angle = real angle. (180-0=180, 180-(-90)=270).
In quadrant 4, arcsin is between -90 and 0. The real angle is between 270 and 360. So 360+calculated angle=real angle. (360+(-90)=270, 360+0)=360).
The same is also true for quadrant 1, you just don't need to make the transformation. (0+360=360 (equivalent to 0), 90+360=450 (equivalent to 90) ).
So, determine the quadrant first, and apply a rule based on that.
For an (x,y) coordinate, if x is positive and y is positive, you are quadrant 1. If x is negative and y is positive, you are quadrant 2. If x is negative and y is negative, you are quadrant 3. if x is positive and y is negative, you are quadrant 4.
So in your case, the distance from the origin is you (dX,dY) coordinate pair, so something like this should do it:
//your original code...
var degrees = radians*(180/Math.PI); //convert from radians to degrees
//then
if (dX>=0 and dY>=0)
{//quadrant 1
//no transformation, do nothing
}
if (dX>=0 and dy<0)
{ //quadrant 4
degrees=360+degrees;
}
if (dX<0 and dy<0)
{ //quadrant 3
degrees=180-degrees;
}
if (dX<0 and dy>0)
{ //quadrant 2
degrees=180-degrees;
}
this.calculatedAngle = degrees;

Related

Calculate angle based on x, y position

I am trying to calculate the angle for an arrow on a ball, based on the position where it is going to.
The arrow moves, but in a total unexplainable direction, can anybody give some pointers?
Codepen available: Codepen
I added the full code on here (EDITED based on input):
I added a step to make the difference bigger for the angle calculation, not sure if that is the right way to go, but it seems a bit more functional. Plus added the +/- 90 in the angle method, but that doesnt seem to fix it. It is still feeling odd.
class Throwable {
constructor(){
this.throwObject = null;
this.canDrag = null;
this.initialDiffX = 0;
this.initialDiffY = 0;
this.previousX = 0;
this.previousY = 0;
this.intervalCounter = 0;
}
set x(input) {
this.throwObject.style.left = input + 'px';
}
set y(input) {
this.throwObject.style.top = input + 'px';
}
set rotation(input) {
this.throwObject.style.transform = `rotate(${input}deg)`;
}
init(){
this.throwObject = document.querySelector('.throwable');
this.throwObject.addEventListener('mousedown', this.activateDrag.bind(this));
this.throwObject.addEventListener('mouseup', this.deactivateDrag.bind(this));
document.addEventListener('mousemove', this.drag.bind(this));
}
activateDrag(event) {
this.canDrag = true;
this.initialDiffX = event.clientX - this.throwObject.offsetLeft;
this.initialDiffY = event.clientY - this.throwObject.offsetTop;
}
deactivateDrag() {
this.canDrag = false;
}
drag(event) {
if(this.canDrag === true) {
if(this.intervalCounter >= 30) {
this.intervalCounter = 0;
}
if(this.intervalCounter === 0) {
this.previousX = event.clientX;
this.previousY = event.clientY;
}
this.intervalCounter++;
this.y = event.clientY- this.initialDiffY;
this.x = event.clientX - this.initialDiffX;
this.rotation = this.angle(event.clientX, event.clientY, this.previousX, this.previousY);
}
}
angle(ex, ey, cx, cy) {
var dy = ey - cy;
var dx = ex - cx;
return Math.atan2(dy, dx) * 180 / Math.PI + 90;
}
// Untility
log(logObject) {
let logStr = '';
for(let key in logObject) {
logStr += `${key}: ${logObject[key]}<br>`;
}
document.getElementById('log').innerHTML = logStr;
}
}
let throwable = new Throwable();
throwable.init();
I made a mistake in comparing two different values, I fixed that, it is working way better, still have some odd behavior sometimes, seems like it doesnt know where to go in some points. But working better than before.
Maybe you have some mistakes in your angle function. This works for me:
angle(cx, cy, ex, ey) {
var dy = ey - cy ;
var dx = cx - ex ;
return Math.atan2(dx, dy) * 180 / Math.PI;
}
When you call this.angle() you give it twice this.throwObject.offset..., once directly and once via px and py:
let px = this.throwObject.offsetLeft;
let py = this.throwObject.offsetTop;
this.rotation = this.angle(this.throwObject.offsetLeft, this.throwObject.offsetTop, px, py)
That will result in dx and dy to be 0 in angle() making the result of Math.atan2() unpredictable.
I'm not sure about the rest of your code, but maybe you meant to call angle() like this:
this.rotation = this.angle(this.x, this.y, px, py);
There are a couple small issues that I can see.
First, the angle method is calculating radians in range of -180 to 180 and you want it to be 0 to 360. So after angle calculation you'll want to convert something like this:
angle(ex, ey, cx, cy) {
var dy = ey - cy;
var dx = ex - cx;
var theta = Math.atan2(dy, dx) * 180 / Math.PI;
if (theta < 0) theta += 360; // convert to [0, 360]
return theta;
}
Second, the starting angle of your element at 0 degrees is not the actual 0 degrees calculated by this method due to how js coordinates work. A quick fix is to add 90 degrees to make it match:
set rotation(input) {
this.throwObject.style.transform = `rotate(${input + 90}deg)`;
}
It's still a little janky after these conversion but I think it's a start on the right calculations. My guess is part of the issue is having such close points for calculation.
This happens because there's a difference how angles are measured between Math.atan2() and the CSS rotate transformation.
For us humans it's natural that the 12 o' clock position on an analog clock refers to the angle 0 - same for CSS rotate.
Math.atan2() however measures the angle starting from the horizontal x axis. So depending on your input coordinates it would be the 3 or 9 o' clock position.
There's an easy fix however.
After calculating the angle
Math.atan2(dy, dx) * 180 / Math.PI
just subtract 90 degrees like
Math.atan2(dy, dx) * 180 / Math.PI - 90
What happens when intervalCounter become 0? The previus point moved to the event point, so dy, dx becomes 0 and you have a jitter: -180 + 90, +180 + 90, 0 + 90 as defined in Math.atan2. After that, the previus point is fixed until intervalCounter < 30 and you have some inceasing distance between the previus and event points, so the angle is close to the expected one.
Anyway, this is a bad coordinate filter. You can improve it by implementing simple exponential filtering or by using fixed size (30 in your case) queue for event point.

Get the angle degrees from 2 points on a grid

I have a grid for a flat, 2D map which is a bit different from usual. The top left point is 0,0 and bottom right is 1000,1000. I have 2 points on this map, an origin/anchor point and a destination.
I am looking to figure out the degrees (in javascript) from the origin to the destination. I have looked through many answers and they all don't produce the correct result.
function getAngle(origin_x, origin_y, destination_x, destination_y) {
var newx = destination_x - origin_x;
var newy = destination_y - origin_y;
var theta = Math.atan2(-newy, newx);
if (theta < 0) {
theta += 2 * Math.PI;
}
theta *= 180 / Math.PI;
return theta;
}
This is what I have so far but it doesn't produce the right angle.
Thankyou very much in advance!
image from mdn Math.atan2 doc
It will give the angle relative to the x-axis, not the y-axis. To convert all you would do is
var newAngle = 90 - theta;

Additive Angles in Javascript

I'm trying to calculate the angle between a still and moving vector in javascript. However, I want the angle to be additive based on direction (so if you're moving clockwise, the angle would always increase, whereas moving counterclockwise would cause the angle to only decrease).
I'm storing the coordinates in arrays as start[x, y] and current[x,y] and need to calculate the angle while the current array changes. I'm also currently using the atan2 function, but this is limited to -180 to +180 degrees.
start = [event.clientX - discCent[0], event.clientY - discCent[1]];
current = [event.clientX - discCent[0], event.clientY - discCent[1]];
// Get this to be additive
angleDeg = Math.atan2(current[1] - start[1], current[0] - start[0]) * 180 / Math.PI;
Thanks!
Keep the previous angle and add/subtract a multiple of 360° to get closest to it:
var angleDegPrev = 0.; // initialization at start
...
// compute angle in ]-180,180]
start = [event.clientX - discCent[0], event.clientY - discCent[1]];
current = [event.clientX - discCent[0], event.clientY - discCent[1]];
angleDeg = Math.atan2(current[1] - start[1], current[0] - start[0]) * 180 / Math.PI;
// add multiple of 360 to get closest to previous angle
angleDeg += Math.round((angleDegPrev - angleDeg)/360.)*360.;
angleDegPrev = angleDeg;

Need to find a (x,y) coordinate based on an angle

So I'm stumped. I didn't know trigonometry before this, and I've been learning but nothing seems to be working.
So a few things to note: In html, cartesian origin(0,0) is the top left corner of the screen. DIVS natural rotation is 0deg or ---->this way.
I need to find the x,y point noted by the ? mark in the problem.
$('#wrapper').on('click', function(e){
mouseX = e.pageX;
mouseY= e.pageY;
var angle = getAngle(mouseX,Rocket.centerX,mouseY,Rocket.centerY);
var angleDistance = Math.sqrt((Math.pow((mouseX - (Rocket.left+Rocket.halfX)),2)) + (Math.pow((mouseY-(Rocket.top+Rocket.halfY)),2)));
var cp2Angle = -90 +(angle*2);
var invCP2Angle = 90+ angle;
var cp2Distance = angleDistance*.5;
//Red Line
$(this).append('<div class="line" style="transform-origin:left center;width:'+(Math.round(angleDistance))+'px;top:'+(Rocket.top+Rocket.halfY)+'px;left:'+(Rocket.left+Rocket.halfX)+'px;transform:rotate('+(Math.round(angle))+'deg);"></div>');
//Blue Line
$(this).append('<div class="line" style="background:#0000FF;transform-origin:left center;width:'+Math.round(cp2Distance)+'px;top:'+(mouseY)+'px;left:'+(mouseX)+'px;transform:rotate('+(Math.round(cp2Angle))+'deg);"></div>');
}
function getAngle(x2,x1,y2,y1){
var angle = Math.degrees(Math.atan2(y2-y1,x2-x1));
return angle;
}
Math.degrees = function(radians) {
return (radians * 180) / Math.PI;
};
So this might be confusing. Basically when I click on the page, i calculate the angle between my custom origin and the mouse points using Math.atan2(); I also calculate the distance using Math.sqrt((Math.pow((x2 - x1),2)) + (Math.pow((y2-y1),2)));
The blue line length is half the length of the red line, but the angle changes, based on the angle of the red line.
When the red line angle = 0deg(a flat line), the blue line angle will be -90(or straight up, at red line -45 deg, the blue line will be -180(or flat), and at Red Line -90, the blue line will be -270 deg(or straight down). The formula is -90 +(angle*2)
I need to know the other end point of the blue line. The lines only exist to debug, but the point is needed because I have an animation where I animate a rocket on a bezier curve, and I need to change the control point based on the angle of the mouse click, if there's abetter way to calculate that without trigonometry, then let me know.
I read that the angle is the same as the slope of the line and to find it by using Math.tan(angle in radians). Sometimes the triangle will be a right triangle for instance if the first angle is 0 deg, sometimes it won't be a triangle at all, but a straight line down, for instance if they click -90.
I've also tried polar coordinates thought I wasn't sure which angle to use:
var polarX = mouseX-(cp2Distance * Math.cos(Math.radians(invCP2Angle)));
var polarY = mouseY- (cp2Distance * Math.sin(Math.radians(invCP2Angle)));
I do not know javascript well, so instead of giving you code, I'll just give you the formulae. On the figure below, I give you the conventions used.
x3 = x2 + cos(brownAngle + greenAngle) * d2
y3 = y2 + sin(brownAngle + greenAngle) * d2
If I understand you correctly, you have already d2 = 0.5 * d1, d1, (x2, y2) as well as the angles. This should then just be a matter of plugging these values into the above formulae.
Let A, B and C be the three points.
AB = ( cos(angle1), sin(angle1) ) * length1
B = A + B
BC = ( cos(angle1+angle2), sin(angle1+angle2) ) * length2
C = B + BC
In your case,
A = ( 0, 0 )
angle1 = 31°
length1 = 655
angle2 = 152°
length2 = 328
Then,
C = ( Math.cos(31*Math.PI/180), Math.sin(31*Math.PI/180) ) * 655 +
( Math.cos(152*Math.PI/180), Math.sin(152*Math.PI/180) ) * 328
= ( Math.cos(31*Math.PI/180) * 655 + Math.cos(183*Math.PI/180) * 328,
Math.sin(31*Math.PI/180) * 655 + Math.sin(183*Math.PI/180) * 328 )
= ( 233.8940945603834, 320.1837454184)

For the point inside circle, find in which quarter it is?

I researched google but couldn't find the keywords for search. So I ask here if my algorithm and code is efficient?
http://sketchtoy.com/66429941 (algorithm)
The algoritm is: I have four points which are: north, east, south and west of circle. I check 4 distances (distanceToNorth, distanceToEast, distanceToSouth, distanceToWest). And I find minimum of them so that is the quarter.
Here is the code but it does not seem efficient for me.
(firstQuarter is North, secondQuarter is East and so on..
note: assume that mousemove is inside the circle.
var firstQuarterX = centerX;
var firstQuarterY = centerY - radius;
var secondQuarterX = centerX + radius;
var secondQuarterY = centerY;
var thirdQuarterX = centerX;
var thirdQuarterY = centerY + radius;
var fourthQuarterX = centerX - radius;
var fourthQuarterY = centerY;
var distanceToFirst = Math.sqrt(Math.pow(x-firstQuarterX, 2) + Math.pow(y-firstQuarterY, 2));
var distanceToSecond = Math.sqrt(Math.pow(x-secondQuarterX, 2) + Math.pow(y-secondQuarterY, 2));
var distanceToThird = Math.sqrt(Math.pow(x-thirdQuarterX, 2) + Math.pow(y-thirdQuarterY, 2));
var distanceToFourth = Math.sqrt(Math.pow(x-fourthQuarterX, 2) + Math.pow(y-fourthQuarterY, 2));
var min = Math.min(distanceToFirst, distanceToSecond, distanceToThird, distanceToFourth);
var numbers = [distanceToFirst, distanceToSecond, distanceToThird, distanceToFourth];
var index = numbers.indexOf(min); // it will give 0 or 1 or 2 or 3
var quarter = index + 1;
Observe that the boundaries between your quarters lie along the lines with equations y = x and y = -x, relative to an origin at the center of the circle. You can use those to evaluate which quarter each point falls in.
If your point is (x, y), then its coordinates relative to the center of the circle are xRelative = x - centerX and yRelative = y - centerY. Then
your point is in the first (south in your code) quarter if yRelative < 0 and Math.abs(xRelative) < -yRelative
your point is in the second (east) quarter if xRelative > 0 and Math.abs(yRelative) < xRelative
your point is in the third (north) quarter if yRelative > 0 and Math.abs(xRelative) < yRelative
your point is in the fourth (west) quarter if xRelative < 0 and Math.abs(yRelative) < -xRelative
I leave it to you to determine to which quarter to assign points that fall exactly on a boundary. Also, you can implement a little decision tree based on those criteria if you prefer; that should be a little more efficient then testing each criterion in turn.
Not so sure but I think this might work. Math.atan2(CenterY - y, CenterX - x) * 180 / Math.PI gives the apparent angle between the points. Do the remaining math to figure out the quarter.
What about something like:
return x>centerX?(y>centerY?"Quad 2":"Quad 1"):(y>centerY?"Quad 3":"Quad 4");
Less graceful, more slim.
For more efficient algorithm, you can compute the quadrant just by analyzing the signs of dx + dy and dx - dy quantities (dx, dy being x, y minus centerX, centerY respectively) (I presume that as your animation shows, your quadrants are rotated by 45 degrees against 'standard' quadrants.

Categories