Punching bags added and working

I've been able to add punching bags to the game and they disappear when hit. It doesn't feel right or perfect yet but I was happy to figure some of it out. I'm basically enabling and disabling different parts of game objects. When I try to destroy them I seem to always grab the wrong object and run into problems.




This may not be the best way but I put an OnCollisionEnter2D function in my PunchBoxEnable script. I check if the tag being collided with is "PunchingBag". If it is I send the message ("Hurt") and also log so I know what's being called. I used the Enter and the Stay just to see how the Unity engine handles this stuff.

The PunchingBag script knows what to do with Hurt.

Here is the script for the KickBoxEnable:

 using UnityEngine;  
 using System.Collections;  
 public class KickBoxEnable : MonoBehaviour {  
      // Use this for initialization  
      void Start () {  
     collider2D.enabled = false;  
      }  
      // Update is called once per frame  
      void Update () {  
     // If the player presses alt or Y the kickbox collider is enabled.  
     if (Input.GetButtonDown("Fire2")) {  
       collider2D.enabled = true;  
     }  
     else {  
       collider2D.enabled = false;  
     }  
      }  
   void OnCollisionEnter2D(Collision2D collider) {  
     if (collider.gameObject.tag == "PunchingBag") {  
       collider.gameObject.SendMessage("Hurt");  
       Debug.Log("Enter called.");  
     }  
   }  
   void OnCollisionStay2D(Collision2D collider) {  
     if (collider.gameObject.tag == "PunchingBag") {  
       collider.gameObject.SendMessage("Hurt");  
       Debug.Log("Stay called.");  
     }  
   }  
 }  
Here is the script for the PunchingBag:

 using UnityEngine;  
 using System.Collections;  
 public class PunchingBag : MonoBehaviour {  
   public int HP = 1;  
      // Use this for initialization  
      void Start () {  
      }  
      // Update is called once per frame  
      void Update () {  
     if (HP < 1) {  
       GetComponent<Collider2D>().enabled = false;  
       GetComponent<SpriteRenderer>().enabled = false;  
     }  
      }  
   void Hurt() {  
     HP--;  
   }  
 }  

Comments

Popular Posts