根据游戏类型的不一样,会需要各种各样的摄像机,下面将分享三种典型的摄像机类型:(1)地下城摄像机;(2)第三人称跟随摄像机;(3)鼠标控制旋转摄像机。将这些控制脚本拖动到场景的MainCamera上即可:
看向固定目标的Camera的基本实现,主要使用transform.LookAt函数来实现:
public class LookAtCamera : MonoBehaviour { public GameObject target = null; void LateUpdate() { if (target == null) return; transform.LookAt(target.transform); } }
(1)地下城摄像机,就像暗黑3那样的,摄像机和角色保持固定距离和角度,摄像机不会绕着角色旋转:
public class DungeonCamera : MonoBehaviour { public GameObject target = null; public Vector3 offset = Vector3.zero; public float damping = 1; void Start() { if (target == null) return; offset = transform.position - target.transform.position; } void LateUpdate() { if (target == null) return; Vector3 desiredPosition = target.transform.position + offset; // 平滑变换过程,即不要立即变换 Vector3 position = Vector3.Lerp(transform.position, desiredPosition, Time.deltaTime * damping); transform.position = position; // Camera始终看向目标 transform.LookAt(target.transform.position); } }
(2)第三人称跟随摄像机,比较典型的3D游戏摄像机,摄像机会绕着角色一起旋转:
public class FollowCamera : MonoBehaviour { public GameObject target = null; public Vector3 offset = Vector3.zero; public float damping = 1; void Start() { if (target == null) return; offset = transform.position - target.transform.position; } void LateUpdate() { float currentAngle = transform.eulerAngles.y; float desireAngle = target.transform.eulerAngles.y; // 平滑角度变换 float angle = Mathf.LerpAngle(currentAngle, desireAngle, Time.deltaTime * damping); Quaternion rotation = Quaternion.Euler(0, angle, 0); transform.position = target.transform.position + (rotation * offset); transform.LookAt(target.transform); } }
(3)鼠标控制角色旋转摄像机,注意,鼠标控制旋转时不要做Lerp,因为鼠标控制需要精确,比如玩CS的时候,鼠标控制角色转动还要过程那还能玩吗
public class MouseAimCamera : MonoBehaviour { public GameObject target = null; public Vector3 offset = Vector3.zero; public float rotateSpeed = 5; void Start() { offset = target.transform.position - transform.position; } void LateUpdate() { // 根据鼠标左键旋转目标物体 float horizontal = Input.GetAxis("Mouse X") * rotateSpeed; target.transform.Rotate(0, horizontal, 0); float desiredAngle = target.transform.eulerAngles.y; Quaternion rotation = Quaternion.Euler(0, desiredAngle, 0); transform.position = target.transform.position - (rotation * offset); transform.LookAt(target.transform); } }
另外为了辅助测试,使用了下面的角色移动/旋转控制脚本:
using UnityEngine; using System.Collections; public class Player : MonoBehaviour { public float movementSpeed = 10; public float turningSpeed = 60; void Update() { float horizontal = Input.GetAxis("Horizontal") * turningSpeed * Time.deltaTime; transform.Rotate(0, horizontal, 0); float vertical = Input.GetAxis("Vertical") * movementSpeed * Time.deltaTime; transform.Translate(0, 0, vertical); } }
参考:http://code.tutsplus.com/tutorials/unity3d-third-person-cameras--mobile-11230
时间: 2024-10-10 01:29:48