- Home /
How to make a tick speed for heart health system?,How to make a tick speed for health script?
I'm making a 2D game using the hearts system, every time my player collides with an enemy, one point of health is deduced. The problem is, every time my player collides, the health is reduced super quickly, killing the player in 1 or 2 seconds. How do I make it so that I can have a tick speed or a moment of invincibility so that my player doesn't automatically die when colliding with an enemy?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Health: MonoBehaviour
{
public int health;
public int numOfHearts;
public Image[] hearts;
public Sprite fullHeart;
public Sprite emptyHeart;
void Update(){
if(health > numOfHearts){
health = numOfHearts;
}
for (int i = 0; i < hearts.Length; i++) {
if(i < health){
hearts[i].sprite = fullHeart;
} else {
hearts[i].sprite = emptyHeart;
}
if(i < numOfHearts){
hearts[i].enabled = true;
} else {
hearts[i].enabled = false;
}
}
}
private void OnCollisionEnter2D(Collision2D collision) {
if (collision.gameObject.CompareTag("Enemy")) {
health--;
}
if(health <= 0){
Destroy(gameObject);
}
}
}
Answer by Klarzahs · Oct 26, 2020 at 08:48 AM
Hi @Jollymello9,
You can use the time difference as well, see here.
Code example (untested)
float lastTime = 0;
float threshold = 5;
voidOnCollisionEnter2D(Collision2D collision){
if(Time.time - lastTime > threshold && .. compareTag("Enemy")){
health--;
lastTime = Time.time;
}
..
}
As a side note, have a look at OnCollisionStay2D as well, it gets called everytime you stay in a collider, whereas enter only gets called, well, if you actively newly enter a collider. You probably want to use a combination of both?
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Jumping from special jump orb 1 Answer
The player randomly freezes in place while other objects move ingame 1 Answer
How can I make a speed booster in a 2D game? 1 Answer
Distribute terrain in zones 3 Answers