Trouble with maths relating to GameObject[] anyone able to assist with a formula
Hi Guys,
I'm trying to make this system where i have a bunch of damage sprites in a sprite[3] array. player has 100 Health
4 Sprites to be assigned evenly over the 100 health int range. How do i write a formula? That's easy right, just assign a sprite at 100 health of sprite[0], then at 75 do sprite[1] and 50 do sprite[2] and 25 do sprite[3]. But i am struggling with the math.
I want to make it so no matter how many sprites I add or remove from the array the math will work and divide the health up into the amount of sprites I have and then somehow assign the sprites as needed.
MaxPlayerHealth(100) / sprites[].length(4) = 25 (Each Sprite rep 25 Segment)
here is my Code so far
private void OnTriggerEnter2D(Collider2D col) //Colider is Bullet //Triger is Enemy Object
{
//Debug.Log($"Enemy has detected a colission {col.ToString()}");
if (col.gameObject.tag == "Bullet")
{
//SET SPRITE
int spriteToActivateIndex = Mathf.Abs(HealthStarting / Health) / sprites);
//Mathf.Clamp((HealthStarting / Health) / LifecycleSprites.Length, 0, LifecycleSprites.Length);
print("EnemyHealth - Sprite Index " + spriteToActivateIndex);
sr.sprite = LifecycleSprites[spriteToActivateIndex];
//Set Explosions
int explosionToActivateIndex = Mathf.Abs(HealthStarting / Health) / explosions;
print("EnemyHealth - Explosion Index " + explosionToActivateIndex);
GameObject ToSetActive = ExplosionsPrefabs[explosionToActivateIndex];
ToSetActive.SetActive(true);
Destroy(col.gameObject, 0.25f); //destroy bullet
}
}
I mean, I could be dodgy and wrap it in a try catch, because all the divide by zero and index-exceptions are nearer to the end of the Objects life anyway, that's not really what I want but will work for now.
try
{
//SET SPRITE
int spriteToActivateIndex = $$anonymous$$athf.Abs(HealthStarting / Health) / sprites;
//$$anonymous$$athf.Clamp((HealthStarting / Health) / LifecycleSprites.Length, 0, LifecycleSprites.Length);
print("EnemyHealth - Sprite Index " + spriteToActivateIndex);
sr.sprite = LifecycleSprites[spriteToActivateIndex];
}
catch (IndexOutOfRangeException Ior)
{
print(Ior);
Destroy(gameObject);
}
Your answer
