Mini-Games-Game/Assets/Scripts/PlayerController.cs

98 lines
2.3 KiB
C#
Raw Normal View History

using UnityEngine;
using UnityEngine.UI;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class PlayerController : MonoBehaviour
{
[Header("Keybinds")]
public KeyCode forwardKey = KeyCode.W;
public KeyCode backwardKey = KeyCode.S;
public KeyCode leftKey = KeyCode.A;
public KeyCode rightKey = KeyCode.D;
[Header("Speed")]
public float speed = 5;
[Header("Lives")]
public string enemyTag = "Enemy";
public float invulnerabilityTimeSeconds = 0.25f;
public float lastHit = 0;
public int lives = 3;
public GameObject[] hearts;
[Header("Audio")]
public AudioSource metalPipe;
[Header("Player Object")]
public Vector3 moveDirection;
public Rigidbody rb;
void Start()
{
if (hearts.Length != 3)
{
Debug.LogError("Hearts array not properly configured. Expected length 3.");
enabled = false;
return;
}
if (!TryGetComponent(out rb))
{
Debug.LogError("Rigidbody not found!");
enabled = false; // Disable script if Rigidbody is missing.
}
else
{
rb.freezeRotation = true;
}
}
void Update()
{
moveDirection = PlayerInput();
rb.velocity = moveDirection.normalized * speed;
}
Vector3 PlayerInput()
{
Vector3 direction = Vector3.zero;
if (Input.GetKey(rightKey)) direction.x += 1f;
if (Input.GetKey(leftKey)) direction.x -= 1f;
if (Input.GetKey(forwardKey)) direction.z += 1f;
if (Input.GetKey(backwardKey)) direction.z -= 1f;
return direction;
}
void OnCollisionEnter(Collision collision)
{
bool collidedWithEnemy = collision.gameObject.tag == enemyTag;
bool isInvulnerable = invulnerabilityTimeSeconds >= Time.time - lastHit;
if (collidedWithEnemy && !isInvulnerable)
{
lastHit = Time.time;
metalPipe.Play();
lives--;
hearts[lives].GetComponent<RawImage>().color = Color.gray;
bool playerOutOfLives = lives == 0;
if (playerOutOfLives) ExitGame();
}
}
void ExitGame()
{
#if UNITY_EDITOR
EditorApplication.ExitPlaymode();
#endif
Application.Quit();
}
}