游戏开发中用到的几种摄像机跟随方法(1)

固定跟随(不带旋转)

using UnityEngine;
using System.Collections;

public class CameraFollow : MonoBehaviour {

	public Transform target;//目标物体
	public float smoothing = 3;//平滑系数

	void LateUpdate () 
	{
		//目标物体要到达的目标位置 = 当前物体的位置 + 当前摄像机的位置
		Vector3 targetPos = target.position + new Vector3 (0, 9, -10);
		//使用线性插值计算让摄像机用smoothing * Time.deltaTime时间从当前位置到移动到目标位置
		this.transform.position = Vector3.Lerp (this.transform.position, targetPos, smoothing * Time.deltaTime);
	}
}

固定跟随(带旋转)

using UnityEngine;
using System.Collections;

public class CameraFollow : MonoBehaviour {

	public Transform target;//目标物体
	public float smoothing = 3;//平滑系数

	void LateUpdate () 
	{
		//目标物体要到达的目标位置 = 当前物体的位置 + 当前摄像机的位置
		Vector3 targetPos = target.position + new Vector3 (0, 9, -10);
		//使用线性插值计算让摄像机用smoothing * Time.deltaTime时间从当前位置到移动到目标位置
		this.transform.position = Vector3.Lerp (this.transform.position, targetPos, smoothing * Time.deltaTime);
		//使用Quaternion.LookRotation方法可以计算出目标位置旋转后相机需要旋转的角度
		Quaternion angle = Quaternion.LookRotation (target.position - this.transform.position);
		//使用球形差值计算可以得到从当前的位置旋转到移动后的位置
		this.transform.rotation = Quaternion.Slerp (this.transform.rotation, angle, smoothing * Time.deltaTime);
	}
}


第三人称跟随

using UnityEngine;
using System.Collections;

public class CameraFollow : MonoBehaviour {

	public Transform target;//目标物体
	public float distance = 10;//距离
	public float height = 5;//高度
	public float heightDamping = 2;//高度的阻尼系数
	public float rotationDamping = 3;//旋转的阻尼系数

	void LateUpdate()
	{
		//如果场景中有Player物体
		if (GameObject.FindWithTag ("Player")) {
			//如果目标物体为空
			if (!target)
				//重新取得目标物体
				target = GameObject.FindWithTag ("Player").transform;
			//摄像机最终旋转的角度
			float wantedRotationAngle = target.eulerAngles.y;
			//摄像机最终的高度
			float wantedHeight = target.position.y + height;
			//摄像机当前的角度
			float currentRotationAngle = transform.eulerAngles.y;
			//摄像机当前的高度
			float currentHeight = transform.position.y;

			currentRotationAngle = Mathf.LerpAngle (currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);
			currentHeight = Mathf.Lerp (currentHeight, wantedHeight, heightDamping * Time.deltaTime);
			//相机当前的旋转
			Quaternion currentRotation = Quaternion.Euler (0, currentRotationAngle, 0);
			//相机的实际位置 = 目标位置 - 相机当前的正方向位置*距离 
			Vector3 pos = target.position - currentRotation * Vector3.forward * distance;
			//相机实际位置的高度
			pos.y = currentHeight;
			//最后把实际位置赋值给相机
			transform.position = pos;
			//摄像机始终朝向目标位置
			transform.LookAt (target);
		}
	}
}
未完待续

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值