WebGL - Rotating object in the direction it is travelling

心已入冬 提交于 2019-12-10 11:49:48

问题


In this example: http://deeplogic.info/project/webGL/

How can I rotate the object in the direction in which it is travelling?


回答1:


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).




回答2:


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.

E = D × 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

D_x E_x N_x
D_y E_y N_y
D_z E_z N_z

extend this matrix into a 4×4 homogenous one

D_x E_x N_x 0
D_y E_y N_y 0
D_z E_z N_z 0
  0   0   0 1

and you can pass it to OpenGL with glMultMatrix to apply it on the matrix stack.



来源:https://stackoverflow.com/questions/7288478/webgl-rotating-object-in-the-direction-it-is-travelling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!