You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修改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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 09:45:34