I'm not very good at math or geometry, but I want to draw some line segments at increasing angles. What I want to draw is something like when you hold your hand up and spread your fingers apart: lines that start at a common point and expand out at angles that have an equal difference between them.
I have tried this:
len = 300;
angle = 10;
for (i = 0; i <= 5; ++i) {
endPointX = 50 + len * Math.cos(angle);
endPointY = 50 + len * Math.tan(angle);
draw.Line(50, 50, endPointX, endPointY);
angle += 10;
}
However, that's totally wrong and produces something like this
http://i.stack.imgur.com/taX40.png
But I want something like this (bad mspaint, sorry):
http://i.stack.imgur.com/8xfpp.png
What's the right math for this?
There are two separate issues in your question, I will cover each.
Here's an ASCII picture of your situation:
B
+
/|
/ |
/ |
/ |
len / | y
/ |
/ |
/ |
/ __|
/ θ | |
+----------+
A x C
This is a right triangle. It has three sides:
The diagonal side in the picture opposite to the 90° angle is called the hypotenuse and has a length len. The hypotenuse is what you're trying to draw.
The vertical side is the side opposite to the angle θ and has a length y.
The horizontal side is the side adjacent to the angle θ and has a length x.
Given the above illustration the following equations are true:
cos(θ) = x/len
sin(θ) = y/len
These equations are another way of saying:
The cosine of an angle is equal to the length of the adjacent side divided by the length of the hypotenuse.
The sine of an angle is equal to the length of the opposite side divided by the length of the hypotenuse.
When solving the equation for x and y, you get:
x = len * cos(θ)
y = len * sin(θ)
So you want sin() and cos(), not cos() and tan(). If the point A is not at the origin, you would need to offset x and y by addition, like so:
x = len * cos(θ) + 50
y = len * sin(θ) + 50
With the values for x and y, you can find the coordinates for point B on the triangle, and thus be able to draw your lines.
Also, assuming you're programming in Java, the trigonometric functions in the Math class expect the angle in radians, not degrees. Lots of programming languages that provides trigonometric functions are like this.
Radians and degrees measure the same thing, but a complete rotation in degrees goes from 0 to 360° while a complete rotation in radians go from 0 to 2π.
To convert angles in degrees to radians, multiply the angle by π/180. In Java, the constant π is provided by Math.PI.
For example, an angle of 10° degrees is equivalent to 10 * π/180, or π/18 radians.
Firstly, you want cos and sin, not cos and tan.
Secondly, most maths libraries perform trigonometric functions in radians, not degrees. So 10 is a very large difference indeed! To convert from degrees to radians, multiply by (pi/180).
You shouldn't be using tan, but sin. If I remember correctly, it should be something like:
Math.cos(angle/180);
-Math.sin(angle/180);
The negative on sin is important.
The reason you are getting uneven looking angles is that every time you add 10 you're actually spinning the line around the circle 1.6 times.
The math functions expect angles to be in radians, not degrees.
360 degrees = 2*Math.PI radians.
Instead of 10, write "2*Math.PI/36.0"
Also, use sin instead of tan.
Related
I am currently looking to implement an algorithm that will be able to compute the arc midpoint. From here on out, I will be referring to the diagram below. What is known are the start and end nodes (A and B respectively), the center (point C) and point P which is the intersection point of the line AB and CM (I am able to find this point without knowing point M because line AB is perpendicular to line CM and thus, the slope is -1/m). I also know the arc angle and the radius of the arc. I am looking to find point M.
I have been looking at different sources. Some suggest converting coordinates to polar, computing the mid point from the polar coordinates then reverting back to Cartesian. This involves sin and cos (and arctan) which I am a little reluctant to do since trig functions take computing time.
I have been looking to directly computing point M by treating the arc as a circle and having Line CP as a line that intersects the circle at Point M. I would then get two values and the value closest to point P would be the correct intersection point. However, this method, the algebra becomes long and complex. Then I would need to create special cases for when P = C and for when the line AB is horizontal and vertical. This method is ok but I am wondering if there are any better methods out there that can compute this point that are simpler?
Also, as a side note, I will be creating this algorithm in C++.
A circumference in polar form is expressed by
x = Cx + R cos(alpha)
y = Cy + R sin(alpha)
Where alpha is the angle from center C to point x,y. The goal now is how to get alpha without trigonometry.
The arc-midpoint M, the point S in the middle of the segment AB, and your already-calculated point P, all of them have the same alpha, they are on the same line from C.
Let's get vector vx,vy as C to S. Also calculate its length:
vx = Sx - Cx = (Ax + Bx)/2 - Cx
vy = Sy - Cy = (Ay + By)/2 - Cy
leV = sqrt(vx * vx + vy * vy)
I prefer S to P because we can avoid some issues like infinite CP slope or sign to apply to slope (towards M or its inverse).
By defintions of sin and cos we know that:
sin(alpha) = vy / leV
cos(alpha) = vx / leV
and finally we get
Mx = Cx + R * vx / leV
My = Cy + R * vy / leV
Note: To calculate Ryou need another sqrt function, which is not quick, but it's faster than sin or cos.
For better accuracy use the average of Ra= dist(AC) and Rb= dist(BC)
I would then get two values
This is algebraically unavoidable.
and the value closest to point P would be the correct intersection point.
Only if the arc covers less than 180°.
Then I would need to create special cases for when P = C
This is indeed the most tricky case. If A, B, C lie on a line, you don't know which arc is the arc, and won't be able to answer the question. Unless you have some additional information to start with, e.g. know that the arc goes from A to B in a counter-clockwise direction. In this case, you know the orientation of the triangle ABM and can use that to decide which solition to pick, instead of using the distance.
and for when the line AB is horizontal and vertical
Express a line as ax + by + c = 0 and you can treat all slopes the same. THese are homogeneous coordinates of the line, you can compute them e.g. using the cross product (a, b, c) = (Ax, Ay, 1) × (Bx, By, 1). But more detailed questions on how best to compute these lines or intersect it with the circle should probably go to the Math Stack Exchange.
if there are any better methods out there that can compute this point that are simpler?
Projective geometry and homogeneous coordinates can avoid a lot of nasty corner cases, like circles of infinite radius (also known as lines) or the intersection of parallel lines. But the problem of deciding between two solutions remains, so it probably doesn't make things as simple as you'd like them to be.
So I am writing a game in C++, currently I am working on a 'Compass', but I am having some problems with the vector math..
Here is a little image I created to possibly help explain my question better
Ok, so as you can see the 2D position of A begins at (4, 4), but then I want to move A along the 45 degree angle until the 2D position reaches (16, 16), so basically there is a 12 distance between where A starts and where it ends. And my qustion is how would I calculate this?
the simplest way in 2D is to take angle 'ang', and distance 'd', and your starting point 'x' and 'y':
x1 = x + cos(ang) * distance;
y1 = y + sin(ang) * distance;
In 2D the rotation for any object can be just stored as a single value, ang.
using cos for x and sin for y is the "standard" way that almost everyone does it. cos(ang) and sin(ang) trace a circle out as ang increases. ang = 0 points right along the x-axis here, and as angle increases it spins counter-clockwise (i.e at 90 degrees it's pointing straight up). If you swap the cos and sin terms for x and y, you get ang = 0 pointing up along the y axis and clockwise rotation with increasing ang (since it's a mirror image), which could in fact be more convenient for making game, since y-axis is often the "forward" direction and you might like that increasing ang spins to the right.
x1 = x + sin(ang) * distance;
y1 = y + cos(ang) * distance;
Later you can get into vectors and matricies that do the same thing but in a more flexible manner, but cos/sin are fine to get started with in a 2D game. In a 3D game, using cos and sin for rotations starts to break down in certain circumstances, and you start really benefiting from learning the matrix-based approaches.
The distance between (4,4) and (16,16) isn't actually 12. Using pythagorean theorem, the distance is actually sqrt(12^2 + 12^2) which is 16.97. To get points along the line you want to use sine and cosine. E.g. If you want to calculate the point halfway along the line the x coordinate would be cos(45)(16.97/2) and the y would be sin(45)(16.97/2). This will work with other angles besides 45 degrees.
Ok.... so I made a quick diagram to sorta explain what I'm hoping to accomplish. Sadly math is not my forte and I'm hoping one of you wizards can give me the correct formulas :) This is for a c++ program, but really I'm looking for the formulas rather than c++ code.
Ok, now basically, the red circle is our 0,0 point, where I'm standing. The blue circle is 300 units above us and at what I would assume is a 0 degree's angle. I want to know, how I can find a find the x,y for a point in this chart using the angle of my choice as well as a certain distance of my choice.
I would want to know how to find the x,y of the green circle which is lets say 225 degrees and 500 units away.
So I assume I have to figure out a way to transpose a circle that is 500 units away from 0,0 at all points than pick a place on that circle based on the angle I want? But yeah no idea where to go from there.
A point on a plane can be expressed in two main mathematical representations, cartesian (thus x,y) and polar : using a distance from the center and an angle. Typically r and a greek letter, but let's use w.
Definitions
Under common conventions, r is the distance from the center (0,0) to your point, and
angles are measured going counterclockwise (for positive values, clockwise for negative), with the 0 being the horizontal on the right hand side.
Remarks
Note a few things about angles in polar representations :
angles can be expressed with radians as well, with π being the same angle as 180°, thus π/2 90° and so on. π=3.14 (approx.) is defined by 2π=the perimeter of a circle of radius 1.
angles can be represented modulo a full circle. A full circle is either 2π or 360°, thus +90° is the same as -270°, and +180° and -180° are the same, as well as 3π/4 and -5π/4, 2π and 0, 360° and 0°, etc. You can consider angles between [-π,π] (that is [-180,180]) or [0,2π] (i.e. [0,360]), or not restrain them at all, it doesn't matter.
when your point is in the center (r=0) then the angle w is not really defined.
r is by definition always positive. If r is negative, you can change its sign and add half a turn (π or 180°) to get coordinates for the same point.
Points on your graph
red : x=0, y=0 or r=0 w= any value
blue : x=0, y=300 or r=300 and w=90°
green : x=-400, y=-400 or r=-565 and w=225° (approximate values, I didn't do the actual measurements)
Note that for the blue point you can have w=-270°, and for the green w=-135°, etc.
Going from one representation to the other
Finally, you need trigonometry formulas to go back and forth between representations. The easier transformation is from polar to cartesian :
x=r*cos(w)
y=r*sin(w)
Since cos²+sin²=1, pythagoras, and so on, you can see that x² + y² = r²cos²(w) + r²sin²(w) = r², thus to get r, use :
r=sqrt(x²+y²)
And finally to get the angle, we use cos/sin = tan where tan is another trigonometry function. From y/x = r sin(w) / (r cos(w)) = tan(w), you get :
w = arctan(y/x) [mod π]
tan is a function modulo π, instead of 2π. arctan simply means the inverse of the function tan, and is sometimes written tan^-1 or atan.
By inverting the tangent, you get a result betweeen -π/2 and π/2 (or -90° and 90°) : you need to eventually add π to your result. This is done for angles between [π/2,π] and [-π,π/2] ([90,180] and [-180,-90]). These values are caracterized by the sign of the cos : since x = r cos(w) you know x is negative on all these angles. Try looking where these angles are on your graph, it's really straightforward. Thus :
w = arctan(y/x) + (π if x < 0)
Finally, you can not divide by x if it is 0. In that corner case, you have
if y > 0, w = π/2
if y < 0, w = -π/2
What is seems is that given polar coordinates, you want to obtain Cartesian coordinates from this. It's some simple mathematics and should be easy to do.
to convert polar(r, O) coordinates to cartesian(x, y) coordinates
x = r * cos(O)
y = r * sin(O)
where O is theta, not zero
reference: http://www.mathsisfun.com/polar-cartesian-coordinates.html
I need to quantize my vector and generate directional code words from 0 to 15. So I had implemented following code line using C++ to achieve that. Just pass 2 points and calculate atan() value using that points. But it's only return just 0 to 7. other values are not return. Also sometimes it's return very large numbers like 42345. How can I modify this to return directional code words from 0 to 15
double angle = abs(atan((acc.y - acc.lastY)/(acc.x - acc.lastX))/(20*3.14159/180));
That's what the std::atan2 function is for.
Since tan function is periodic over just half circle. Logically, if you negate both coordinates, the expression in the argument comes out the same, so you can't tell the two cases apart. So you have to first look at which quadrant you are in by checking the signs and than adding 180 if you are in the negative half-space. The std::atan2 function will do it for you.
double angle = std::atan2(acc.y - acc.lastY, acc.x - acc.lastX) * (8 / PI);
It has the added benefit of actually working when acc.x == acc.lastX, while your expression will signal division by zero.
Additionally, the use of abs is wrong. If you get angle between -π and π you want to get angle between 0 and 2π, you need to write:
double angle = std::atan2(acc.y - acc.lastY, acc.x - acc.lastX); // keep it in radians
if(angle < 0)
angle += 2 * PI;
return angle * (8 / PI); // convert to <0, 16)
With abs you are unifying the cases with oposite sign of y, but same x.
Additionally if you want to round the values so that 0 represents directions along x axis slightly off to either side, you'll need to modify the rounding by adding half of the interval width and you'll have to do before normalizing to the ⟨0, 2π) range. You'd start with:
double angle = std::atan2(acc.y - acc.lastY, acc.x - acc.lastX) + PI/16;
I have pitch, roll, and yaw angles. How would I convert these to a directional vector?
It'd be especially cool if you can show me a quaternion and/or matrix representation of this!
Unfortunately there are different conventions on how to define these things (and roll, pitch, yaw are not quite the same as Euler angles), so you'll have to be careful.
If we define pitch=0 as horizontal (z=0) and yaw as counter-clockwise from the x axis, then the direction vector will be
x = cos(yaw)*cos(pitch)
y = sin(yaw)*cos(pitch)
z = sin(pitch)
Note that I haven't used roll; this is direction unit vector, it doesn't specify attitude. It's easy enough to write a rotation matrix that will carry things into the frame of the flying object (if you want to know, say, where the left wing-tip is pointing), but it's really a good idea to specify the conventions first. Can you tell us more about the problem?
EDIT:
(I've been meaning to get back to this question for two and a half years.)
For the full rotation matrix, if we use the convention above and we want the vector to yaw first, then pitch, then roll, in order to get the final coordinates in the world coordinate frame we must apply the rotation matrices in the reverse order.
First roll:
| 1 0 0 |
| 0 cos(roll) -sin(roll) |
| 0 sin(roll) cos(roll) |
then pitch:
| cos(pitch) 0 -sin(pitch) |
| 0 1 0 |
| sin(pitch) 0 cos(pitch) |
then yaw:
| cos(yaw) -sin(yaw) 0 |
| sin(yaw) cos(yaw) 0 |
| 0 0 1 |
Combine them, and the total rotation matrix is:
| cos(yaw)cos(pitch) -cos(yaw)sin(pitch)sin(roll)-sin(yaw)cos(roll) -cos(yaw)sin(pitch)cos(roll)+sin(yaw)sin(roll)|
| sin(yaw)cos(pitch) -sin(yaw)sin(pitch)sin(roll)+cos(yaw)cos(roll) -sin(yaw)sin(pitch)cos(roll)-cos(yaw)sin(roll)|
| sin(pitch) cos(pitch)sin(roll) cos(pitch)sin(roll)|
So for a unit vector that starts at the x axis, the final coordinates will be:
x = cos(yaw)cos(pitch)
y = sin(yaw)cos(pitch)
z = sin(pitch)
And for the unit vector that starts at the y axis (the left wing-tip), the final coordinates will be:
x = -cos(yaw)sin(pitch)sin(roll)-sin(yaw)cos(roll)
y = -sin(yaw)sin(pitch)sin(roll)+cos(yaw)cos(roll)
z = cos(pitch)sin(roll)
There are six different ways to convert three Euler Angles into a Matrix depending on the Order that they are applied:
typedef float Matrix[3][3];
struct EulerAngle { float X,Y,Z; };
// Euler Order enum.
enum EEulerOrder
{
ORDER_XYZ,
ORDER_YZX,
ORDER_ZXY,
ORDER_ZYX,
ORDER_YXZ,
ORDER_XZY
};
Matrix EulerAnglesToMatrix(const EulerAngle &inEulerAngle,EEulerOrder EulerOrder)
{
// Convert Euler Angles passed in a vector of Radians
// into a rotation matrix. The individual Euler Angles are
// processed in the order requested.
Matrix Mx;
const FLOAT Sx = sinf(inEulerAngle.X);
const FLOAT Sy = sinf(inEulerAngle.Y);
const FLOAT Sz = sinf(inEulerAngle.Z);
const FLOAT Cx = cosf(inEulerAngle.X);
const FLOAT Cy = cosf(inEulerAngle.Y);
const FLOAT Cz = cosf(inEulerAngle.Z);
switch(EulerOrder)
{
case ORDER_XYZ:
Mx.M[0][0]=Cy*Cz;
Mx.M[0][1]=-Cy*Sz;
Mx.M[0][2]=Sy;
Mx.M[1][0]=Cz*Sx*Sy+Cx*Sz;
Mx.M[1][1]=Cx*Cz-Sx*Sy*Sz;
Mx.M[1][2]=-Cy*Sx;
Mx.M[2][0]=-Cx*Cz*Sy+Sx*Sz;
Mx.M[2][1]=Cz*Sx+Cx*Sy*Sz;
Mx.M[2][2]=Cx*Cy;
break;
case ORDER_YZX:
Mx.M[0][0]=Cy*Cz;
Mx.M[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z;
Mx.M[1][1]=Cx*Cz;
Mx.M[1][2]=-Cy*Sx+Cx*Sy*Sz;
Mx.M[2][0]=-Cx*Sy+Cy*Sx*Sz;
Mx.M[2][1]=Cz*Sx;
Mx.M[2][2]=Cx*Cy+Sx*Sy*Sz;
break;
}
return(Mx);
}
FWIW, some CPU's can compute Sin & Cos simultaneously (for example fsincos on x86). If you do this, you can make it a bit faster with three calls rather than 6 to compute the initial sin & cos values.
Update: There are actually 12 ways depending if you want right-handed or left-handed results -- you can change the "handedness" by negating the angles.
Beta saved my day. However I'm using a slightly different reference coordinate system and my definition of pitch is up\down (nodding your head in agreement) where a positive pitch results in a negative y-component. My reference vector is OpenGl style (down the -z axis) so with yaw=0, pitch=0 the resulting unit vector should equal (0, 0, -1).
If anyone comes across this post and has difficulties translating Beta's formulas to this particular system, the equations I use are:
vDir->X = sin(yaw);
vDir->Y = -(sin(pitch)*cos(yaw));
vDir->Z = -(cos(pitch)*cos(yaw));
Note the sign change and the yaw <-> pitch swap. Hope this will save someone some time.
You need to be clear about your definitions here - in particular, what is the vector you want? If it's the direction an aircraft is pointing, the roll doesn't even affect it, and you're just using spherical coordinates (probably with axes/angles permuted).
If on the other hand you want to take a given vector and transform it by these angles, you're looking for a rotation matrix. The wiki article on rotation matrices contains a formula for a yaw-pitch-roll rotation, based on the xyz rotation matrices. I'm not going to attempt to enter it here, given the greek letters and matrices involved.
If someone stumbles upon looking for implementation in FreeCAD.
import FreeCAD, FreeCADGui
from FreeCAD import Vector
from math import sin, cos, pi
cr = FreeCADGui.ActiveDocument.ActiveView.getCameraOrientation().toEuler()
crx = cr[2] # Roll
cry = cr[1] # Pitch
crz = cr[0] # Yaw
crx = crx * pi / 180.0
cry = cry * pi / 180.0
crz = crz * pi / 180.0
x = sin(crz)
y = -(sin(crx) * cos(crz))
z = cos(crx) * cos(cry)
view = Vector(x, y, z)