目次

039 追従するカメラ

概要

GameObjectが動くとカメラもそれに従って移動します。

ソースコード

using UnityEngine;
using System.Collections;
 
public class CameraScript : MonoBehaviour
{
	GameObject target;
 
	void Start ()
	{
		target = GameObject.FindGameObjectWithTag("playerTag");
	}
 
	void Update ()
	{
		transform.LookAt( target.transform.position );
 
		Vector3 vecCamera = transform.position - target.transform.position;
		vecCamera = Vector3.Normalize( vecCamera );
 
		float distance = 5.0f;
		Vector3 cameraTargetPosition = target.transform.position + vecCamera * distance;
 
		float damping = 1.0f;
		transform.position = Vector3.Lerp( transform.position, cameraTargetPosition, damping * Time.deltaTime );
	}
}

カメラのGameObjectに割り当てる。移動量はLerp で補間。

Vector3.SmoothDampを使う場合

Vector3 velocity = Vector3.zero;
transform.position = Vector3.SmoothDamp( transform.position, cameraTargetPosition, ref velocity, damping );