LoginSignup
11
14

More than 5 years have passed since last update.

キャラに追従するカメラ

Last updated at Posted at 2017-10-21

キャラを用意

Colliderの形状がカプセルなどの場合は、転がってしまわないように、RigidbodyのFreeze Rotationのx,zにチェックを入れる。

カメラをキャラの子要素にする

Chara
 └ MainCamera

camera.gif

スクリプトで操作する

カメラに以下のスクリプトをアタッチ

CameraController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraController : MonoBehaviour {
    public Transform target;
    public float smoothing = 5f;
    private Vector3 offset;

    void Start () {
        offset = transform.position - target.position;
    }

    void Update () {
        Vector3 targetCamPos = target.position + offset;
        transform.position = Vector3.Lerp(
            transform.position,
            targetCamPos,
            Time.deltaTime * smoothing
        );
    }
}

cameraControl.gif

汎用スクリプトを使う

Scripts > UnityStandardAssets.Utility > Smooth Follow

もしくは

Scripts > UnityStandardAssets.Utility > Smooth Target

参考
Unityでカメラの設定とキャラクターの追従をさせる

常にプレイヤーの進行方向後ろから追従させる

背面ベクトルを何倍かさせてカメラの位置ベクトルを決定する。

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

public class ChaseCamera : MonoBehaviour {

    private GameObject player;
    private Vector3 prevPlayerPos;
    private Vector3 posVector;
    public float scale = 3.0f;
    public float cameraSpeed = 1.0f;

    void Start () {
        player = GameObject.Find ("CameraTarget");
        prevPlayerPos = new Vector3 (0, 0, -1);
    }

    void Update () {
        Vector3 currentPlayerPos = player.transform.position;
        Vector3 backVector = (prevPlayerPos - currentPlayerPos).normalized;
        posVector = (backVector == Vector3.zero) ? posVector : backVector;
        Vector3 targetPos = currentPlayerPos + scale * posVector;
        targetPos.y = targetPos.y + 0.5f;
        this.transform.position = Vector3.Lerp (
            this.transform.position, 
            targetPos, 
            cameraSpeed * Time.deltaTime
        );
        this.transform.LookAt (player.transform.position);
        prevPlayerPos = player.transform.position;
    }
}

正面ベクトルをとれば前から撮影するカメラに変わる。

void Update () {
    Vector3 currentPlayerPos = player.transform.position;
    Vector3 frontVector = (currentPlayerPos - prevPlayerPos).normalized;
    posVector = (frontVector == Vector3.zero) ? posVector : frontVector;
    Vector3 targetPos = currentPlayerPos + scale * posVector;
    targetPos.y = targetPos.y + 0.5f;
    this.transform.position = Vector3.Lerp (
        this.transform.position,
        targetPos, 
        cameraSpeed * Time.deltaTime
    );
    this.transform.LookAt (player.transform.position);
    prevPlayerPos = player.transform.position;
}
11
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
14