1

I made a enemy prefab and a object to it (Field of View).

The enemy has a Box Collider 2D and a Rigidbody 2D, the FOV only has Box Collider 2D.

The enemy checks if a bullet is hitting him and takes damage from the bullets.

My problem is that he gets double the damage he should normally get, because the FOV seems to detects the bullet too. But the FOV Object doesn't have the script for the detection but detects it anyways.

I disabled the Box Collider 2D and the enemy got the normal damage. But that is not a real solution. I looked if the FOV had the accidentally the same script as the enemy, but that is not the case.


What's the reason for that? Thanks in advance!

HeyoMayo
  • 33
  • 7
CodingGuy
  • 11
  • 3
  • Please show the code related to the bullet and collider interaction – hijinxbassist Apr 11 '23 at 21:32
  • 2
    You should use physics layers to control physics interactions. But even so, your scripts will also need to do some checking to make sure what they collided with is expected - e.g., does the collided object have a "projectile" tag or a "Projectile" component? If so, then take damage. Otherwise it will take damage from every single physics object that it hits. By the way, I've found it is almost always easier to apply this logic on the projectile objects (i.e., check if the projectile hit something with a Health or Enemy component, not the other way around). –  Apr 11 '23 at 22:24
  • 2
    +1 to @rshepp. An alternative and maybe more performant approach is to use the collision matix between layers that's built in. Look in Project Settings > Physics. – Absinthe Apr 11 '23 at 23:58
  • 1
    Agreed, that is what I meant by physics layers although I expressed it poorly. Use the matrix filter out any physics interactions that should never occur, but for safety still do some checks in code. –  Apr 12 '23 at 00:25
  • 1
    @rshepp i did it like you said so that the bullet checks if it collides with an enemy, and if yes then it does the damage to that enemy. Is it ok if I did it like this? I checked with OnTriggerEnter2D and if it's a object with the "Enemy"-Tag. To do the damage to the enemy which collided with the bullet i did this: `collision.GetComponent().enemyHP--;` (Sure only doing "--" isn't the best thing, but I'll improve it later with a damage variable and so on..) – CodingGuy Apr 12 '23 at 09:41

0 Answers0