Reputation: 313
I have a implemented this tutorial https://webglfundamentals.org/webgl/lessons/webgl-2d-rotation.html but there's some things I don't understand.
In the shader the rotations is applied by creating a new vec2 rotatedPosition
:
...
vec2 rotatedPosition = vec2(
a_position.x * u_rotation.y + a_position.y * u_rotation.x,
a_position.y * u_rotation.y - a_position.x * u_rotation.x);
...
but how exactly is this actually providing a rotation? With rotation=[1,0]->u_rotation=vec2(1,0)
the object is rotated 90 degrees. I understand the unit circle maths, what I don't understand is how the simple equation above actually performs the transformation.
a_position
is a vec2, u_rotation
is a vec2. If i do the calculation above outside the shader and feed it into the shader as a position, that position simply becomes vec2 rotatedPosition = vec2(y, -x)
. But inside the shader then this calculation vec2 rotatedPosition = vec2( a_position.x * u_rota...
performs a rotation (it does not become vec2(y, -x)
but instead uses a rotation matrix).
What magic ensures that rotatedPostion
actually gets rotated when the vec2 is calculated inside the shader, as opposed to outside the shader? What 'tells' the vertex shader that it's supposed to do a rotation matrix calculation, as opposed to normal arithmetic?
Upvotes: 1
Views: 316
Reputation: 1579
Check the 2D rotation in Wikipedia. The magic (linear algebra) is that your u_rotation
vector probably has the cos
and sin
from the angle θ
in radians.
The rotation is counterclockwise of a two-dimensional Cartesian coordinate system. Example:
// your point
a = (a.x, a.y) = (1, 0)
// your angle in radians
θ = PI/2
// intermediaries
cos(θ) = 0
sin(θ) = 1
// your rotation vector
r = (r.x, r.y) = (cos(θ), sin(θ)) = (0, 1)
// your new `v` vector, the rotation of `a` around
// the center of the coordinate system, with angle `θ`
// be careful, 'v' to be a new vector, because if you try
// to reuse 'a' or 'r' you will mess the math
v.x = a.x * r.x - a.y * r.y = 1 * 0 - 0 * 1 = 0
v.y = a.x * r.y + a.y * r.x = 1 * 1 + 0 * 0 = 1
Here v
will be x=0, y=1
as it should be. Your code does not seem to do the same.
Maybe you also want to know, how to rotate the point around an arbitrary other point, not always around the center of the coordinate system. You have to translate your point relatively to the new rotation center, rotate it, then translate it back like this:
// your arbitrary point to rotate around
center = (10, 10)
// translate (be careful not to subtract `a` from `center`)
a = a - center;
// rotate as before
...
// translate back
a = a + center;
Upvotes: 1