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

Unity双角色同时按前进+右键时输入失效问题求助

问题分析与解决建议

核心原因

你遇到的问题主要来自两个方面:

  1. 键盘硬件键位冲突:普通薄膜键盘普遍存在N键冲突限制,W/D/I/L这类分布在键盘不同区域但共享扫描线路的按键,同时按下时会导致部分按键输入无法被系统识别,这是最可能的原因。
  2. 代码逻辑缺陷:原代码直接赋值player.velocity的方式会覆盖原有速度,虽然不是当前问题的主因,但会导致移动逻辑不严谨。

解决步骤

1. 排查并解决硬件键位冲突

  • 测试键位冲突:使用本地按键检测程序同时按下W+D+I+L,查看是否有按键无法被检测到。
  • 更换键位:将两个角色的操作键位调整到键盘无冲突区域,比如玩家1保留WASD,玩家2改用方向键(↑↓←→)。
  • 更换硬件:如果条件允许,使用支持全键无冲的机械键盘。

2. 修复代码逻辑

原代码中直接赋值velocity的方式会覆盖角色的所有速度(包括重力等其他力的影响),且按键判断逻辑不够严谨,以下是优化后的代码:

玩家1移动脚本(Player1Movement.cs)

using UnityEngine;

public class Player1Movement : MonoBehaviour
{
    public Rigidbody playerRb;
    public float moveSpeed = 5f;
    public float rotateSpeed = 100f;

    void FixedUpdate()
    {
        // 计算前进后退方向
        float forwardInput = 0f;
        if (Input.GetKey(KeyCode.W)) forwardInput += 1f;
        if (Input.GetKey(KeyCode.S)) forwardInput -= 1f;

        if (forwardInput != 0)
        {
            // 仅修改XZ平面的移动速度,保留Y轴的重力速度
            Vector3 moveDirection = transform.forward * forwardInput * moveSpeed;
            playerRb.velocity = new Vector3(moveDirection.x, playerRb.velocity.y, moveDirection.z);
        }
        else
        {
            // 无输入时让角色平滑减速
            playerRb.velocity = new Vector3(playerRb.velocity.x * 0.9f, playerRb.velocity.y, playerRb.velocity.z * 0.9f);
        }
    }

    void Update()
    {
        // 计算左右旋转方向
        float rotateInput = 0f;
        if (Input.GetKey(KeyCode.A)) rotateInput -= 1f;
        if (Input.GetKey(KeyCode.D)) rotateInput += 1f;

        transform.Rotate(0f, rotateInput * rotateSpeed * Time.deltaTime, 0f);
    }
}

玩家2移动脚本(Player2Movement.cs)

using UnityEngine;

public class Player2Movement : MonoBehaviour
{
    public Rigidbody playerRb;
    public float moveSpeed = 5f;
    public float rotateSpeed = 100f;

    void FixedUpdate()
    {
        float forwardInput = 0f;
        if (Input.GetKey(KeyCode.I)) forwardInput += 1f;
        if (Input.GetKey(KeyCode.K)) forwardInput -= 1f;

        if (forwardInput != 0)
        {
            Vector3 moveDirection = transform.forward * forwardInput * moveSpeed;
            playerRb.velocity = new Vector3(moveDirection.x, playerRb.velocity.y, moveDirection.z);
        }
        else
        {
            playerRb.velocity = new Vector3(playerRb.velocity.x * 0.9f, playerRb.velocity.y, playerRb.velocity.z * 0.9f);
        }
    }

    void Update()
    {
        float rotateInput = 0f;
        if (Input.GetKey(KeyCode.J)) rotateInput -= 1f;
        if (Input.GetKey(KeyCode.L)) rotateInput += 1f;

        transform.Rotate(0f, rotateInput * rotateSpeed * Time.deltaTime, 0f);
    }
}

代码优化说明

  • 不再直接覆盖velocity的所有分量,保留Y轴速度以兼容重力效果。
  • 使用方向值累加的方式处理按键输入,避免单个按键覆盖其他输入逻辑。
  • 添加了无输入时的平滑减速,提升移动手感。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 00:27:07