- Home /
The question is answered, right answer was accepted
On collision deal damage each few seconds and doesn't keep consistent collision?
Hi, I am experiencing bit of an error. I am trying to make so that every time that the enemy is colliding with the player, it will deal damage to player every few seconds.
These both are attached to the player-health script:
I am ok with coding so I don't need a script, however I would need a good explanation for it. Script would be nice to see and obtain information from too.
Thanks
Answer by JoeriVDE · Oct 18, 2017 at 06:28 PM
I would use OnCollisionStay and then just add Time.Deltatime to the timer so it increases each frame the collision is hitting.
Example script (didn't test this though). Note: this won't work with multiple enemies.
public class CollisionDamageTimer : MonoBehaviour {
// Timer to track collision time
float _timeColliding;
// Time before damage is taken, 1 second default
public float timeThreshold = 1f;
// player health I assume?
int _currentHealth = 100;
// called when first colliding
void OnCollisionEnter(Collision collision) {
if (collision.gameObject.tag == "Enemy") {
// Reset timer
_timeColliding = 0f;
Debug.Log("Enemy started colliding with player.");
// Take damage on impact?
PlayerDamage(5);
}
}
// called each frame the collider is colliding
void OnCollisionStay(Collision collision) {
if(collision.gameObject.tag == "Enemy") {
// If the time is below the threshold, add the delta time
if (_timeColliding < timeThreshold) {
_timeColliding += Time.deltaTime;
} else {
// Time is over theshold, player takes damage
PlayerDamage(5);
// Reset timer
_timeColliding = 0f;
}
}
}
void PlayerDamage(int amount) {
_currentHealth -= amount;
Debug.Log(_currentHealth);
if(_currentHealth <= 0f) {
Die();
}
}
}
Wow, thanks it actually worked. 4 hours on finding a script when it looks like this. Thanks :)