Hi, I'm trying to make a 2d shooting minigame, but my 3 collisions are "bugging". All enemies has 10 hp, and head should do 5 damage, torso 3, and legs 1, but when I use 2 or 3 collisions it cannot detect anything, or sometimes I get torso or legs, but never head and I need to click a lot. First I did it with MouseOnOver events, but I tried to rewrite it with AI because I though that was the problem, now it uses Layers, enums and Raycast.
All code involved:
using UnityEngine;
using UnityEngine.InputSystem;
public class ShootingThings : MonoBehaviour
{
[SerializeField] private int health = 10;
public void ApplyDamage(int dmg)
{
//Debug.Log(health);
//Debug.Log(dmg);
health -= dmg;
if (health <= 0)
Destroy(gameObject);
}
}
public class MouseBodyPart : MonoBehaviour
{
public enum BodyPart { Head, Torso, Legs }
[SerializeField] private BodyPart part;
[SerializeField] private int damage = 1;
private ShootingThings enemy;
private void Awake()
{
enemy = GetComponentInParent<ShootingThings>();
if (enemy == null)
{
Debug.LogError("No ShootingThings found in parent!");
}
}
public void Hit()
{
enemy.ApplyDamage(damage);
}
}
public class ClickShooter : MonoBehaviour
{
[SerializeField] private Camera cam;
[SerializeField] private LayerMask hurtboxMask;
private void Awake()
{
if (cam == null) cam = Camera.main;
}
private void Update()
{
if (!Mouse.current.leftButton.wasPressedThisFrame) return;
Vector2 world = cam.ScreenToWorldPoint(Mouse.current.position.ReadValue());
RaycastHit2D hit = Physics2D.Raycast(world, Vector2.zero, 0f, hurtboxMask);
if (!hit) return;
var part = hit.collider.GetComponent<MouseBodyPart>();
if (part != null)
part.Hit();
}
}