Im working on a game where you are falling through some kind of corridor and need to avoid stuff while falling
The level generation works that it takes a random prefab out of an array and instantiates it below the last one so the walls are just a lot of different objects stacked on top of each other
and when i tried to implement dying I realized that I can´t use the “OnCollisionEnter2D()” function to reduce the health of the Character because it would be loosing health every time it comes past a new piece of wall
Simply add a counter and bool check to the OnCollision code.
I do this exact thing on my projectile’s to avoid damaging unintended targets.
The following code is from my projectile script to give you an idea of what I mean.
public void Activate()
{
hasHasCollided = false;
collisions = 0;
currentLifeTime = 0f;
gameObject.SetActive(true);
if (!hasHasCollided && Data.Lifetime > currentLifeTime)
behavior.Perform(this);
}
private void OnCollisionEnter(Collision other)
{
collisions++;
hasHasCollided = true;
Behavior.End(this);
if (collisions <= 1)
{
Collided?.Invoke(this, new ProjectileCollisionEventArgs(other.gameObject.transform.GetInstanceID(), projectileData.Value));
}
}
Your implementation may end up different from mine but the concept remains.
Hello @unity_943kingpl !
FullMe7alJake7’s answer is a good solution and should work for you! Another idea for you is to have a singular variable keeping track of the amount of seconds it’s been since the player last took damage. From there, whenever the player hits a wall, before they take damage, quickly check to see if the last time they took damage was - say - at least 5 seconds ago. If it was, then it’s been long enough that the player should take more damage.
Below is an example of this implementation:
private float timeSinceLastDamage = 0f;
public void Update() {
timeSinceLastDamage += Time.deltaTime;
}
private void TakeDamage() {
if (timeSinceLastDamage >= 5f) {
player.hp -= 10;
timeSinceLastDamage = 0f;
}
}
Hopefully this helps!