Calculate angle of triangle with sin or cos - javascript

I'm trying to calculate an angle based on triangle sides, preferably with sin.
The first 2 are helper functions getDistance and getPointsDifference
I have these functions:
var getDistance = function(p1, p2){
var dx = p1.x - p2.x, dy = p1.y - p2.y;
return Math.sqrt(dx*dx + dy*dy);
}
var getPointsDifference = function(p1, p2){
return {
x: -1 * (p1.x - p2.x),
y: (p1.y - p2.y)
}
}
and finaly:
var getMenuChoice = function(cx,cy, x, y){
var distance = getDistance({x:cx,y:cy}, {x:x,y:y});
if (distance <= 100) {
console.log(1)
} else {
console.log(2)
}
var diff = getPointsDifference({x:cx,y:cy}, {x:x,y:y});
var a = Math.sin(diff.y/distance)
console.log("asdf:", a)
}
Could someone please show me what am I doing wrong? I would like to calculate the result in degrees.
update
I detect a lick on the screen which gives me a x,y, and then I subtract those x,y from cx and cy which are the center of the screen

This is called the angle (or direction) of the vector from (or to, depends on what you need) point of click to the center of the screen. There is no need in calculation of the distance and arcsin of the angle (instead of yours sin) - you can just use Math.atan2(dy, dx);.
dy is change in y (y2 - y1) and dx is change in x (x2 - x1) between those two points. You can use a regular Math.atan(dy / dx), but then you must be sure that you are not dividing by zero and have to take into account the signs of dy and dx to have answer in the correct quadrant. Math.atan2 will do it all for you. And the picture below is just a reminder.
And yes, the answer will be in radians, as it was mentioned in comments. Conversion is simple degrees = radians * (180 / Math.PI);

Related

Draw text above a line on P5js

