- Home /
The question is answered, right answer was accepted
Any good way to make code do what you want based on how many frames that has passed?
Hey! In the 2D game I'm currently trying to do the player can die. When the player dies I want the players death to be animated using some sprites. The code I'm currently using contains many else-if statements and I'm not sure whether this is quite an ugly code or not given the situation. This is all code I'm using that I believe is relevant:
private SpriteRenderer spriteRend;
public Sprite[] allDeathSprites, currentDeathSprites;
private bool playerIsDying = false;
private void Update() {
if (playerIsDying) {
PlayerDeath();
}
}
private int killStage = 0;
public void PlayerDeath() {
if (++killStage == 1) {
spriteRend.sprite = currentDeathSprites[0];
} else if (killStage == 5) {
spriteRend.sprite = currentDeathSprites[1];
} else if (killStage == 9) {
spriteRend.sprite = currentDeathSprites[2];
} else if (killStage == 13) {
spriteRend.sprite = currentDeathSprites[3];
} else if (killStage >= 20) {
Respawn();
playerIsDying = false;
}
}
The 'allDeathSprites' array contains all sprites for each death scenario while the 'currentDeathSprites' array will be set to some sprites depending on what causes the players death. Is this code bad and do you have a better suggestion? Thanks!
Answer by Commoble · Mar 22, 2017 at 03:27 AM
What I do to animate my sprites is to define how often I want my sprite to animate in terms of frames per second, then keep track of a timer using unity's Time class and update the sprite to the next frame after the correct amount of time elapses.
Thank you, that seems like a good idea! I'll say if I've made this work in my script.
Although I didn't choose to use the solution you suggested it's thanks to you I found a solution. :D
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Sprite Fade In/Out Not Working 1 Answer
Why Sprite is null? 0 Answers
Character Sprite "Spasms" 0 Answers