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.
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.
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.
Hej Douglas! Vad trevligt att du har startat en egen wordpress. Jag ser fram emot att följa din karriär.