schteppe / cannon.js

A lightweight 3D physics engine written in JavaScript.
http://schteppe.github.com/cannon.js
MIT License
4.68k stars 710 forks source link

Quaternions instability #211

Open CoWayger opened 9 years ago

CoWayger commented 9 years ago

Hello I'm trying to connect my game engine in WebGL to cannon.js, but I have a trouble to convert your quaternions to euler angles. (I'm using euler angles, I never had the problem until I faced quaternions)

Function on Quaternion.js toEuler provides very unstable angles. They are ok in x axis. But y and z are behaving weird. I captured it on video. It is very noticeable on the end of video. http://youtu.be/ljd4avOFPs4 If you know where the problem could be please let me know. Thank you :)

schteppe commented 9 years ago

Maybe the euler order is wrong? What order do you use in your rendering engine?

In any case, it is often more convenient to not use euler. Use the quaternion directly or convert it to a rotation matrix.

CoWayger commented 9 years ago

I tried all 6 permutations of xyz order, none of them works stable. I woke up today and try different aproach... searched for formulas on internet: These works perfectly:

function quatToVec3(x,y,z,w){ var ax = Math.atan2(-2_y_z+2_x_w,1-2_x_x-2_y_y); var ay = Math.asin(2_x_z+2_y_w); var az = Math.atan2(-2_x_y+2_z_w,1-2_y_y-2_z_z); return [ax,ay,az]; }

It's for XYZ order. Someone will be happy if you add this order to cannon.js. Anyway thank you for awesome physics library! :)