This section will guide you to create the
CameraWork script to follow along your player as you play this game.
This section has nothing to do with networking, so it will be kept short.
Creating the CameraWork Script
- Create a new C# script called
Replace the the content of
CameraWorkwith the following:
- Save the Script
The maths behind following the player is tricky if you've just started with real time 3d, Vectors and Quaternion based Mathematics. So I'll spare you with trying to explains this within this tutorial. However if you are curious and want to learn, do not hesitate to contact us, We'll do are best to explain it.
However, this script is not just about crazy mathematics, something important is also setup; the ability to control when the behaviour should actively follow the player. And this is important to understand: why would we want to control when to follow a player.
Typically, let's imaging what would happen if it was always following the player.
As you connect to a room full of players, each
CameraWork script on the other players instances would fight to control the "Main Camera" so that it looks at its player...
Well we don't want that, we want to only follow the local player that represents the user behind the computer.
Once we've define the problem that we have only one camera but several Player instances, we can easily find several ways to go about it.
- Only attach the
CameraWorkscript on the local player.
- Control the
CameraWorkbehaviour by turning it off and on depending on whether the player it as to follow is the local player or not.
- Have the
CameraWorkattached to the Camera and watch out for when there is a local player instance in the scene and follow that one only.
These 3 options are not exhaustive, many more ways can be found, but out of these 3, we'll arbitrary pick the second one. None of the above options are better or worse, however this is the one that possibly requires the least amount of coding and the most flexible... "interesting..." I hear you say :)
We've exposed a public property
followOnStartwhich we can set to true if we want to use this on a non networked environment, for example in our test scene, or in completely different scenarios
When running in our networked based game, we'll call the public method
OnStartFollowing()when we detect that the Player is a local player. This will be done in the Script
PlayerManagerthat is created and explained in the chapter Player Prefab Networking