Menu
CoddyTech

Estrella tras estrella

Parte de la sección Fundamentos de scripting en Unity del Journey de Unity de Coddy. Lección 53 de 85.

challenge icon

Desafío

Intermedio

Envía una estrella nueva después de cada captura y cada fallo.

  1. Escribe void ResetStar() para que establezca star.position = new Vector3(Random.Range(-4f, 4f), 6f, 0f);, y llámala en la captura en lugar de la línea anterior.
  2. Después del if de la captura, añade else if (star.position.y < 0f) que llame a ResetStar();. Un else if se ejecuta solo cuando el if anterior fue falso.

Pulsa «Jugar»: cada estrella nueva cae en una x diferente. Después, pulsa «Comprobar».

Pruébalo tú mismo

using UnityEngine;

public class Catcher : MonoBehaviour
{
    [SerializeField] private float speed = 6f;
    [SerializeField] private Transform star;
    [SerializeField] private float fallSpeed = 3f;
    private int score;

    void Update()
    {
        float x = transform.position.x;
        if (Input.GetKey(KeyCode.RightArrow))
        {
            x += speed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            x -= speed * Time.deltaTime;
        }
        x = Mathf.Clamp(x, -4f, 4f);
        transform.position = new Vector3(x, transform.position.y, transform.position.z);

        star.position += Vector3.down * fallSpeed * Time.deltaTime;

        if (Vector3.Distance(transform.position, star.position) < 1f)
        {
            score++;
            Debug.Log("Caught! Score: " + score);
            star.position = new Vector3(star.position.x, 6f, star.position.z);
        }
    }
}

Todas las lecciones de Fundamentos de scripting en Unity

Practica por tu cuenta: Playground de Unity