第3章 输入处理与玩家控制

做游戏开发这么多年,我经常跟新人说一句话:输入系统是玩家和游戏世界之间的桥梁。你画面做得再漂亮,物理做得再真实,输入手感一塌糊涂,玩家马上就会摔手柄走人。

Unity 的输入系统经过了几代演变。老牌的 Input.GetAxis 系列接口,简单直接,很多经典项目还在用。但如果你做的是跨平台项目,要同时支持 PC 键盘鼠标、手机触屏,甚至主机手柄,那么我强烈建议你直接上 Input System 包(也就是新输入系统)。我用它重写过好几个项目,说实话,一旦习惯之后,就再也回不去了。

当然,考虑到很多教学项目和老代码库的兼容性,本章我会两种方式都讲。你心里有个底就行——老接口写原型快,新接口做产品稳。

核心输入来源:键盘(KeyCode)、鼠标(Mouse)、触摸(Touch)。三者映射到统一的角色控制逻辑,是本章的主线。

3.1.1 老接口与新接口的选择

对比项旧 Input 类新 Input System
获取按键Input.GetKey(KeyCode.Space)Keyboard.current.spaceKey.wasPressedThisFrame
轴值Input.GetAxis("Horizontal")Keyboard.current.aKey / dKey 组合
触摸支持Input.touchesTouchscreen.current.touches
配置方式硬编码在代码里Input Actions 资产可视化配置
适合场景入门教学、快速原型正式项目、多平台发布
用新输入系统时,千万别忘了在 Player Settings 里将 Active Input Handling 改为 Input System Package (New) 或 Both。我曾在项目里忘了改,结果所有按键都没反应,排查了半天。

3.2 键盘输入与角色移动

我们先从最基础的键盘 WASD 移动说起。为什么用 WASD?因为左手放上去,食指在 D,中指在 W,无名指在 A——这就是肌肉记忆的起点。

3.2.1 用旧 Input 实现平滑移动

我个人习惯在 Update() 里读取输入,在 FixedUpdate() 里施加物理力。原因很简单:Update 帧率不稳定,FixedUpdate 才是物理模拟的正确节奏。

public class PlayerMovementOld : MonoBehaviour
{
    public float moveSpeed = 5f;
    public float rotationSpeed = 720f;
    private Rigidbody rb;
    private Vector3 moveInput;

    void Start() {
        rb = GetComponent<Rigidbody>();
    }

    void Update() {
        float h = Input.GetAxis("Horizontal"); // A/D 或左右方向键
        float v = Input.GetAxis("Vertical");   // W/S 或上下方向键
        moveInput = new Vector3(h, 0f, v).normalized;
    }

    void FixedUpdate() {
        if (moveInput.magnitude > 0.1f) {
            // 移动到目标方向
            Vector3 targetVelocity = moveInput * moveSpeed;
            rb.velocity = new Vector3(targetVelocity.x, rb.velocity.y, targetVelocity.z);
            
            // 转向
            Quaternion targetRotation = Quaternion.LookRotation(moveInput);
            rb.rotation = Quaternion.RotateTowards(
                rb.rotation, targetRotation, rotationSpeed * Time.fixedDeltaTime);
        }
    }
}
注意 GetAxis 返回的是平滑插值后的值,比 GetKey 的手感好很多。玩家按一下 A 键,值会从 0 慢慢过渡到 -1。这就是为什么不用 GetKey——它只有 0 和 1,走起来像在开开关。

转向这里我用的是 Quaternion.RotateTowards,好处是旋转速度恒定,不会因为帧率波动而忽快忽慢。为什么不用 Quaternion.Lerp?因为 Lerp 没限制最大角速度,旋转速度会受帧率影响,手感不一致。

3.2.2 新 Input System 的动作映射

新输入系统的核心是 Input Actions 资产。你创建一个 .inputactions 文件,在里面定义按键映射。我个人习惯是:Move 动作绑定 WASD + 左摇杆,Jump 绑定空格 + 手柄 A 键。

public class PlayerMovementNew : MonoBehaviour
{
    public InputActionReference moveAction;
    public InputActionReference jumpAction;
    public float moveSpeed = 5f;
    private Vector3 moveDir;

