0
votes

I have two scripts, one attached to a gameobject and the other attached to an enemy prefab that is instantiated over time. The script attached to the gameobject uses OnTriggerEnter2D to detect when the enemy has entered, then the health bar for the object goes down by one. Iit works, the only problem is now is that because of the fact that the enemy comes up then walks back down, the enemy is colliding with the objects more than once which is not what I want.

I have tried things like using booleans to stop it colliding more than once but other prefabs enemies isn't able to collide with the gameobject because of the boolean is being set to true and not being set back to false. I don't want to use yield wait for seconds because enemies do spawn often and so it won't really look normal; I also tried onTriggerExit2D but you get the idea if I try that method. Is there any other way of detecting if an enemy has entered the objects collider damaging the object once but then when the enemy comes back down he ignores the collision (without turning off the enemies or the gameobject's collider) aka all instantiated enemies is able to collide with the gameobject when they are going up but not when they are coming back down.

1
I want to make sure I'm envisioning the problem correctly. So you have prefab creatures spawning and then walking up and down a pathway that has a trigger2d on it somewhere. You want the trigger to only damage the monsters while they're walking up the pathway but not while they're walking down?oxrock
Yes! Sorry if I made it confusing, I sometimes ramble on and over complicates things! But yes, that is what I want to do!wasicool2

1 Answers

1
votes

Your best bet is to simply do a bool check on the monsters if they're going north or not. There are several ways to go about this. If you know where they are going you can simply compare where they are going to where they are and compare the y vector values. so something like this:

public bool monsterNorthChecker(){
    if(monsterDestination.y > currentLocation.y){
        return true;
    }
    else{
        return false;
    }
}

Then you can simply call that function OnTriggerEnter and verify if the monster is going north or not, if he is, take away his health. If you don't know his destination, you'll probably have to resort to more tedious means of determining destination direction. Something like comparing the y values of last frame's vector2 to this one and see which way he's moved.