Unity中Sprite向左与向上移动速度过快问题求助
问题分析与修复方案
核心问题
你的代码存在三个关键问题导致移动速度异常:
- 对角线判断逻辑错误:原条件
horizontalInput == 1 || horizontalInput == -1 && verticalInput == 1 || verticalInput == -1因运算符优先级(&&高于||),会在仅按W(向上)时触发verticalInput == 1的判断,错误修改speed;仅按A(向左)时,也会因逻辑判断失误导致speed切换异常。 - 移动与speed修改顺序颠倒:先执行
transform.Translate移动,再修改speed,当前帧移动用的是上一帧的speed值,逻辑完全混乱。 - 输入处理冗余且易出错:单独处理每个按键的Down/Up事件,代码冗余且容易遗漏边缘情况。
修复方案
正确的做法是先计算方向向量并归一化,再执行移动,这样无论单方向还是对角线移动,速度大小都一致,无需切换speed值,逻辑更清晰可靠:
- 用
Input.GetKey持续检测按键状态,直接赋值输入值; - 创建方向向量,对其归一化(避免对角线方向速度叠加导致过快);
- 用归一化后的向量执行移动,保持固定speed值。
修正后的完整代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { private float speed = 10f; private float horizontalInput; private float verticalInput; void Update() { // 持续检测按键状态,更新输入值 horizontalInput = 0; if (Input.GetKey(KeyCode.A)) horizontalInput = -1; if (Input.GetKey(KeyCode.D)) horizontalInput = 1; verticalInput = 0; if (Input.GetKey(KeyCode.S)) verticalInput = -1; if (Input.GetKey(KeyCode.W)) verticalInput = 1; // 创建方向向量并归一化,确保单方向与对角线移动速度一致 Vector2 moveDirection = new Vector2(horizontalInput, verticalInput); if (moveDirection.magnitude > 0) { moveDirection = moveDirection.normalized; } // 执行移动 transform.Translate(moveDirection * Time.deltaTime * speed); } }
额外优化(可选)
你也可以用Unity内置的Input.GetAxisRaw简化输入处理,代码更简洁:
void Update() { horizontalInput = Input.GetAxisRaw("Horizontal"); verticalInput = Input.GetAxisRaw("Vertical"); Vector2 moveDirection = new Vector2(horizontalInput, verticalInput); if (moveDirection.magnitude > 0) { moveDirection = moveDirection.normalized; } transform.Translate(moveDirection * Time.deltaTime * speed); }
这种方式会自动对应Unity输入设置中的Horizontal(A/D、左右箭头)和Vertical(W/S、上下箭头)按键,无需手动判断每个按键。
内容的提问来源于stack exchange,提问作者pickle the cow
相关产品推荐
相关产品推荐

