Finding rotation of a rigidbody

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By percy1000

Say I have a rigidbody dice cube, which is thrown and tumbles etc. How can I find the orientation of the rigid body when it comes to rest so I can tell which face is upwards?
I guess I could have a node on each face and see which is highest on the z axis but I have a feeling it should be more elegant than this!

y axis, I mean

percy1000 | 2019-01-30 08:29

:bust_in_silhouette: Reply From: wombatstampede

Each Spatial (this includes rigidbodies) has the attributes transform and global_transform.

transform.basis holds three vectors which represent the axis directions of your node.

For example:
The y-axis vector (transform.basis.y) for the initial position of your cube is (x=0,y=1,z=0).

If your cube lands upside down then it is (x=0,y=-1, z=0) because the cube is rotated and its y-axis which originally pointed up now points down.

By combined checking the values of the axes you should be able to determine the rotation of the cube.


if transform.basis.y.y>0.99: #top is up
  print("1 is up")
elif transform.basis.y.y<-0.99: #top is at bottom
  print("6 is up")
elif transform.basis.x.y>0.99: #right side is up
  print("2 is up")
elif transform.basis.x.y<-0.99: #left side is up
  print("5 is up")
elif transform.basis.z.y>0.99: #front side is up
  print("3 is up")
elif transform.basis.z.y<-0.99: #back side is up
  print("4 is up")
  print("dice is angled")

This is untested code, may contain errors. But I hope that you get the idea… I did not use exact == 1 checks because the value may not be exactly 1 but 0.99999. If unsure then it may be a good idea to just print out the transforms basis x/y/z vectors.

Hope it works (& helps). :wink:

Thank you, that is an amazingly comprehensive answer!

percy1000 | 2019-01-30 16:55