Hi,
i almost finished my first 2D Game ever in Unity. Im really new to coding. The Game is Top Down, so The Object moves with WASD and Rotates in the direction it moves. The Player has 5 HP, and when hit by an Enemy the Player loses 1 HP. That all works just fine. But I would like the Game to end when my Health = 0. Currently it just keeps going -1,-2 […].
Ill attach my script, your help would mean a lot. I’m a first semester student of Game Design in germany and as I said, pretty new to coding.
Player script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.SceneManagement;
public class Player : MonoBehaviour
{
public int health;
int score;
public TMP_Text healthDisplay;
public TMP_Text scoreDisplay;
[SerializeField]
private float speed;
[SerializeField]
private float rotationSpeed;
void Update()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector2 movementDirection = new Vector2(horizontalInput, verticalInput);
float inputMagnitude = Mathf.Clamp01(movementDirection.magnitude);
movementDirection.Normalize();
transform.Translate(movementDirection * speed * inputMagnitude * Time.deltaTime, Space.World);
if (movementDirection != Vector2.zero)
{
Quaternion toRotation = Quaternion.LookRotation(Vector3.forward, movementDirection);
transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, rotationSpeed * Time.deltaTime);
}
}
public void TakeDamage()
{
health--;
healthDisplay.text = "Health: " + health;
if (health <= 0)
{
SceneManager.LoadScene("Game");
}
}
public void AddScore()
{
score++;
scoreDisplay.text = "Score: " + score;
}
}