If I have [1, 0]
and I rotate it 90 degrees = 1/2PI radians
, I should get [0, -1]
. How do I achieve this?
I looked at this page and implemented this:
var rotateVector = function(vec, ang)
{
// not right!
return new PVector(
vec.x * cos(ang) - vec.y * sin(ang),
vec.x * sin(ang) + vec.y * cos(ang)
);
};
But that doesn't seem to work.
It doesn't matter if it's degrees or radians, because the geometry remains the same. I use radians right now.
If I have [1, 0]
and I rotate it 90 degrees = 1/2PI radians
, I should get [0, -1]
. How do I achieve this?
I looked at this page and implemented this:
var rotateVector = function(vec, ang)
{
// not right!
return new PVector(
vec.x * cos(ang) - vec.y * sin(ang),
vec.x * sin(ang) + vec.y * cos(ang)
);
};
But that doesn't seem to work.
It doesn't matter if it's degrees or radians, because the geometry remains the same. I use radians right now.
Share Improve this question edited Jan 23, 2015 at 15:06 joppiesaus asked Jan 23, 2015 at 14:42 joppiesausjoppiesaus 5,7604 gold badges27 silver badges37 bronze badges 2- Is your angle in radians? – Ivan Sivak Commented Jan 23, 2015 at 14:46
- 1 Caveat: most polar systems are positive for rotation counter-clockwise, and negative for clockwise. – amphetamachine Commented Jan 23, 2015 at 14:54
2 Answers
Reset to default 11Your formulas are correct, but you need to use the angle in radians instead of degrees:
radians = degrees * (Math.PI/180)
And if you want to rotate it clockwise, notice that your angle is -90 degrees instead of 90. Or, consider it 90 but change the formula to:
radians = -degrees * (Math.PI/180)
Edit:
According to your last edit, probably you get the following result:
[6.123233995736766e-17, -1]
This is because the puter cannot store "infinite" numbers. But, as you can see that number is very small, so it can be considered 0
. You can round the result.
E.g.:
var rotateVector = function(vec, ang)
{
ang = -ang * (Math.PI/180);
var cos = Math.cos(ang);
var sin = Math.sin(ang);
return new Array(Math.round(10000*(vec[0] * cos - vec[1] * sin))/10000, Math.round(10000*(vec[0] * sin + vec[1] * cos))/10000);
};
And test it using:
rotateVector([1,0], 90)
Result:
[0, -1]
I later figured out that PVector
has a method for it: rotate(angle)