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.

89 lines
2.1 KiB

  1. using UnityEngine;
  2. using System.Collections;
  3. public class player2_controls : MonoBehaviour {
  4. public Animator animator;
  5. void Start () {
  6. }
  7. public float speed;
  8. public Vector2 jumpVector;
  9. public int health = 0;
  10. private int displayedHealth = 0;
  11. private bool updateHealth = false;
  12. public GameObject bullet;
  13. public GameObject heart;
  14. bool canJump = true;
  15. void Update() {
  16. Vector2 velo = rigidbody2D.velocity;
  17. velo.x = Input.GetAxis ("Horizontal_P2") * speed;
  18. rigidbody2D.velocity = velo;
  19. animator.SetFloat("Velocity",velo.magnitude);
  20. animator.SetBool ("Fall", !canJump);
  21. applyPlayerDirection (Input.GetAxisRaw ("Horizontal_P2"));
  22. if (displayedHealth != health) {
  23. updateHealth = true;
  24. }
  25. if (updateHealth)
  26. displayHealth (health);
  27. if (Input.GetKey (KeyCode.W)){
  28. if (canJump == true){
  29. rigidbody2D.velocity = jumpVector;
  30. canJump = false;
  31. }
  32. }
  33. //if (Input.GetKey (KeyCode.Space)){
  34. //shoot
  35. //GameObject bulletGO = Instantiate (bullet) as GameObject;
  36. //bulletGO.transform.posplayteition = transform.position;
  37. //}
  38. }
  39. private void displayHealth(int health){
  40. GameObject[] hearts = GameObject.FindGameObjectsWithTag("heartUI");
  41. foreach (GameObject desHeart in hearts)
  42. GameObject.Destroy (desHeart);
  43. for (int i=1; i<= health; i++) {
  44. GameObject heartCanister = Instantiate (heart) as GameObject;
  45. Vector3 heartPos = new Vector3 ((i * 0.033f), 0.95f, 0);
  46. heartCanister.transform.position = heartPos;
  47. }
  48. displayedHealth = health;
  49. updateHealth = false;
  50. }
  51. //Changes direction of sprite according to key pressed
  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. if(transform.position.y>col.transform.position.y){
  66. col.gameObject.GetComponent<PlayerControler>().health --;
  67. //health --;
  68. rigidbody2D.velocity = jumpVector;
  69. canJump = false;
  70. }
  71. }
  72. }
  73. }