修改Unity角色控制脚本,实现角色始终朝向相机
修改Unity角色朝向逻辑:静止时始终面向相机
原脚本仅在角色移动时才会让面部朝向相机,要实现静止状态下也始终朝向相机,只需将旋转相关的逻辑从移动判断的if块中独立出来,确保每一帧都执行旋转更新,而移动逻辑保留在原判断内即可。
修改后的完整代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TPM : MonoBehaviour { CharacterController controller; public Transform cam; public float speed = 6f; public float turnSmoothTime = 0.1f; float turnSmoothVelocity; private void Start() { controller = GetComponent<CharacterController>(); } private void Update() { float horizontal = Input.GetAxis("Horizontal"); float vertical = Input.GetAxis("Vertical"); Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized; // 旋转逻辑:独立出来,无论是否移动都执行 float targetAngle; if (direction.magnitude >= 0.1f) { // 有移动输入时,目标朝向基于输入+相机方向 targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y; } else { // 无移动输入时,直接朝向相机的正前方(忽略输入,只看相机方向) targetAngle = cam.eulerAngles.y; } float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime); transform.rotation = Quaternion.Euler(0f, angle, 0f); // 移动逻辑:仅当有输入时执行 if (direction.magnitude >= 0.1f) { Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward; controller.Move(moveDir.normalized * speed * Time.deltaTime); } } }
关键修改说明
- 把旋转相关的代码从原
if(direction.magnitude >= 0.1f)块中移出,确保每一帧都会计算目标朝向并更新角色旋转。 - 新增判断:当角色静止(无移动输入)时,目标朝向直接设为相机的Y轴旋转角度,让角色始终正对相机前方;当有移动输入时,保持原逻辑,让角色朝向输入对应的相机相对方向。
- 移动逻辑保留在原判断内,确保只有有输入时才触发移动。
内容的提问来源于stack exchange,提问作者George Zyn
相关产品推荐
相关产品推荐

