- Home /
Projectiles aren't hitting enemies
Hi!
I have made some scripts for the player to shoot and the enemy to take damage, I have added colliders etc. so they should be hitting each other and the bullet should be subtracting health from the enemy and then destroying them but the projectile seems to pass through without damaging the enemy. I've been looking around but there doesn't seem to be anywhere that provides answers.
Thanks in advance!
Part of projectile script that is being used to damage enemy:
public int damageToGive;
void OnCollisionEnter2D(Collision2D other){
if (other.gameObject.tag == "Enemy") {
other.gameObject.GetComponent<EnemyHealthManager> ().HurtEnemy (damageToGive);
}
}
Part of the EnemyHealthManager script that is meant to be taking away the health:
public int health;
public int currentHealth;
void Start () {
currentHealth = health;
}
void Update () {
if (currentHealth <= 0) {
Destroy (gameObject);
}
}
public void HurtEnemy(int damage){
currentHealth -= damage;
}
}
Are you sure layers of enemies and bullets are colliding in Physic2D collision matrix?
Are you sure both enemies and bullets have 2D colliders?
I'm pretty sure at least one of the objects should have Rigidbody2D
If you have Rigidbody2D then maybe set collision detection mode to continous
Answer by Qek · Sep 12, 2018 at 02:20 PM
Ok solved this myself, the issue was OnCollisionEnter2D, it should instead be OnTriggerEnter2D e.g.
public int damageToGive;
void OnTriggerEnter2D(Collision2D other){
if (other.gameObject.tag == "Enemy") {
other.gameObject.GetComponent<EnemyHealthManager> ().HurtEnemy (damageToGive);
}
}