I'm doing a graph theory project, and I need to show the edge weight above each of the edges.
currently I'm using this method:
var x1; //starting point
var x2; //ending point
function setup() {
createCanvas(640, 480);
x1 = createVector(random(0, width/2), random(0, height/2)); //random position to the upper left
x2 = createVector(random(width/2, width), random(height/2, height)); //random position to the lower right
}
function draw() {
background(200);
stroke(0);
line(x1.x, x1.y, x2.x, x2.y); //draw a line beetween the points
d = dist(x1.x, x1.y, x2.x, x2.y);
var angle = atan2(x1.y - x2.y, x1.x - x2.x); // gets the angle of the line
textAlign(CENTER);
text("X1", x1.x + 5, x1.y + 5); // just to show where is the begining
text("X2", x2.x - 5, x2.y - 5); // just to show there is the end
fill(0);
signalx = x1.x > x2.x ? -1 : 1; // if the start is to the right of the end
signaly = x1.y > x2.y ? -1 : 1; // if the start is below the end
// I think i need to use the angle here
text(42, (x1.x + (d / 2) * signalx), (x1.y + (d / 2) * signaly));
}
the problem is that the result, well, is not as expected:
The idea is that the text I'm showing (42, the edge weight) is a little bit above the middle of the line, what is currently not happening.
I know that I have to take the angle of the line into consideration, but not sure where.
Thanks for any help, and if there's any need of more information let me know.
What you want to do is use linear interpolation. First, find the equation of the line in slope-intercept form, so you can solve for y (when you know x). (I'm just going to rename x1 to p1 and x2 to p2 for clarity.)
(math)
// with points (x1, y1) and (x2, y2)
y - y1 = m*(x - x1) // point-slope form (just a step)
y - y1 = m*x - m*x1
y = m*x - m*x1 + y1 // slope-intercept
Then, since x is the midpoint of the line, x equals the average of the two endpoints. And then calculate y, based on the above equation:
(code)
float m = (p2.y - p1.y) / (p2.x - p1.x);
int x = (x2 + x1) / 2;
int y = m*x - m*p1.x + p1.y;

need to make a ball travel in the angle it was hit from

self.hitBall = function(ball, x, y) {
var angle = Math.atan2((x - ball.centerX), (y - ball.centerY));
ball.velocityY = (Math.sin(angle) * 10);
ball.velocityX = (Math.cos(angle) * 10);
};
So the function takes in the ball, which has a centerX variable and a centerY variabe. The x and y passed into the function is the x and y is the point the ball was hit. I want to make the ball travel in the direction it was hit from.
Not really sure why my code isn't working.. it's behaving very strangely and I'm not that good with trigonometry so I'm not really quite sure why it isn't working.
Two problems with your code:
Math.atan2() takes the arguments in (y, x) order. Most languages (Java, JavaScript, C, etc.) do this (except Microsoft Excel and some others, which use (x, y) order).
When you say "[make] the ball travel in the angle it was hit from", you want to subtract the hit point from the ball point. In other words, the vector is (ball.centerX - hitX, ball.centerY - hitY).
Thus, the solutions:
Solution 1:
var angle = Math.atan2((ball.centerY - y), (ball.centerX - x));
Solution 2 - do vector math without angles (equivalent calculation):
var dx = ball.centerX - x;
var dy = ball.centerY - y;
var norm = Math.sqrt(dx * dx + dy * dy);
ball.velocityX = (dx / norm) * 10;
ball.velocityY = (dy / norm) * 10;

Calculate vector with given angle and length

Is there any way in which, in javascript, I can call a function with an x and y co-ord and a direction (angle in degrees) and it will return a set of new co-ords that has been 'moved' by 10px in the direction given from the original co-ords? I looked around but all I can find is ways to get the angle of two given co-ords.
This function returns an array [xCoord, yCoord] of the new coordinates:
function myFunction(xCoord, yCoord, angle, length) {
length = typeof length !== 'undefined' ? length : 10;
angle = angle * Math.PI / 180; // if you're using degrees instead of radians
return [length * Math.cos(angle) + xCoord, length * Math.sin(angle) + yCoord]
}
I just wanted to point out, that the answers of are not correct IMHO. I've created a JSFiddle showing that the correct implementation must be something like this:
function getRelativeVector(angle, length, xOffset, yOffset) {
angle = angle * Math.PI / 180;
return {
X:length * Math.sin(angle) + xOffset,
Y:length * Math.cos(angle) + yOffset
};
}
The other solutions shown here from #Audrius and #Markus are simply twisted in cos and sin. They are working for angles between 0 and 45 degrees only.
The formula would be:
X = length * sin(angle) + xLocation
Y = length * cos(angle) + yLocation
The shift in x coordinate is L*cos(a) and shift in y coordinate is L*sin(a), where a is the angle ("direction given") and L is 10 px in your case.

How to calculate rotation in 2D in Javascript

I am not so familiar trigonometry, but I have only two points to rotate in 2D:
*nx, ny
. -
. -
. angle -
*cx,cy.................*x,y
cx, cy = rotation center
x,y = current x,y
nx, ny = new coordinates
How to calculate new points in a certain angle?
function rotate(cx, cy, x, y, angle) {
var radians = (Math.PI / 180) * angle,
cos = Math.cos(radians),
sin = Math.sin(radians),
nx = (cos * (x - cx)) + (sin * (y - cy)) + cx,
ny = (cos * (y - cy)) - (sin * (x - cx)) + cy;
return [nx, ny];
}
The first two parameters are the X and Y coordinates of the central point (the origin around which the second point will be rotated). The next two parameters are the coordinates of the point that we'll be rotating. The last parameter is the angle, in degrees.
As an example, we'll take the point (2, 1) and rotate it around the point (1, 1) by 90 degrees clockwise.
rotate(1, 1, 2, 1, 90);
// > [1, 0]
Three notes about this function:
For clockwise rotation, the last parameter angle should be positive. For counterclockwise rotation (like in the diagram you provided), it should be negative.
Note that even if you provide arguments that should yield a point whose coordinates are whole numbers -- i.e. rotating the point (5, 0) by 90 degrees about the origin (0, 0), which should yield (0, -5) -- JavaScript's rounding behavior means that either coordinate could still be a value that's frustratingly close to the expected whole number, but is still a float. For example:
rotate(0, 0, 5, 0, 90);
// > [3.061616997868383e-16, -5]
For this reason, both elements of the resulting array should be expected as a float. You can convert them to integers using Math.round(), Math.ceil(), or Math.floor() as needed.
Finally, note that this function assumes a Cartesian coordinate system, meaning that values on the Y axis become higher as you go "up" in the coordinate plane. In HTML / CSS, the Y axis is inverted -- values on the Y axis become higher as you move down the page.
First, translate the rotation center to the origin
Calculate the new coordinates (nx, ny)
Translate back to the original rotation center
Step 1
Your new points are
center: (0,0)
point: (x-cx, y-cy)
Step 2
nx = (x-cx)*cos(theta) - (y-cy)*sin(theta)
ny = (y-cy)*cos(theta) + (x-cx)*sin(theta)
Step 3
Translate back to original rotation center:
nx = (x-cx)*cos(theta) - (y-cy)*sin(theta) + cx
ny = (y-cy)*cos(theta) + (x-cx)*sin(theta) + cy
For deeper explanation, with some fancy diagrams, I recommend looking at this.
above accepted answer not work for me correctly, rotation are reversed , here is working function
/*
CX # Origin X
CY # Origin Y
X # Point X to be rotated
Y # Point Y to be rotated
anticlock_wise # to rotate point in clockwise direction or anticlockwise , default clockwise
return # {x,y}
*/
function rotate(cx, cy, x, y, angle,anticlock_wise = false) {
if(angle == 0){
return {x:parseFloat(x), y:parseFloat(y)};
}if(anticlock_wise){
var radians = (Math.PI / 180) * angle;
}else{
var radians = (Math.PI / -180) * angle;
}
var cos = Math.cos(radians);
var sin = Math.sin(radians);
var nx = (cos * (x - cx)) + (sin * (y - cy)) + cx;
var ny = (cos * (y - cy)) - (sin * (x - cx)) + cy;
return {x:nx, y:ny};
}
According to Polar coordinate system artycle on Wikipedia:
x = r * cos(deg)
y = r * sin(deg)
r (radius) is equal to distance between Rotation Centre and Rotated Point
deg (degrees) is angle measured in degrees
I think it is better to use matrices for such operations.
Here is the example with gl-matrix (but you can use something like THREEJS as well).
import * as glm from 'gl-matrix';
const rotateVector = (() => {
const q = glm.quat.create();
// const m = glm.mat4.create(); // 2nd way
return (v: glm.vec3, point: glm.vec3, axis: glm.vec3, angle: number) => {
glm.quat.setAxisAngle(q, axis, angle);
// glm.mat4.fromRotation(m, angle, axis); // 2nd way
glm.vec3.sub(v, v, point);
glm.vec3.transformQuat(v, v, q);
// glm.vec3.transformMat4(v, v, m); // 2nd way
glm.vec3.add(v, v, point);
return v;
}
})();
In 2D case you need to rotate around z-axis:
rotateVector([x, y, 0], [cX, cY, 0], [0, 0, 1], angleInRadians);

How to calculate rotation angle from rectangle points?

I have 4 points 1,2,3,4 that closes a rectangle.
The points are in a array in this following way: x1 y1 x2 y2 x3 y3 x4 y4
The problem I have is that the rectangle can be rotated in a angle.
How can I calculate the original points (gray outline), and the angle?
I'm trying to reproduce this effect in javascript+css3-transform, so I need to first know the straight dimensions and then rotate with the css.
I just know if the rectangle is straight by comparing points e.g. y1==y2
if(x1==x4 && x2==x3 && y1==y2 && y4==y3){
rectangle.style.top = y1;
rectangle.style.left = x1;
rectangle.style.width = x2-x1;
rectangle.style.height = y4-y1;
rectangle.style.transform = "rotate(?deg)";
}
You can use any coordinate pair on the same side to calculate the rotation angle. Note that mathematic angles normally assume 0 as long the +ve X axis and increase by rotating anti–clockwise (so along the +ve Y axis is 90°, -ve X axis is 180° and so on).
Also, javascript trigonometry functions return values in radians that must be converted to degrees before being used in a CSS transform.
If the shape is not rotated more than 90°, then life is fairly simple and you can use the tanget ratio of a right angle triangle:
tan(angle) = length of opposite side / length of adjacent side
For the OP, the best corners to use are 1 and 4 so that rotation is kept in the first quadrant and clockwise (per the draft CSS3 spec). In javascript terms:
var rotationRadians = Math.atan((x1 - x4) / (y1 - y4));
To convert to degrees:
var RAD2DEG = 180 / Math.PI;
var rotationDegrees = rotationRadians * RAD2DEG;
If the rotation is more than 90°, you will need to adjust the angle. e.g. where the angle is greater than 90° but less than 180°, you'll get a -ve result from the above and need to add 180°:
rotationDegrees += 180;
Also, if you are using page dimentions, y coordinates increase going down the page, which is the opposite of the normal mathetmatic sense so you need to reverse the sense of y1 - y4 in the above.
Edit
Based on the orientation of points in the OP, the following is a general function to return the center and clockwise rotation of the rectangle in degrees. That's all you should need, though you can rotate the corners to be "level" yourself if you wish. You can apply trigonometric functions to calculate new corners or just do some averages (similar to Ian's answer).
/** General case solution for a rectangle
*
* Given coordinages of [x1, y1, x2, y2, x3, y3, x4, y4]
* where the corners are:
* top left : x1, y1
* top right : x2, y2
* bottom right: x3, y3
* bottom left : x4, y4
*
* The centre is the average top left and bottom right coords:
* center: (x1 + x3) / 2 and (y1 + y3) / 2
*
* Clockwise rotation: Math.atan((x1 - x4)/(y1 - y4)) with
* adjustment for the quadrant the angle is in.
*
* Note that if using page coordinates, y is +ve down the page which
* is the reverse of the mathematic sense so y page coordinages
* should be multiplied by -1 before being given to the function.
* (e.g. a page y of 400 should be -400).
*
* #see https://stackoverflow.com/a/13003782/938822
*/
function getRotation(coords) {
// Get center as average of top left and bottom right
var center = [(coords[0] + coords[4]) / 2,
(coords[1] + coords[5]) / 2];
// Get differences top left minus bottom left
var diffs = [coords[0] - coords[6], coords[1] - coords[7]];
// Get rotation in degrees
var rotation = Math.atan(diffs[0]/diffs[1]) * 180 / Math.PI;
// Adjust for 2nd & 3rd quadrants, i.e. diff y is -ve.
if (diffs[1] < 0) {
rotation += 180;
// Adjust for 4th quadrant
// i.e. diff x is -ve, diff y is +ve
} else if (diffs[0] < 0) {
rotation += 360;
}
// return array of [[centerX, centerY], rotation];
return [center, rotation];
}
The center of the rectangle is right between two opposite corners:
cx = (x1 + x3) / 2
cy = (y1 + y3) / 2
The size of the rectangle is the distance between two points:
w = sqrt(pow(x2-x1, 2) + pow(y2-y1, 2))
h = sqrt(pow(x3-x2, 2) + pow(y3-y2, 2))
The corners of the gray rectangle can be calculated from the center and the size, for example the top left corner:
x = cx - w / 2
y = cy - h / 2
The angle is the arctangent of a side of the square:
a = arctan2(y4 - y1, x4 - x1)
(I'm not sure exactly which angle it returns, or what angle you expect for that matter, so you get to test a bit.)
This is how you get the angle between the vertical pink line and the black line starting at the pink line intersection:
var deg = 90 - Math.arctan((x2-x1) / (y2-y1));
The dimensions can be calculated with the help of the Pythagoras theorem:
var width = Math.sqrt((x2-x1)^2 / (y2-y1)^2));
var height = Math.sqrt((x1-x4)^2) / (y4-y1)^2));
The positional coordinates (left and top) are the averages of x1 and x3 and y1 and y3 respectively.
var left = Math.floor((x1 + x3) / 2);
var top = Math.floor((y1 + y3) / 2);
You want to use the negative-margin trick.
var marginLeft = -Math.ceil(width / 2);
var marginTop = -Math.ceil(height / 2);

Categories