using TMPro; using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; using UnityEditorInternal; using System.IO; public class playerScript : MonoBehaviour { public float speed = 5f; private Rigidbody2D body; private Vector2 move; private SpriteRenderer spriteRenderer; private Vector2 mousePosition; public int keysCollected = 0; public TextMeshProUGUI keysText; private bool canMove = true; public float movementDelay = 0.75f; public Countdown countdownscript; /// /// This code checks if all the variables are assigned to the right components. /// void Start() { body = GetComponent(); spriteRenderer = GetComponent(); StartCoroutine(DelayMovement()); } /// /// This code controls the movement of the player including checking if the player is allowed to move or not. /// void Update() { if (!canMove) return; mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); Vector2 aimDirection = mousePosition - (Vector2)transform.position; float aimAngle = Mathf.Atan2(aimDirection.y, aimDirection.x) * Mathf.Rad2Deg; body.rotation = aimAngle; Vector2 movementDirection = new Vector2(Mathf.Cos(aimAngle * Mathf.Deg2Rad), Mathf.Sin(aimAngle * Mathf.Deg2Rad)); movementDirection.Normalize(); body.velocity = movementDirection * speed; Lose_condition(); Win_condition(); } /// /// This code is for updating the keys text, It relates to the code below, When the player collides with the object tagged key, /// keys collected increases, and the text should display "Keys collected ... (number of keys collected) /// public void UpdateKeysText() { keysCollected++; keysText.text = "Keys Collected: " + keysCollected; } /// /// This code is for collecting the keys, It just means if the player collides with a object with the tag "Key" /// update the key collected text, and destroy the key object. /// private void OnTriggerEnter2D(Collider2D other) { if (other.CompareTag("key")) { UpdateKeysText(); Destroy(other.gameObject); } } private IEnumerator DelayMovement() { canMove = false; yield return new WaitForSeconds(movementDelay); canMove = true; } /// /// lose conditon, This code is to see if the player has less than 5 keys when the time has reached 0. /// If yes, Scene 1 will oad which is the starting position. /// private void Lose_condition() { if (keysCollected < 5 && countdownscript.remainingTime < 0) { Debug.Log("Time out! Level Restarted"); SceneManager.LoadScene(1); } } /// /// This code is for the win condition. This is for when the player has collected 5 keys under one minute. /// If the player has, It prints to the console saying the player has won, loading up scene 1 which is the starting position. /// private void Win_condition() { string path = Path.Combine(Application.dataPath, "../Data/highcore.text"); File.WriteAllText(path, keysText.text); if (keysCollected == 5 && countdownscript.remainingTime > 0) { Debug.Log("You win! Level Restarted"); SceneManager.LoadScene(1); } } }