Menu
CoddyTech

Repaso: cambio de entrada

Parte de la sección Creación de juegos reales del Journey de Unity de Coddy. Lección 48 de 60.

En este capítulo leíste el teclado, el ratón y las acciones del proyecto con Input System. La varita de burbujas todavía usa la antigua clase Input: migra sus llamadas una por una.

challenge icon

Desafío

Intermedio

Adapta la varita de burbujas al Input System; aquí la antigua clase Input provoca un error.

  1. Añade using UnityEngine.InputSystem; y los campos InputAction moveAction y jumpAction; asígnales valores en Start() con InputSystem.actions.FindAction.
  2. Muévete con moveAction.ReadValue<Vector2>(), usando su eje y para el eje z.
  3. Sustituye las comprobaciones de Jump por WasPressedThisFrame(), IsPressed() y WasReleasedThisFrame(), y el clic por Mouse.current.leftButton.wasPressedThisFrame.

Pulsa «Jugar», crea una burbuja y hazla estallar. Después, pulsa «Comprobar».

Pruébalo tú mismo

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 iconPonte a prueba

Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.

Todas las lecciones de Creación de juegos reales

Practica por tu cuenta: Playground de Unity