In this example: http://deeplogic.info/project/webGL/
How can I rotate the object in the direction in which it is travelling?
In this example: http://deeplogic.info/project/webGL/
How can I rotate the object in the direction in which it is travelling?
To get rotation around z for an object moving in the direction (x, y) you can use the
Math.atan2(y,x)
method. It'll return an angle in radians. The OpenGL convention prior to ES 2 was to work in degrees, but nowadays it's up to whatever code you have to push transformations to the vertex shader. You'll probably want to convert though, in which case just multiply the result by 180 (half a circle in degrees) and divide by pi (half a circle in radians).Say your object is moving into direction D, then all you need to do is finding a vector perpendicular to that direction. In case your movement is in only one plane you can find this vector E by taking the cross product of D with the plane normal N.
This yields you with 3 vectors D, E and N. After normalization those form the base of a rotated coordinate system. You can put them into the columns of a 3×3 matrix
extend this matrix into a 4×4 homogenous one
and you can pass it to OpenGL with glMultMatrix to apply it on the matrix stack.