遊テックプログラミング教室

プログラミングノートNOTE

プレイヤーを追従するカメラ

Unityでカメラにプレイヤーを追従させたい場合に使うスクリプトです。

まずは、MainCameraとプレイヤーの位置関係を、カメラが追従する時の位置関係に合わせておきましょう。

そして、CameraManagerというスクリプトを作り、以下のコードを入力して、MainCameraにアタッチ(付けて)実行してみましょう。

カメラがプレイヤーを追従してくれるはずです。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraManager : MonoBehaviour
{
    private GameObject player;
    private Vector3 offset;

    // Use this for initialization
    void Start()
    {
        
        player = GameObject.Find("Player");//Playerは必要に応じて変更する

        // MainCameraとplayerとの位置関係(方向+距離)を求めて変数offsetに入れる
        offset = transform.position - player.transform.position;
    }

    // Update is called once per frame
    void Update()
    {
        //Startで求めたプレイヤーとの位置関係を常にキープするようにカメラを動かす
        transform.position = player.transform.position + offset;
    }
}