- Home /
Question by
bitznicegameing · Apr 09, 2020 at 09:01 PM ·
damage
cant seem to get damage on collision to work
Im a bit new to unity and Ive gone through a ton of tutorials online (thx Brackeys) but none of them seem to work when I input them into my game Ive started to code on my own from what Ive learned but Im not sure what Im missing or doing wrong to make this work heres the code Im using for my enemy to take damage on a collision from a bullet
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemy : MonoBehaviour
{
public Transform target;
public int moveSpeed;
public int rotationSpeed;
protected int health = 5;
public GameObject hitEffect;
public int damage = 1;
void Start()
{
target = GameObject.Find("Player").transform;
}
void Update()
{
if (target != null)
{
Vector3 dir = target.position - transform.position;
dir.z = 0.0f;
if (dir != Vector3.zero)
transform.rotation = Quaternion.Slerp(transform.rotation,
Quaternion.FromToRotation(Vector3.right, dir),
rotationSpeed * Time.deltaTime);
transform.position += (target.position - transform.position).normalized
* moveSpeed * Time.deltaTime;
}
GetComponent<Rigidbody2D>().velocity = Vector3.zero;
}
void OnTriggerEnter(Collider Enter, int damage)
{
if (Enter.CompareTag("Enemy"))
{
health -= damage;
}
}
public void OnCollisionEnter2D(Vector2 dir, int damage)
{
if (health < 1)
{
GameObject effect = Instantiate(hitEffect, transform.position, Quaternion.identity);
Destroy(effect, 5f);
Destroy(gameObject);
}
}
}
Comment