could you give me a tip please, a redirection to what is the "simple" math I need to learn and understand for the rotation of an object (its coordinate x, y) around an other object (an other x, y), I guess I could also describing my need as (x, y) moving coordinate orbiting around (x, y) fixed coordinates. It is for a little HTML5/Javascript game. Thank you.
-
\$\begingroup\$ I would recommend learning about high school trigonometry. \$\endgroup\$– sam hocevarCommented Apr 26, 2016 at 8:30
-
\$\begingroup\$ Thanks I will, also, if someone is interested by this question, I got this link : gamefromscratch.com/post/2012/11/24/… \$\endgroup\$– Michaël SeyneCommented Apr 26, 2016 at 9:42
2 Answers
You don't need matrices at all. Just take the rotation angle in radians, get its cosine and sine, multiply them by the distance you want between the two objects and add the x and y values of the fixed object:
rotatingObject.x = Math.cos(rotationAngle) * distance + fixedObject.x
rotatingObject.y = Math.sin(rotationAngle) * distance + fixedObject.y
-
\$\begingroup\$ Lol, yeah. Probably i'm thinking to hard right there. Up you gooo \$\endgroup\$ Commented Apr 26, 2016 at 9:00
-
-
Edit: Added the simplified form. user6245072's answer works great if distance is known, and the way below works with known coordinates.
Edit: Nevermind the matrices, look at what user6245072's answer instead. It's more simple. I was thinking too hard :p
That, would be matrices. There's a lot of websites that explains it for you.
This is a matrix i took from an util class i made my self a while back:
[Math.cos(ang), -Math.sin(ang), 0.0f, (-X * Math.cos(ang) + Y * Math.sin(ang) + X)]
[Math.sin(ang), Math.cos(ang) , 0.0f, (-X * Math.sin(ang) - Y * Math.cos(ang) + Y)]
[0.0f , 0.0f , 1.0f, 0.0f ]
[0.0f , 0.0f , 0.0f, 1.0f ]
With (X, Y) to be the point of rotation and ang to be the rotation degree in radians.
If you multiply that with a vector it will rotate the vector relative to (X, Y). This is the multiplied form:
rotatedX = x * (Math.cos(ang)) + y * (-Math.sin(ang)) + (-X * Math.cos(ang) + Y * Math.sin(ang) + X);
rotatedY = x * (Math.sin(ang)) + y * (Math.cos(ang)) + (-X * Math.sin(ang) - Y * Math.cos(ang) + Y);
Edit: Simplified form for anyone running to this thread again:
float dx = x - X, dy = y - Y;
rotatedX = dx * (Math.cos(ang)) + dy * (-Math.sin(ang)) + X);
rotatedY = dx * (Math.sin(ang)) + dy * (Math.cos(ang)) + Y);
There should be some other approaches out there, but this work too.
The main idea:
- Translate the point which you want the object to rotate to, to (0, 0)
- Rotate normally (can be done with a normal rotation matrix)
- Translate back to its original place