    void OnEnable() {
        moveAction.action.Enable();
        jumpAction.action.Enable();
        jumpAction.action.performed += OnJumpPerformed;
    }

    void OnDisable() {
        moveAction.action.Disable();
        jumpAction.action.Disable();
        jumpAction.action.performed -= OnJumpPerformed;
    }

    void Update() {
        Vector2 input = moveAction.action.ReadValue<Vector2>();
        moveDir = new Vector3(input.x, 0f, input.y);
    }

    void FixedUpdate() {
        // 同旧版逻辑...
    }

    private void OnJumpPerformed(InputAction.CallbackContext ctx) {
        // 跳跃触发
        Debug.Log("Jump pressed");
    }
}
新输入系统的价值在于:你不需要改代码,只需要在 Input Actions 资产里重新绑定按键。玩家想要把跳跃从空格改成 J 键?配置一下就行,一行代码不用动。

3.3 鼠标输入与视角控制

鼠标不只是用来点击 UI 的。在第三人称游戏中,鼠标控制镜头的旋转;在第一人称中,鼠标控制人物转身抬头。这里我讲一个最常见的第三人称方案:鼠标控制相机围绕角色旋转,角色朝相机朝向移动。

3.3.1 鼠标灵敏度与平滑滤波

public class MouseLook : MonoBehaviour
{
    public float mouseSensitivity = 100f;
    public Transform playerBody;
    private float xRotation = 0f;
    private float mouseX, mouseY;

    void Update() {
        mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -80f, 80f); // 抬头低头限制

        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
        playerBody.Rotate(Vector3.up * mouseX);
    }
}
鼠标灵敏度一定要乘以 Time.deltaTime。否则同样的灵敏度,在不同帧率的电脑上,转镜头的速度完全不一样。我踩过这个坑——在开发机上好好的,发布到低端笔记本上,画面直接“陀螺仪”了。

如果你觉得鼠标移动有“飘”的感觉,可以加一个简单的鼠标平滑处理:保存上一帧的鼠标位置,用 Lerp 做插值。说白了,就是给鼠标加一点“阻尼感”。

3.4 触摸输入与移动端适配

做移动端游戏,触摸输入是绕不开的。我的个人经验是:触摸输入的精髓不在于检测“按下了”,而在于判断“手指滑动的意图”。

3.4.1 虚拟摇杆的实现思路

虚拟摇杆(Virtual Joystick)是移动端最常见的移动控制方案。实现起来其实很简单:一个圆的背景区域 + 一个可拖动的中心点。

public class VirtualJoystick : MonoBehaviour
{
    public RectTransform background;
    public RectTransform handle;
    public float maxRadius = 80f;
    private Vector2 inputVector;

    public void OnDrag(UnityEngine.EventSystems.PointerEventData eventData) {
        // 计算手指位置相对中心的偏移
        Vector2 localPoint;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(
            background, eventData.position, eventData.pressEventCamera, out localPoint);

        // 限制在范围内
        localPoint = Vector2.ClampMagnitude(localPoint, maxRadius);
        handle.anchoredPosition = localPoint;
        
        // 归一化输出 -1 到 1 的输入向量
        inputVector = localPoint / maxRadius;
    }

    public void OnPointerUp(UnityEngine.EventSystems.PointerEventData eventData) {
        handle.anchoredPosition = Vector2.zero;
        inputVector = Vector2.zero;
    }

    public Vector2 GetInput() => inputVector;
}
在手机上做虚拟摇杆,背景区域一定要做得比视觉上的圆稍大一圈。因为手指有触控盲区,实际点击范围总比你想象的要偏一些。这是我在真机测试中总结出来的。

3.4.2 多点触控与手势识别

void Update() {
    if (Input.touchCount == 0) return;

    // 双指缩放
    if (Input.touchCount == 2) {
        Touch touch0 = Input.GetTouch(0);
        Touch touch1 = Input.GetTouch(1);

        Vector2 prevDist = touch0.position - touch0.deltaPosition -
                           (touch1.position - touch1.deltaPosition);
        Vector2 currDist = touch0.position - touch1.position;
        float scaleFactor = currDist.magnitude / prevDist.magnitude;

        // 应用缩放逻辑...
    }
}

3.5 跳跃与地面检测

