Tinting an Enemy to Show Damage
In the 2D XNA game I am developing, all my enemies have hit point values and often take multiple shots from the player to be killed. I did not want to make a specific animation for when an enemy is shot but does not die but I also wanted some kind of visual indication that the enemy had been damaged/hurt/slightly annoyed. I found that I could easily do this by changing the color in the SpriteBatch.Draw() method for a small amount of time following when the enemy got shot.
First, I created the two variables hurtAnimationTimer and hurtAnimationTime. When an enemy gets shot, hurtAnimationTimer be set to the value in hurtAnimationTime and continue to count down until it reaches zero.
float hurtAnimationTimer = 0f;
float hurtAnimationTime = 200;
I also needed to create objects to hold the two colors I would be using, normalColor for when an enemy is unhurt (all white values so that your image is not tinted) and hurtColor for displaying the enemy in a different color just after he has been shot.
Color normalColor = new Color(255, 255, 255, 150);
Color hurtColor = new Color(255, 100, 100, 150);
In the Update method of my game loop, I call the enemy's IsShot() method whenever one of my enemies is shot. This kicks off the hurt animation timer for that specific enemy.
public void IsShot()
{
// Start the hurt animation
hurtAnimationTimer = hurtAnimationTime;
}
In the Update method for each enemy, I check to see if hurtAnimationTimer is set and, if so, I decriment it based on the amount of time that has passed since the last game loop. If it happens to go below zero, I set it back to zero.
if (hurtAnimationTimer > 0f)
{
hurtAnimationTimer -= (float)gameTime.ElapsedGameTime.TotalMilliseconds;
if (hurtAnimationTimer < 0f)
{
// End the hurt animation
hurtAnimationTimer = 0f;
}
}
Finally, in the Draw method for my enemy, I pass the hurtColor if there is a hurtAnimationTimer value. Otherwise, the enemy gets drawn as normal.
if (hurtAnimationTimer == 0f)
{
theSpriteBatch.Draw(enemyTexture, CurrentPosition, source, normalColor,
0.0f, Vector2.Zero, scale, SpriteEffects.None, 0);
}
else
{
theSpriteBatch.Draw(enemyTexture, CurrentPosition, source, hurtColor, 0.0f,
Vector2.Zero, scale, SpriteEffects.None, 0);
}
This effect will cause your enemy to be briefly tinted red when he gets shot before returning to his normal color. Modify hurtAnimationTime if you want a longer or shorter duration for this effect and change hurtColor if you want to tint your enemy a different color.
Below is a video of how this looks in action (which you can see when the larger blue enemies get shot), though it may be hard to really tell due to the poor video quality on YouTube.
-->
This article has been view 651 times.
|