Saturday, February 23, 2013

Let me get a flash!

I wanted to provide the player feedback upon getting hit. A good way to do this is to "flash" the player, or alternate very quickly between various colors.



There are a few ways you can do this in a 2D game when you're using sprites. However, I'm not using sprites just yet (I'm using the Unity provided basic shape models), so I have to start manipulating the applied materials of the player cube model directly. Simply, on the player object material, you can just interpolate between two (or more, if you're feeling bold) colors rapidly for a short duration.

The following Gist may not be the most elegant, and in fact it's very inefficient, but it's my First Stab Solution™ at the problem. After you're done laughing, be kind and call me out in the comments and show me a better way!



So what do we have? When collision occurs with the player, we begin a InvokeRepeating of the method colorFlash. The colorFlash method will lerp, or interpolate, between the two Colors in the flashColors array. By using the Matf.PingPong method to calculate a lerp time, we add variance to the length of time used for the lerp. The lerp parameter passed into Color.Lerp will be clamped between 0 and 1. If it's 0, the first color is returned, if 1, the second. That's why we divide the result of Mathf.PingPong by flashLerpDuration, to receive a float value between 0 and 1, which allows Color.Lerp to return even more variance in color. 

Unfortunately (or fortunately, depending on how you look at it), when you use InvokeRepeating, it'll call the specified method until you make a call to CancelInvoke (I would like for there to be an implementation of InvokeRepeating that accepts a float value as a parameter to specify how many seconds the invoking should last). So, we have to setup a timer, flashInvokeDuration, and when that timer reaches 0, we make the call to CancelInvoke and the player will stop flashing. 

No comments:

Post a Comment