Unity3D第三视觉角色相机控制

经过一段时间的学习,学得以下第三视觉相机控制方法,当设置相机初始高度较高的状态下,相机有由高到低的效果,适合做为外景相机,如果是做室内相机,需要另外设计。将这个分享给大家,同时希望得到阅读者宝贵的意见,废话不多说,贴代码:

/// <summary>
/// Created by Hong Youwei
/// Created in 2015.3.25
/// </summary>

using UnityEngine;
using System.Collections;

public class CameraControl : MonoBehaviour {
	// 高度移动变化速度和旋转变化速度
	public float HeDamping = 2f;
	public float RoDamping = 3f;
	//相对主角的位置
	public float distance = 5f;
	public float height = 5f;
	
	//游戏对象和对象位置
	public GameObject target;
	Transform target_tf;
	
	// 游戏结束,相机围绕角色旋转的速度
	public float rotateSpeed = 20;
	
	void Start()
	{
		// 获取角色对象
		if (!target) {
			target = GameObject.FindGameObjectWithTag ("Player");
		}
	}
	
	void LateUpdate() {
		// 获取角色对象当前位置
		target_tf = target.transform;
		
		float wantRotationAngle = target_tf.eulerAngles.y;//想要旋转的角度 Y
		float wantHeight = target_tf.position.y + height; //想要的高度
		
		float currentRotationAngle = transform.eulerAngles.y;//当前旋转角度Y
		float currentHeight = transform.position.y;//当前高度
		
		currentRotationAngle = Mathf.LerpAngle (currentRotationAngle, wantRotationAngle, Time.deltaTime * RoDamping);//当前旋转角度差值
		currentHeight = Mathf.Lerp (currentHeight, wantHeight, Time.deltaTime * HeDamping);//当前高度差值
		
		Quaternion currentRotation = Quaternion.Euler (new Vector3 (0, currentRotationAngle, 0));//当前旋转只Y
		transform.position = target_tf.position;
		transform.position -= currentRotation * Vector3.forward * distance;//与主角的相对位置
		transform.position = new Vector3 (transform.position.x, currentHeight, transform.position.z);//设置位置,关键高度

		Quaternion mR;
		mR = Quaternion.LookRotation (target_tf.position - transform.position);//创建一个旋转
		transform.rotation = Quaternion.Slerp (transform.rotation, mR, Time.deltaTime * RoDamping);//控制跟随人物旋转
		transform.LookAt (target_tf);
	}
	
}



猜你喜欢

转载自blog.csdn.net/a3636987/article/details/44851757