Good day, I'm trying to create an enemy that damages the player because that's what enemies do. I have figured it out on how to do this the only problem is that the enemy kills the player almost instantly and is too overpowered... I was trying to put some cooldown before the enemy strikes again but unfortunately, an OnTriggerEnter2D
seems to only accept 1 if statement.
void OnTriggerEnter2D(Collider2D col){
//What iam trying to achieve but this doesn't work
if(Time.time > nextDamageTime) {
if(col.CompareTag("Player")){
player.curHealth -= 1;
Debug.Log("Enemy damaged player!");
nextDamageTime = Time.time + cooldownTime;
}
}
}
First of all this is c#. There is nothing that can anyhow control how many if
blocks you open within a method.
So, no there is no limit on conditions and if
blocks within OnTriggerEnter2D
!
I don't see a direct problem in your code actually except maybe: OnTrigggerEntet2D
is called exactly once namely in the moment the trigger enters without exiting. So if this already instantly kills the player then reducing 1
might simply be a too high value.
With the timer nothing happens because as said it is called only once, so in the case the timer wasn't finished yet nothing happens until the enemy leaves and re-enters eventually.
You might want to rather use OnTriggerStay2D
which is rather called every frame as long as a trigger collides.
float timer;
private void OnTriggerEnter2D (Collider other)
{
// reset the timer so the first hit happens immediately
timer = 0;
}
private void OnTriggerStays2D(Collider other)
{
if(!col.CompareTag("Player")) return;
timer -= Time.deltaTime;
if(timer > 0) return;
timer = cooldownTime;
player.curHealth -= 1;
}
Which now would reduce the players health by 1
every cooldownTime
seconds.
In general especially for multiple enemies I personally would rather give the player the control over timer after it was last hit so the player itself has kind of an invincible time. Enemies can simply attack like they would do usually but the player itself decides whether the damage counts or not.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.