# Changing a Sprite When Hit in GameMaker

I am making a simple little Galaga style game. I want the objects sprite to change whenever it is hit.

For example if a laser hits an alien then the sprite takes 1 out of 4 damage to its health points (HP). However I want the sprite to change from green to yellow after 1 hit, yellow to orange after 2 hits, orange to red after 3 hits, and red to pixel explosion after all 4 HPs are lost. That way you can easily distinguish the amount of health each alien has left.

How can I do this? Preferably explain it in code.

I tried this and it works perfectly, if you would like the gamemaker file, tell me...

So the alien image make three more image indexes.. Or to be way simpler make three more seperate images of the alien, Make a normal image of the alien, a green, a yellow, a red, and look online for some explosion gif.

So if your laser beam is an object and not just a drawn event image, thats good and what we need.

## Alien Object

So in your alien event add a collision with the laser beam. now in the create event make a variable:

hits=0


Now back to the Collision event. In there add this code:

hits=+1


Now make a Step event and add this code:

if hits=1{ action_sprite_set(sprAlienGREEN,0,0) } //Alien gets hit one time
if hits=2{ action_sprite_set(sprAlienYELLOW,0,0) } //Alien gets hit two times
if hits=3{ action_sprite_set(sprAlienRED,0,0) } //Alien gets hit three times


Now we need to make that alien explode! so now working still in the step event add this code

if hits=4{ instance_change(objExplosionGif,1) } //Alien dies with exploding gif'


Now hold on we need to make the explosion object!

## Explosion Object (objExplosionGif)

Add an event called Other and in the list of items click Amination End (if i am correct that is what its called). Now enter this code

instance_destroy(x,y) //Destroy this explosion when animation is done...


Hopefully it worked for you with ease!

• I used this method but the character would only go yellow and did not go further, what am I doing wrong?
– Joe
Jun 14 '18 at 9:00

I was looking for a solution to a simular problem of making a sprite flash when it was hit. What i would suggest is to add the different colours (or damage states) as images within the same sprite. Then include a piece of code in the enemy object's step event that is something like:

If (hitpoints >= 10) {image_index=0} // the original sprite

If (hitpoints <= 5) {image_index=1} // the first damage state

And so on...