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

Unity玩家横竖轴移动异常求助:按上下键时玩家水平移动

解决Unity中玩家垂直移动时触发水平位移的问题

我是Unity和编程新手,可能问题比较基础。我想实现玩家在地图上同时进行水平和垂直移动,但当前代码存在问题:按下上下方向键时,玩家也会产生水平方向的移动。请问需要修改哪里?

原代码

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

public class Test : MonoBehaviour
{
    Rigidbody2D _rb;

    float _walkSpeed;
    float _inputHorizontal;
    float _inputVertical;
    float _walkSpeedVertical;
    
    void Start()
    {
        _rb = gameObject.GetComponent<Rigidbody2D>();

        _walkSpeed = 5.5f;
        _walkSpeedVertical = 6.5f;
    }

    void Update()
    {
        _inputHorizontal = Input.GetAxisRaw("Horizontal");
    
        if (_inputHorizontal != 0)
        {
            _rb.AddForce(new Vector2(_inputHorizontal * _walkSpeed, 0f));
        }
        
        _inputVertical = Input.GetAxisRaw("Vertical");

        if (_inputVertical != 0) 
        {
            _rb.AddForce(new Vector2(_inputVertical * _walkSpeedVertical, 0f));
        }
        if (_inputVertical + _inputHorizontal == 0)
        {
            _rb.velocity = Vector2.zero;
        }
    }
}

问题原因

垂直移动的力被错误施加到了X轴(水平方向),导致按下上下方向键时,玩家会产生水平位移。

修改方案

将垂直移动代码里的力作用轴从X轴改为Y轴:
把new Vector2(_inputVertical * _walkSpeedVertical, 0f)替换为new Vector2(0f, _inputVertical * _walkSpeedVertical)。

修改后的完整代码

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

public class Test : MonoBehaviour
{
    Rigidbody2D _rb;

    float _walkSpeed;
    float _inputHorizontal;
    float _inputVertical;
    float _walkSpeedVertical;
    
    void Start()
    {
        _rb = gameObject.GetComponent<Rigidbody2D>();

        _walkSpeed = 5.5f;
        _walkSpeedVertical = 6.5f;
    }

    void Update()
    {
        _inputHorizontal = Input.GetAxisRaw("Horizontal");
    
        if (_inputHorizontal != 0)
        {
            _rb.AddForce(new Vector2(_inputHorizontal * _walkSpeed, 0f));
        }
        
        _inputVertical = Input.GetAxisRaw("Vertical");

        if (_inputVertical != 0) 
        {
            _rb.AddForce(new Vector2(0f, _inputVertical * _walkSpeedVertical));
        }
        if (_inputVertical + _inputHorizontal == 0)
        {
            _rb.velocity = Vector2.zero;
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 15:03:20