Monday, January 18, 2010

2D Rotation

I've got a vector, which represents the direction an agent is "facing" within a maze's frame of reference.  OpenGL will allow me to draw the agent's rotation by rotating its own frame of reference--but the agent's "facing" vector remains unchanged within the agent's frame of reference.  I am unable to determine the vector's value in the maze's frame of reference from OpenGL.

What I need, then, is to do the rotation myself, and pass the result into OpenGL (without using OpenGL to rotate the agent's frame of reference).  In this case, I will be rotating a single vector value around the z-axis, so it looks just like a two-dimensional rotation.

If I rotate the vector represented by the red line by θ (theta), the result will be the vector represented by the green line.  α (alpha), is the angle between the x-axis and the vector.  We'll call the original vector V0 (with components x0, y0), and the vector resulting from the rotation V1 (with x1, y1).  The length of the vector is r.

x0 and y0 are found by simple trigonometric functions on α:
x0 = r∙cos(α)
y0 = r∙sin(α)

Likewise, x1 and y1 are found in terms of α and θ:
x1 = r∙cos(α + θ)
y1 = r∙sin(α + θ)
 Since cos(a+b) = cos(a)∙cos(b) - sin(a)∙sin(b), and sin(a+b) = sin(a)∙cos(b) + cos(a)∙sin(b):
x1 = r( cos(α)∙cos(θ) - sin(α)∙sin(θ) )
x1 = r∙cos(α)∙cos(θ) - r∙sin(α)∙sin(θ)
x1 = x0∙cos(θ) - y0∙sin(θ)

y1 = r( sin(α)∙cos(θ) + cos(α)∙sin(θ) )
y1 = r∙sin(α)∙cos(θ) + r∙cos(α)∙sin(θ)
y1 = y0∙cos(θ) + x0∙sin(θ)
y1 = x0∙sin(θ) + y0∙cos(θ)
These equations can be represented in matrix form, but for now they suffice to rotate the agent's "facing" vector.

No comments:

Post a Comment