Unity使用New Input Package无法移动角色的问题求助
Unity角色无法移动问题求助
我是Unity新手,跟着教程学习,编写了教程42:00处的代码后编译,角色完全无法移动。已严格按照视频步骤操作,但找不到问题所在。
相关版本信息:
- Unity: 2021.3.7f1
- Input System: 1.3.0
- Visual Studio Code Editor: 1.2.5
- Test Framework: 1.1.33
我的代码如下:
using System.Collections; using System.Collections.Generic; using UnityEngine.InputSystem; using UnityEngine; //Take and handle input and movement from the character 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>(); // Start is called before the first frame update void Start() { rb = GetComponent<Rigidbody2D>(); } private void FixedUpdate(){ //If movement input is not 0, try to move if(movementInput != Vector2.zero){ bool success = TryMove(movementInput); if(!success){ success = TryMove(new Vector2(movementInput.x, 0)); } if(!success){ success = TryMove(new Vector2(0, movementInput.y)); } } } private bool TryMove(Vector2 direccion){ //Check for Potencial Collisions int count = rb.Cast( direccion, // X and Y values between -1 and 1 that represent the direction from the body to look for collision movementFilter, // The setting that determines where a collision can occur on such as layers to collide with castCollisions, // Lists of collisions to store the found collisions into after the Cast is finished moveSpeed = Time.fixedDeltaTime + collisionOffset); // The amount to cast equal to the movement plus an offset if(count == 0){ rb.MovePosition(rb.position * direccion * moveSpeed * Time.fixedDeltaTime); return true; } else{ return false; } } void OnMove(InputValue movementValue){ movementInput = movementValue.Get<Vector2>(); } }
问题排查与修正
代码里有两处关键错误导致角色无法移动:
rb.Cast距离参数的运算符错误
你使用了赋值运算符=替代乘法运算符*,正确写法应为moveSpeed * Time.fixedDeltaTime + collisionOffset。错误的赋值会把moveSpeed设置为极小值(默认Time.fixedDeltaTime是0.02),后续移动几乎不可见。rb.MovePosition位置计算逻辑错误
你用乘法rb.position * direccion * ...计算新位置,正确逻辑应该是加法:rb.position + direccion * moveSpeed * Time.fixedDeltaTime。乘法会导致角色位置异常,甚至直接归0,自然无法正常移动。
修正后的TryMove方法:
private bool TryMove(Vector2 direccion){ //Check for Potencial Collisions int count = rb.Cast( direccion, movementFilter, castCollisions, moveSpeed * Time.fixedDeltaTime + collisionOffset); if(count == 0){ rb.MovePosition(rb.position + direccion * moveSpeed * Time.fixedDeltaTime); return true; } else{ return false; } }
额外检查项:
- 确保Player对象挂载了
Rigidbody2D组件,且Body Type设置为Dynamic,否则MovePosition无法生效。 - 验证Input System输入绑定正确,可在
OnMove方法中添加Debug.Log(movementInput)测试输入是否正常接收。
内容的提问来源于stack exchange,提问作者Tomas Iniguez
相关产品推荐
相关产品推荐

