Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Rotating a vector around a certain point

I am trying to rotate a vector around a certain point on the vector(in C++):

1 2 3
4 5 6
7 8 9

rotated around the point (1,1) (which is the "5") 90 degrees would result in:

7 4 1
8 5 2
9 6 3

Right now I am using:

x = (x * cos(90)) - (y * sin(90))
y = (y * cos(90)) + (x * sin(90))

But I don't want it rotated around (0,0)

like image 978
Erik Ahlswede Avatar asked Mar 06 '09 22:03

Erik Ahlswede


People also ask

How do you rotate a point around the origin?

Direction of Rotation: Counterclockwise or clockwise direction. Positive rotations are counterclockwise. Negative rotations are clockwise. For example, to rotate the point (2, 5) counterclockwise about the origin by 90 degrees, we use the rule: (x,y)→(−y,x) ( x , y ) → ( − y , x ) .

How do you rotate a vector by 90 degrees?

Normally rotating vectors involves matrix math, but there's a really simple trick for rotating a 2D vector by 90° clockwise: just multiply the X part of the vector by -1, and then swap X and Y values.


2 Answers

The answer depends on your coordinate system.

Computer graphics coordinate system, with (0,0) at Top left

If you are using a computer graphics vector implementation where (0,0) is the top left corner and you are rotating around the point (dx, dy), then the rotation calculation, including the translation back into the original coordinate system, would be:

x_rotated =      ((x - dx) * cos(angle)) - ((dy - y) * sin(angle)) + dx
y_rotated = dy - ((dy - y) * cos(angle)) + ((x - dx) * sin(angle))

Physics/Maths coordinate system, with (0,0) at Bottom left

If you are using a more traditional real world coordinate system, where (0,0) is the bottom left corner, then the rotation calculation, around the point (dx, dy) including the translation back into the original coordinate system, would be:

x_rotated = ((x - dx) * cos(angle)) - ((y - dy) * sin(angle)) + dx
y_rotated = ((x - dx) * sin(angle)) + ((y - dy) * cos(angle)) + dy

Thanks to mmx for their comment on Pesto's post, and to SkeletorFromEterenia for highlighting an error in my implementation.

like image 160
Mark Booth Avatar answered Nov 01 '22 06:11

Mark Booth


The solution is to translate the vector to a coordinate system in which the center of rotation is (0,0). Apply the rotation matrix and translate the vector back to the original coordinate system.

dx = x of rotation center  
dy = y of rotation center

V2 = V - [dx, dy, 0]  
V3 = V2 * rotation matrix  
Result = V3 + [dx, dy, 0]
like image 41
mmx Avatar answered Nov 01 '22 06:11

mmx