You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.1 KiB

  1. using UnityEngine;
  2. using System.Collections;
  3. public class PlayerControler : MonoBehaviour {
  4. public Animator animator;
  5. // Use this for initialization
  6. void Start () {
  7. }
  8. public float speed;
  9. public Vector2 jumpVector;
  10. public int health = 0;
  11. private int displayedHealth = 0;
  12. private bool updateHealth = false;
  13. public GameObject bullet;
  14. public GameObject heart;
  15. bool canJump = true;
  16. void Update() {
  17. Vector2 velo = rigidbody2D.velocity;
  18. velo.x = Input.GetAxis ("Horizontal_P1") * speed;
  19. rigidbody2D.velocity = velo;
  20. animator.SetFloat("Velocity",velo.magnitude);
  21. animator.SetBool ("Fall", !canJump);
  22. applyPlayerDirection (Input.GetAxisRaw ("Horizontal_P1"));
  23. if (displayedHealth != health) {
  24. updateHealth = true;
  25. }
  26. if (updateHealth)
  27. displayHealth (health);
  28. if (Input.GetKey (KeyCode.UpArrow)){
  29. if (canJump == true){
  30. rigidbody2D.velocity = jumpVector;
  31. canJump = false;
  32. }
  33. }
  34. //if (Input.GetKey (KeyCode.Space)){
  35. //shoot
  36. //GameObject bulletGO = Instantiate (bullet) as GameObject;
  37. //bulletGO.transform.position = transform.position;
  38. //}
  39. }
  40. private void displayHealth(int health){
  41. GameObject[] hearts = GameObject.FindGameObjectsWithTag("heartUI2");
  42. foreach (GameObject desHeart in hearts)
  43. GameObject.Destroy (desHeart);
  44. for (int i=1; i<= health; i++) {
  45. GameObject heartCanister = Instantiate (heart) as GameObject;
  46. Vector3 heartPos = new Vector3 (1-(i * 0.033f), 0.95f, 0);
  47. heartCanister.transform.position = heartPos;
  48. }
  49. displayedHealth = health;
  50. updateHealth = false;
  51. }
  52. private void applyPlayerDirection(float moveHorizontal)
  53. {
  54. if (moveHorizontal != 0)
  55. {
  56. Vector3 scale = transform.localScale;
  57. scale.x = -moveHorizontal * Mathf.Abs(scale.x);
  58. transform.localScale = scale;
  59. }
  60. }
  61. void OnCollisionEnter2D(Collision2D col){
  62. if (col.collider.tag == "ground")
  63. canJump = true;
  64. else if (col.collider.tag == "Player") {
  65. canJump = true;
  66. if(transform.position.y>col.transform.position.y){
  67. col.gameObject.GetComponent<player2_controls>().health --;
  68. //health --;
  69. rigidbody2D.velocity = jumpVector;
  70. canJump = false;
  71. }
  72. }
  73. }
  74. }