Unity玩家角色无法移动问题排查求助
玩家角色无法移动排查(Unity新输入系统)
问题描述
使用Unity 2022.2.0b14 + Input System 1.2.0编写的玩家移动脚本无报错,但Play模式下方向键无法控制角色移动,代码如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.InputSystem; public class PlayerController : MonoBehaviour { public float moveSpeed = 1f; public float CollisionOffset = 0.05f; public ContactFilter2D movementFilter; Vector2 movementInput; Rigidbody2D rb; List<RaycastHit2D> castCollisions = new List<RaycastHit2D>(); void Start() { rb = GetComponent<Rigidbody2D>(); } private void FixedUpdate() { if (movementInput != Vector2.zero) { int count = rb.Cast( movementInput, movementFilter, castCollisions, moveSpeed * Time.fixedDeltaTime + CollisionOffset ); if (count == 0) { rb.MovePosition(rb.position + movementInput * moveSpeed * Time.fixedDeltaTime); } } } void onMove(InputValue movementValue) { movementInput = movementValue.Get<Vector2>(); } }
排查与修复步骤
1. 修复输入回调方法的大小写问题
新输入系统的回调方法名严格区分大小写,代码中的onMove需改为OnMove(首字母大写),否则输入系统无法识别绑定的回调:
void OnMove(InputValue movementValue) { movementInput = movementValue.Get<Vector2>(); }
2. 检查输入动作的绑定设置
- 打开你的
.inputactions资源文件 - 找到
Move动作,确认已绑定方向键(或WASD)输入 - 确保动作的
Type为Value,Control Type为Vector2
3. 验证Player Input组件配置
- 玩家对象必须挂载
Player Input组件 - 组件配置要求:
Actions字段选择你的输入动作资源Behavior选择Send Messages(需保证回调方法名正确)或Invoke Unity Events(需手动绑定OnMove到Move事件)
4. 检查Rigidbody2D参数
- 确认玩家对象上的
Rigidbody2D组件正常挂载 Body Type需设为Dynamic或Kinematic(Static会完全阻止移动)- 根据游戏类型调整
Gravity Scale,避免重力导致角色无法正常移动
5. 调试输入值是否接收
在OnMove方法中添加日志,确认输入是否被捕获:
void OnMove(InputValue movementValue) { movementInput = movementValue.Get<Vector2>(); Debug.Log($"Movement Input: {movementInput}"); }
进入Play模式按方向键,查看Console是否有输入值输出。若无输出,回到步骤2、3检查输入绑定。
6. 排查ContactFilter2D设置
- 确保
movementFilter的Use Layer Mask已勾选,并设置了正确的碰撞图层(避免误检测无关碰撞体) - 可暂时将
movementFilter设为默认值,测试是否是碰撞检测阻止了移动
内容的提问来源于stack exchange,提问作者Sai Prashanth
相关产品推荐
相关产品推荐

