Menu
CoddyTech

Ôn tập: chuyển đổi đầu vào

Thuộc phần Xây dựng trò chơi thực tế trong hành trình Unity của Coddy. Bài học 48 trên 60.

Chương này đọc bàn phím, chuột và các hành động của dự án bằng Input System. Cây đũa bong bóng vẫn dùng lớp cũ Input: hãy chuyển đổi từng lời gọi một.

challenge icon

Thử thách

Trung bình

Chuyển cây đũa phép tạo bong bóng sang Input System; lớp Input cũ gây lỗi ở đây.

  1. Thêm using UnityEngine.InputSystem; và các trường InputAction moveAction và jumpAction, rồi gán giá trị trong Start() bằng InputSystem.actions.FindAction.
  2. Di chuyển bằng moveAction.ReadValue<Vector2>(), dùng trục y của giá trị này làm trục z.
  3. Thay các lần kiểm tra Jump bằng WasPressedThisFrame(), IsPressed() và WasReleasedThisFrame(), đồng thời thay thao tác nhấp bằng Mouse.current.leftButton.wasPressedThisFrame.

Nhấn Chơi, thổi bong bóng rồi làm vỡ nó. Sau đó nhấn Kiểm tra.

Tự làm thử

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 iconTự kiểm tra

Bài học này có một bài trắc nghiệm ngắn. Bắt đầu bài học để trả lời và theo dõi tiến độ.

Tất cả bài học trong Xây dựng trò chơi thực tế

Tự luyện tập: Playground Unity