Way to move the camera
1. Create a component which traces “Player”
It creates a component which trace “Player”. This component has some function following.
- Get the position of “Player”.
- Adjust a coordinate of the Player’s position every frame.
So, at first, it creates the “Follow Player” component. Then add “Main Camera” to it.
- Select “Main Camera” in Hierarchy View.
- Click the “Add Component” button in Inspector View.
- Select “New Script” and add “Follow Player”.
- Move “FollowPlayer.cs”, is under Assets, to Assets/Script folder in Project Browser.
Next, double click “FollowPlayer” to invoke code editor.
2. Way to trace player
It makes tracing function from getting an object’s position. Write a source code below in “FollowPlayer.cs”.
using UnityEngine;
using System.Collections;
public class FollowPlayer : MonoBehaviour
{
public Transform target; // Reference to target
void Update ()
{
// set target’s position to oneself
GetComponent<Transform>().position = target.position;
}
}
Look component of “Main Camera” and confirm what add term of target in “Follow Player”. Drag & drop “Player” onto this term.
Let’s start the game. Game View shows a view like the below picture as FPS.
3. Set offset to a component
Change a camera point like TPS that have an appropriate distance to ball. So, add a function which maintains the distance between “Player” and “Main Camera” when starting the game. The function is created by below sub-functions.
- Get a relative distance between “Player” and “Main Camera” when starting the game.
- Set the position of the camera to “Player’s position + relative distance” every frame.
At first, Set the position and rotation to “Main Camera” like a below picture.
Next, Change a source code.
using UnityEngine;
using System.Collections;
public class FollowPlayer : MonoBehaviour
{
public Transform target; // Reference to target
private Vector3 offset; // relative distance
void Start ()
{
// Get relative distance between “Player” and “Main Camera”
offset = GetComponent<Transform>().position - target.position;
}
void Update ()
{
// Set “Player’s position + relative distance” to oneself
GetComponent<Transform>().position = target.position + offset;
}