Welcome

Spherical Coordinates for a Third-person perspective

The Idea

I have always been fond of the Third person perspective in video games and after my course about multivariate analysis, I finally understood how I can pull it off.

A video game typically uses Cartesian coordinates (X Y Z) for the game logic but in order to have a rotating camera around the player, I implemented a Coordinate system conversion in order to interface with the coordinates of the game. The Cartesian coordinates are converted to Spherical coordinates with the variables now being:

One thing to keep in mind is that formula for phi does not return the desired angle, for example, x<0. A modified version of Acrtan called Arctan2 is used that always returns the angle for any given x and y.

A Third person perspective for a character

The Code

I decided to use the Game engine Unity to make the camera and I started with creating a blank scene and put a plane to represent the ground and a capsule to represent the player.

I created a script called cameraController and made sure that I could link the camera and the capsule to the script to get information like its world position. If you want to you can read the code here.

The lonely player in the vast open void.

I also made a Character controller to move the capsule but it had to move in the expected direction as seen from the camera so with some simple vector mathematics I defined the controller here.

Notice how I determine the desired direction for the buttons A and D with a cross product of the projected vector from the camera to the capsule onto the xz-plane and a vector normal to that plane. This returns the vector orthogonal to those two vectors and is the direction I want the capsule to travel in.

The Demo

Here is a demo of the code running. I did add some slight movement interpolation to smooth out the animation of both the camera movement and the rotation of the camera to make it more presentable.

I made a little course that I used to test the movement and camera controls.

That´s it for this post. If you have any questions about the code ask them below!

Thanks for reading!

Douglas Halse signing off.

1 thought on “Spherical Coordinates for a Third-person perspective

Leave a Reply

Your email address will not be published. Required fields are marked *