Menu
CoddyTech

Du gewinnst

Teil des Abschnitts Physik und Gameplay der Unity-Journey von Coddy. Lektion 33 von 71.

challenge icon

Aufgabe

Mittel

Lass den Spieler bei target Punkten gewinnen.

  1. Füge in Ball.cs public int target = 10; und bool IsPlaying() hinzu, das timeLeft > 0f && score < target zurückgibt.
  2. Verwende in Update() und FixedUpdate() IsPlaying() anstelle von timeLeft > 0f und beginne AddScore mit if (!IsPlaying()) return;.
  3. Gib nach der Zeile mit dem Punktestand You win! aus, wenn score >= target gilt.

Drücke „Spielen“ und sammle 8 Punkte. Drücke dann „Prüfen“.

Probier es selbst

using UnityEngine;

public class Ball : MonoBehaviour
{
    public float force = 10f;
    public int score;
    public float timeLimit = 60f;
    public float timeLeft;
    private Rigidbody rb;

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

    void Update()
    {
        if (timeLeft > 0f)
        {
            timeLeft -= Time.deltaTime;
            if (timeLeft <= 0f)
            {
                timeLeft = 0f;
                Debug.Log("Time's up! Score: " + score);
            }
        }
    }

    void FixedUpdate()
    {
        if (timeLeft > 0f)
        {
            float x = Input.GetAxis("Horizontal");
            float z = Input.GetAxis("Vertical");
            rb.AddForce(new Vector3(x, 0f, z) * force);
        }
    }

    public void AddScore(int points)
    {
        score += points;
        Debug.Log("Score: " + score);
    }
}

Alle Lektionen in Physik und Gameplay

Übe selbstständig: Unity-Playground