- Home /
Gradually Change Color from Original to Red with Each Collision
I'm trying to change the color of the player object everytime it collides with an obstacle. I want to make it so that each time it collides, it becomes more red, however, I don't even know where to start. Here is my current CollisionTracker script.
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
PrintDamage();
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Obstacle"))
{
damagePercentage += 1;
Debug.Log("Collision");
}
}
public void PrintDamage()
{
if (damagePercentage <= 100)
{
damageText.text = $"Damage: {damagePercentage}%";
}
}
}
Answer by JoltenDev · Feb 24, 2020 at 06:50 AM
You can use this https://docs.unity3d.com/ScriptReference/Material.SetColor.html :)
Is there a way so that the player gets a little more red each time it hits an obstacle, rather than the player just turning red immediately?
You could turn the colors you want into variables using this, https://docs.unity3d.com/ScriptReference/Color-ctor.html, and then use those variables in the setcolor script. You'll have to find out the float values of the colors you want, and i'm not good with color palettes and integrating them into rgb values, so I won't be much help telling you how to find the colors you want, but i'm sure there's some article out there that can provide you the information you need. :)
Here's some pseudocode that should do something like it:
Color _baseColor;
float damagePercent = 0f;
void Start()
{
_baseColor = my$$anonymous$$aterial.GetColor("myColor");
}
void OnCollisionEnter()
{
float damagePercent += 0.05f; //0.05 is arbitrary, but the point is to add the amount you want the 'redness' to increase.
Color newcolor = _basecolor + (Color.Red * damagePercent);
my$$anonymous$$aterial.SetColor("myColor", newcolor);
}
Does that help? Interacting with shaders has a bit of a learning curve. I'll assume you know how to get the proper material (my$$anonymous$$aterial) and color name (myColor) but feel free to post if you need more guidance.