Menu
CoddyTech

回顾:切换输入

本课属于 Coddy Unity 学习旅程的“打造真正的游戏”单元。第 48 课,共 60 课。

本章使用 Input System 读取键盘、鼠标和项目中的操作。泡泡棒仍使用旧的 Input 类:逐个调用进行迁移。

challenge icon

挑战

中等

将泡泡魔杖移植到 Input System;旧的 Input 类在这里会报错。

  1. 添加 using UnityEngine.InputSystem; 和 InputAction 字段 moveAction 与 jumpAction,并在 Start() 中使用 InputSystem.actions.FindAction 设置它们。
  2. 通过 moveAction.ReadValue<Vector2>() 移动,让它的 y 轴对应 z 轴。
  3. 将 Jump 检查替换为 WasPressedThisFrame()、IsPressed() 和 WasReleasedThisFrame(),并将点击检查替换为 Mouse.current.leftButton.wasPressedThisFrame。

按“开始”,吹出一个泡泡并戳破它。然后按“检查”。

亲手试试

using UnityEngine;

public class Wand : MonoBehaviour
{
    public float speed = 4f;
    public float growRate = 1f;
    public float maxSize = 1.5f;
    public GameObject bubblePrefab;

    private Transform bubble;

    void Update()
    {
        Vector3 move = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
        transform.position += move.normalized * speed * Time.deltaTime;

        if (Input.GetButtonDown("Jump"))
        {
            bubble = Instantiate(bubblePrefab, transform.position + Vector3.up * 1.5f, Quaternion.identity).transform;
        }
        if (Input.GetButton("Jump") && bubble != null)
        {
            float size = Mathf.Min(bubble.localScale.x + growRate * Time.deltaTime, maxSize);
            bubble.localScale = Vector3.one * size;
        }
        if (Input.GetButtonUp("Jump") && bubble != null)
        {
            Debug.Log("Bubble: " + bubble.localScale.x.ToString("F1"));
            bubble = null;
        }

        if (Input.GetMouseButtonDown(0))
        {
            GameObject[] bubbles = GameObject.FindGameObjectsWithTag("Bubble");
            foreach (GameObject b in bubbles) Destroy(b);
            Debug.Log("Popped " + bubbles.Length);
        }
    }
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

打造真正的游戏中的所有课

自己练习: Unity 在线编辑器