Question by
SpyderManToo · Mar 06, 2021 at 12:41 AM ·
c#effecthealth
How to make low health vignette?
I've tried this a few times, it doesn't work, how do I make a low health vignette that fades in when you are below x% health and fade back out when you are above x% health? i have a script that does the first part but doesnt do the second part...help? heres the script
using UnityEngine;
public class PlayerStats : MonoBehaviour { [Header("Health")] public int maxHealth; public int currentHealth;
[Header("Effects")]
public float FadeInTime;
private float fadeTimeSoFar = 0f;
public float FadeOutTime;
private float fadeOutTimeSoFar = 1f;
public CanvasGroup CanvasGroupComponent;
[Header("References")]
public Rigidbody2D playerRb;
Enemy enemy;
// Start is called before the first frame update
void Start()
{
currentHealth = maxHealth;
}
// Update is called once per frame
void Update()
{
if (currentHealth <= 0)
{
Debug.Log("You ded");
Time.timeScale = 0f;
}
if (currentHealth <= maxHealth * 0.4) //Check if you have <= 40% health
{
if (fadeTimeSoFar < FadeInTime) //If the vignette isn't fully faded in yet:
{
fadeTimeSoFar += Time.deltaTime; //Add time to the fade in time
float percent = fadeTimeSoFar / FadeInTime; //Calculate what percentage it is at.
if (percent > 1f) //If the percent is more than 1
{
percent = 1f; //Set the percent to 1 to avoid errors
}
CanvasGroupComponent.alpha = percent; //Set the alpha to the current percentage so it can fade in
}
}
else
{
if (fadeOutTimeSoFar < FadeOutTime) //If the vignette isn't fully faded out yet:
{
fadeOutTimeSoFar -= Time.deltaTime; //Add time to the fade out time
float _percent = fadeOutTimeSoFar / FadeOutTime; //Calculate what percentage it is at.
if (_percent < 0f) //If the percent is less than 0:
{
_percent = 0f; //Set the percent to 0 to avoid errors
}
CanvasGroupComponent.alpha = _percent; //Set the alpha to the current percentage so it can fade out
Debug.Log(_percent);
}
}
}
public void TakeDamage(int damageToTake)
{
currentHealth -= damageToTake;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Enemy"))
{
enemy = collision.gameObject.GetComponent<Enemy>();
currentHealth -= enemy.contactDamage;
Debug.Log("You came into contact with an enemy, you are now at " + currentHealth + " health.");
}
}
}
doesn't rly work tho ;-;
Comment
Your answer
Follow this Question
Related Questions
How to do multiple inheritance (or workaround) with Unity? 1 Answer
Health system in a text based game. 2 Answers
Why does my start function not work? 1 Answer
Slowing down while loops 2 Answers