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

Unity 2021.3.20f1中2D俯视角色无法移动问题求助

2D俯视RPG玩家角色无法移动(无控制台报错)

我跟着一款2D俯视RPG教程学到40分钟左右,测试教程提供的代码后发现玩家角色完全无法移动,且控制台无任何报错信息。

使用的代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

// Takes and handles input and movement for a player 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(movementInput != Vector2.zero){
            int count = rb.Cast(
                movementInput, 
                movementFilter, 
                castCollisions, 
                moveSpeed * Time.fixedDeltaTime + collisionOffset); 
    
            rb.MovePosition(rb.position + movementInput * moveSpeed * Time.fixedDeltaTime);

        }
    }

    void OnMove(InputValue movementValue) {
        movementInput = movementValue.Get<Vector2>();
    }
}

排查与修复方案

  • 检查输入系统配置:确认玩家对象已添加PlayerInput组件,关联了正确的输入动作资产,且"Move"动作已绑定WASD/方向键等输入方式。OnMove方法依赖输入系统的动作触发,若绑定错误,movementInput始终为Vector2.zero,角色自然不会移动。
  • 验证Rigidbody2D设置:确保玩家对象的Rigidbody2D组件Body Type为Dynamic,且未冻结X/Y轴位置。若Body Type是Static或冻结了位置,代码执行移动也不会生效。
  • 修复碰撞检测与移动逻辑:原代码中rb.Cast仅执行了碰撞检测,但未根据检测结果控制移动。即使检测到障碍物,代码仍会强制移动,同时若movementFilter配置不当(如未正确设置可碰撞图层),也可能引发隐性问题。调整FixedUpdate逻辑,仅在无碰撞时执行移动:
private void FixedUpdate() {
    if(movementInput != Vector2.zero){
        // 清空之前的碰撞检测结果
        castCollisions.Clear();
        // 执行碰撞检测
        int count = rb.Cast(
            movementInput, 
            movementFilter, 
            castCollisions, 
            moveSpeed * Time.fixedDeltaTime + collisionOffset); 
        
        // 只有当没有检测到碰撞时,才执行移动
        if(count == 0){
            rb.MovePosition(rb.position + movementInput * moveSpeed * Time.fixedDeltaTime);
        }
    }
}
  • 检查movementFilter配置:在Inspector面板中,确保movementFilter的Use Layer Mask勾选正确,仅包含需要碰撞的图层(如障碍物图层),避免误检测导致移动被阻止。

内容的提问来源于stack exchange,提问作者AtomicUnleashed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 06:53:15