UPDATE: Check out this script from my framework for something more robust.
How It Works
This system will check whether a Main Camera exists and create one if it doesn’t, so you can actually position your Main Camera wherever you want (just turn off this script during testing). It will then center the Main Camera on an object that is a child of the player object (identified by tag). The reason we don’t look at the player object itself is because the camera will then focus on the feet of the player. By focusing on a child object, we can always have our Main Camera focus on a particular part of the player, such as the head.
1. We will identify the focus of our Main Camera using tags, so it’s important to specify a tag via the Edit -> Project Settings -> Tags and Layers menu. By default, the script looks for a tag called “CameraFocus”.
2. Now we need to create this empty game object and position it. In the menus, use GameObject -> Create Empty. Make this object a child of your player object and then position it where you want the camera to focus.
3. Make five C# script files. Name them:
Attach the thirdPersonController, thirdPersonMotor, and thirdPersonAnimator scripts to your player object.
4. Open each script and add the following code to each. Note that in thirdPersonCamera, thirdPersonMotor, and thirdPersonAnimator, there are some variables that may need to be modified to fit your project! (check the comments)
- thirdPersonController: http://pastebin.com/7zZUiNMA
- thirdPersonMotor: http://pastebin.com/dLVURvRy
- thirdPersonCamera: http://pastebin.com/Vy84iQSp
- thirdPersonCameraHelper: http://pastebin.com/VhjXcxRM
- thirdPersonAnimator: http://pastebin.com/6RdPzyEy
5. Make sure your player character and ALL child objects (except for the camera child object) has the tag “Player”. Also, set the Layer to “Ignore Raycast” and be sure to apply the layer to all child objects. This is because the system uses raycasts to handle occlusion clipping and adjustment. This is so when the character is obstructed by the camera, the camera will automatically zoom in. The script also causes the camera to zoom back out once the obstruction is no longer there.
And That’s It!
The result is a camera and movement system used in many modern-day MMOs such as World of Warcraft and Guild Wars 2. If you want to customize the character’s movement system, add the custom movement code to thirdPersonMotor.cs and any animation code to thirdPersonAnimator.cs