Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.SceneManagement;
- using UnityEngine.UI;
- public class PlayerController : MonoBehaviour
- {
- //User Interface.
- //DO NOT REMOVE
- public Text txtHealth;
- public Text txtLives;
- public Text txtCollectables;
- public float speed = 10;
- public float jumpForce = 10;
- public int lives = 3;
- public int health = 100;
- public int collectables= 0;
- bool isOnGround = false;
- Vector2 force;
- Rigidbody2D body;
- private Vector3 startPosition;
- void Start()
- {
- force.y = jumpForce;
- body = GetComponent<Rigidbody2D>();
- startPosition = transform.position;
- }
- void Update()
- {
- UpdateUI();
- //if the spacebar is released
- if(Input.GetKeyUp(KeyCode.Space))
- {
- //if the player is on the ground
- if (isOnGround)
- {
- //add force to the players rigid body
- body.AddForce(force, ForceMode2D.Impulse);
- isOnGround = false;
- }
- }
- float x = Input.GetAxis("Horizontal");
- //set the players X velocity to x * speed
- //set the players Y velocity to be the current Y velocity
- body.velocity = new Vector2(x * speed, body.velocity.y);
- }
- //DO NOT REMOVE
- void UpdateUI()
- {
- txtHealth.text = "Health: " + health;
- txtLives.text = "Lives: " + lives;
- txtCollectables.text = "Collectables: " + collectables;
- if (health <= 0)
- {
- lives -= 1;
- health = 100;
- }
- else if (lives <= 0)
- {
- int sceneIndex = SceneManager.GetActiveScene().buildIndex;
- SceneManager.LoadScene(sceneIndex);
- }
- }
- private void OnCollisionEnter2D(Collision2D collision)
- {
- string tag = collision.gameObject.tag;
- if (tag == "ground")
- {
- isOnGround = true;
- }
- else if (collision.gameObject.tag == "collectables")
- {
- collectables++;
- Destroy(collision.gameObject);
- }
- else if (collision.gameObject.tag == "kill")
- {
- health -= 50;
- transform.position = startPosition;
- }
- else if (collision.gameObject.tag == "door")
- {
- GetComponent<DoorController>();
- if (collectables >= 1)
- {
- Destroy(collision.gameObject);
- collectables--;
- }
- }
- else if (lives <= 0)
- {
- int sceneIndex = SceneManager.GetActiveScene().buildIndex;
- SceneManager.LoadScene(sceneIndex);
- }
- }
- private void OnTriggerEnter2D(Collider2D collision)
- {
- if (collision.gameObject.tag == "collectable")
- {
- collectables++;
- Destroy(collision.gameObject);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement