It seems so trivial in this age of OpenGL, WebGL and many other beautiful libs, that will do the hard work for you. And then you find yourself in a position, where you need something simple and it's nowhere to be found.
Rotation of a point around the origin or O or {x:0,y:0,z:0}
How hard can it be.
Well, it's not simple.
Here is the code in as3 and javascript
function rotatePoint(p,rx,ry,rz)
{
var x,y,z,q={};
x=p.x*Math.cos(rz)-p.y*Math.sin(rz);
y=p.x*Math.sin(rz)+p.y*Math.cos(rz);
q.x=x*Math.cos(ry)-p.z*Math.sin(ry);
z=x*Math.sin(ry)+p.z*Math.cos(ry);
q.y=y*Math.cos(rx)-z*Math.sin(rx);
q.z=y*Math.sin(rx)+z*Math.cos(rx);
return q;
}
The parameters:
p is a point, so an object with {x:x,y:y,z:z};
rx is the amount you want to rotate around the x axis in radians.
ry is the amount you want to rotate around the y axis in radians.
rz is the amount you want to rotate around the z axis in radians.
It returns a point with the new rotated coordinates. Don't try to understand the maths, it took me three days to put this together.
So in practice, I have a point 1,0,0 and I want to rotate it around the z axis 45 degrees.
The answer is in this case pretty obvious, it would be 0,707...,0.707....,0 or cos(45),sin(45),0
So how would we go about doing that with the function?
p.x=1;
p.y=0;
p.z=0;
p=rotatePoint(p,45/180*Math.PI,0,0);
trace(p.x+","+p.y+","+p.z);
Output:
0.7071067811865476,0.7071067811865475,0
Halleluja, you can now play around with the other axis and stuff.
Any time you need something rotated, this function is your friend.
I've been using it on an off since 1988 just needed it again for my Delft project (about which I will tell you more later, but now, I'm sworn to secrecy :)
I found it in an ancient piece of code from 1996 in C, so I rewrote it to Javascript/As3.
And there you are.
Geen opmerkingen:
Een reactie posten