Question by
Volk37 · Jan 20, 2016 at 03:05 AM ·
collision detection2d-physicscollision2d
Executing a function upon 2d collision
Hey guys,
I am working on a 2D Castle Defense game. I have a base with a polygon collider and a rigid body set to kinematic. Above it I have a square that has a box collider and a rigid body. The base has a function that decreases its healthbar. I want to run that function every time I get a collision with the square. I have tried using OnCollisionEnter, but it doesn't seem to work. Here is the code:
using UnityEngine;
using System.Collections;
public class Base_Health : MonoBehaviour
{
public float maxHealth = 100f;
public float currHealth = 0f;
public GameObject healthBar;
// Use this for initialization
void Start ()
{
currHealth = maxHealth;
}
// Update is called once per frame
void Update ()
{
}
void OnCollisionEnter (Collision col)
{
if (col.gameObject.name == "Enemy")
{
decreaseHealth();
}
}
void decreaseHealth ()
{
currHealth -= 2f;
float calcHealth = currHealth / maxHealth;
setHealthBar(calcHealth);
}
public void setHealthBar (float myHealth)
{
healthBar.transform.localScale = new Vector3(Mathf.Clamp(myHealth, 0f, 1f), healthBar.transform.localScale.y, healthBar.transform.localScale.z);
}
}
I appreciate any feedback.
Comment
Answer by ZefanS · Jan 20, 2016 at 03:26 AM
If you are using 2D physics then you need to use OnCollisionEnter2D().
This question and this question might help clarify.
Hope this helps!