Unity中Isaac角色按键冲突:方向键同时触发移动与射击
问题原因
Unity默认的Horizontal输入轴同时绑定了A/D键和左右方向键,Vertical轴同时绑定了W/S键和上下方向键。所以当你按下方向键时,Input.GetAxisRaw("Horizontal")/Input.GetAxisRaw("Vertical")会读取到输入值,触发移动逻辑,导致方向键同时控制移动和射击。
解决方案
有两种可行的解决方式,按需选择:
方法1:修改Unity输入管理器(Input Manager)
- 打开Unity编辑器,依次点击
Edit > Project Settings > Input Manager - 找到
Horizontal轴,展开后删除Negative Button和Positive Button中的方向键绑定(只保留A/D) - 找到
Vertical轴,展开后删除Negative Button和Positive Button中的方向键绑定(只保留W/S) - 保存设置后,方向键就不会触发移动逻辑,仅用于射击。
方法2:在代码中直接检测WASD按键,不使用默认输入轴
修改Move()方法,直接读取W/A/S/D的按键状态,替代Input.GetAxisRaw:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class IsaacMovements : MonoBehaviour { public float speed = 40f; public Rigidbody2D projectilePrefab; public float projectileSpeed = 10f; private Rigidbody2D rb; void Start() { rb = GetComponent<Rigidbody2D>(); if (rb == null) { Debug.LogError("Rigidbody2D component is not attached to the GameObject."); } } void Update() { Move(); if (Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.RightArrow) || Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.DownArrow)) { Shoot(); } } void Move() { // 直接检测WASD按键,替代默认输入轴 float horizontalInput = 0f; float verticalInput = 0f; if (Input.GetKey(KeyCode.A)) horizontalInput = -1f; else if (Input.GetKey(KeyCode.D)) horizontalInput = 1f; if (Input.GetKey(KeyCode.W)) verticalInput = 1f; else if (Input.GetKey(KeyCode.S)) verticalInput = -1f; Vector2 movement = new Vector2(horizontalInput, verticalInput).normalized; rb.velocity = movement * speed; } void Shoot() { if (Input.GetKey(KeyCode.LeftArrow)) Fire(Vector2.left); else if (Input.GetKey(KeyCode.RightArrow)) Fire(Vector2.right); else if (Input.GetKey(KeyCode.UpArrow)) Fire(Vector2.up); else if (Input.GetKey(KeyCode.DownArrow)) Fire(Vector2.down); } void Fire(Vector2 direction) { Rigidbody2D projectileInstance = Instantiate(projectilePrefab, transform.position, Quaternion.identity); projectileInstance.velocity = direction * projectileSpeed; } }
这种方法不需要修改Unity全局输入设置,直接在脚本里隔离了移动和射击的按键逻辑,更适合单场景的自定义控制需求。
内容的提问来源于stack exchange,提问作者Gabriele Conserva
相关产品推荐
相关产品推荐

