ROLL-A-BALL TUTORIAL #4


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.

  1. Get the position of “Player”.
  2. 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.

  1. Select “Main Camera” in Hierarchy View.
  2. Click the “Add Component” button in Inspector View.
  3. Select “New Script” and add “Follow Player”.
  4. 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”.

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.

  1. Get a relative distance between “Player” and “Main Camera” when starting the game.
  2. 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.

FollowPlayer.cs
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;
    }

Let's play the game.