跳跃看起来是个简单操作,但要做好其实不容易。跳跃的本质是一门“物理课”——你要处理重力、起跳速度、落地检测,还有一个特别容易忽略的点:起跳延迟。

3.5.1 为什么要用缓冲跳跃

你有没有遇到过这种情况:玩家在快落地前按了跳跃键,结果没跳起来,落地后再按一次才跳。玩家体验就是“手感好肉”。解决方法是跳跃缓冲:记录玩家按跳跃键的时间,落地时如果缓冲还没过期,就自动起跳。

public class PlayerJump : MonoBehaviour
{
    public float jumpHeight = 2f;
    public float gravity = -9.81f;
    public float jumpBufferTime = 0.1f;  // 跳跃缓冲时间
    public float groundCheckRadius = 0.2f;
    public Transform groundCheckPoint;
    public LayerMask groundLayer;

    private Rigidbody rb;
    private float lastJumpPressTime = -999f;
    private bool isGrounded = false;

    void Start() => rb = GetComponent<Rigidbody>();

    void Update() {
        // 记录按下跳跃的时刻
        if (Input.GetButtonDown("Jump")) {
            lastJumpPressTime = Time.time;
        }
    }

    void FixedUpdate() {
        CheckGround();
        
        // 只在接触地面时施加重力
        if (!isGrounded) {
            rb.AddForce(Vector3.up * gravity * rb.mass * Time.fixedDeltaTime);
        }

        // 跳跃缓冲检查
        if (isGrounded && Time.time - lastJumpPressTime < jumpBufferTime) {
            float jumpVelocity = Mathf.Sqrt(jumpHeight * -2f * gravity);
            rb.velocity = new Vector3(rb.velocity.x, jumpVelocity, rb.velocity.z);
            lastJumpPressTime = -999f;
        }
    }

    void CheckGround() {
        Collider[] cols = Physics.OverlapSphere(
            groundCheckPoint.position, groundCheckRadius, groundLayer);
        isGrounded = cols.Length > 0;
    }
}
跳跃高度和重力加速度的关系,用公式 v = √(2gh) 计算。我在项目里见过有人硬调数值调到头晕,不如直接用公式一步到位。

3.6 知识结构图:输入处理与角色控制全景

输入处理与玩家控制 键盘输入 WASD 移动 空格 跳跃 GetKey / GetAxis Input Actions 鼠标输入 Mouse X 横向旋转 Mouse Y 纵向俯仰 灵敏度 × deltaTime Clamp 上下限 触摸输入 Touch.fingerId touchCount 点数 虚拟摇杆 双指缩放 移动逻辑(Update 读取) Vector3 方向 + normalize 物理执行(FixedUpdate) Rigidbody.velocity + 旋转 跳跃系统 地面检测 + 起始速度 转向系统 Quaternion.LookRotation 手感优化 跳跃缓冲 + 平滑滤波 旧 Input 适合原型,新 Input System 适合产品

3.7 角色控制器的整体架构建议

最后聊点我自己的项目经验。我建议你把输入处理、角色逻辑、物理反馈分开。别把所有代码塞在一个 MonoBehaviour 里——那不是工程,那是毛线团。

脚本职责划分建议:
├── InputReader(只负责读取输入,转成意图数据)
│   ├── 键盘/鼠标输入采集
│   ├── 触摸输入采集
│   └── 输出:MoveInput(Vector2)、JumpPressed(bool)
├── CharacterMotor(负责物理移动和跳跃)
│   ├── 应用速度、旋转
│   ├── 处理重力
│   └── 检测地面
└── PlayerAnimator(根据状态驱动动画)
    ├── 移动速度参数
    ├── 跳跃触发
    └── 地面状态
“输入读取”和“角色移动”分离的好处是:你后面想加 AI 控制、换摇杆、接入键盘,只需要替换 InputReader 即可,CharacterMotor 完全不改。这就是解耦的价值。

嗯,关于输入处理和玩家控制,核心的点就这些了。代码可以直接拿去用,但更重要的是理解背后的思路。我始终认为,一个手感好的游戏,不是靠某一个神奇代码实现的,而是靠无数个细节堆积起来的。每个细节看起来都不起眼,合在一起就是天壤之别。希望你动手实践的时候,也能体会到这种“抠手感”的乐趣。