跟随Sebastian Graves黑魂教程遇AnimatorHandler报错及移动异常求助
解决Sebastian Graves黑魂风格Unity教程第2集的两个问题
问题1:Script error (AnimatorHandler): Update() can not take parameters
Unity中MonoBehaviour的Update()是引擎自动调用的固定生命周期方法,不允许带参数。你在AnimatorHandler里定义了带参数的Update(float verticalMovement, float horizontalMovement),这会触发签名冲突错误。
修复步骤:
- 将带参数的方法改名,比如改为
UpdateAnimatorValues:
public void UpdateAnimatorValues(float verticalMovement, float horizontalMovement) { // 原方法内的逻辑保持不变 }
- 在玩家控制脚本(如
PlayerController)的Update()或FixedUpdate()中,调用这个改名后的方法并传入移动参数:
// 获取输入值 float vertical = Input.GetAxis("Vertical"); float horizontal = Input.GetAxis("Horizontal"); // 调用AnimatorHandler的方法 animatorHandler.UpdateAnimatorValues(vertical, horizontal);
问题2:相机与玩家同时移动时角色移动异常
这种方向错乱的核心原因是输入未根据相机视角做坐标转换,导致角色移动方向基于世界坐标,而非玩家当前看到的相机视角。
修复步骤:
- 在玩家控制脚本中,将原始输入向量转换为相对于相机的本地方向:
// 获取相机的水平前向和右向向量(忽略Y轴,避免上下移动影响) Vector3 cameraForward = Camera.main.transform.forward; cameraForward.y = 0; cameraForward.Normalize(); Vector3 cameraRight = Camera.main.transform.right; cameraRight.y = 0; cameraRight.Normalize(); // 计算基于相机视角的移动方向 Vector3 moveDirection = cameraForward * vertical + cameraRight * horizontal; moveDirection.Normalize();
- 将世界空间的移动方向转换为角色本地坐标系的轴向值,再传递给
AnimatorHandler:
// 转换为角色本地空间的垂直/水平值 float localVertical = Vector3.Dot(moveDirection, transform.forward); float localHorizontal = Vector3.Dot(moveDirection, transform.right); animatorHandler.UpdateAnimatorValues(localVertical, localHorizontal);
- 同步修正角色旋转逻辑,确保朝向与相机视角匹配:
if (moveDirection.magnitude > 0.1f && animatorHandler.canRotate) { Quaternion targetRotation = Quaternion.LookRotation(moveDirection); transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, Time.deltaTime * 10f); }
内容的提问来源于stack exchange,提问作者Milk is good
相关产品推荐
相关产品推荐

