vrijdag 2 november 2012

Unity and rotations, what about the rotation point?

I've been playing around with Unity for a while now. It's a great cross platform (pc, web, mobile) tool for developing 3D games (in C# or javascript). One of the things I had to get used to was rotations, and something called a Quaternion.

I won't go into the details of Quaternions here, there are plenty of good references such as wiki. However, there was one thing that took me a while to get clear, and for that reason I'll share it with you here.

All rotations can be represented by an axis and angle. If you think about this for a while, it seems reasonable. Pick up a matchbox, imagine sticking a pin through it (the axis), hold both ends of the pin and spin the matchbox a little. Voila, a rotation.

Now an axis in 3D math notation is a vector with 3 coordinates (x,y,z) and an angle is just a number, so a 4th coordinate. This gives rise to Quaternions, which are 4 dimensional vectors, as a way of expressing and carrying out rotations (I won't bore you with the details).

The point that had me confused for a while is that a 3D vector (x,y,z) is an arrow/pin stuck through the origin of the 3D coordinate system (0,0,0). But how does that relate to the matchbox. You can stick the pin through the matchbox from below or from the side, or squiff, or .... It seemed to me that you also need to specify the rotation point (place you stick the pin in).

Turns out this is true. However, you can still express all rotations with Quaternions. the idea is that you first move (translate) the matchbox so that the origin (0,0,0) of the 3D coordinate system is at the rotation point. Then, you can perrform the rotation.

So how does this all work in Unity? Well, all GameObjects have a (non visible) pivot point. When you call transform.rotate() the rotation is around this point (default space.self).

When you have a 3D model of a six legged alien, the location of the pivot point is a bit arbitrary. It also seems to depend on what kind of 3D content creation tool you are using (say Maya). For something simple like the default Unity cube, the pivot point is in the centre of the cube (seems logical). You have a button on the editor screen to show the pivot point (toggle pivot/center).

If you want to rotate around a different point, then you can use the Unity function tranform.rotateAround which requires you to specify the rotation point as well as the axis.

Small Side Note: rotateAround() always use World coordinates, whereas rotate() can use both local/self or World (default is self, so around the gameobject pivot point).

Geen opmerkingen:

Een reactie posten