Shake UI Image/Gradually Change Color
Hello!
I've recently picked up learning Unity, and by that extent C#. As such, I do not yet have a very extensive understanding of C# coding, and am, as such, making a couple of simple projects to get the hang of it. But I've run into a bit of a problem I can't find the proper function/solution for:
Upon the opponent being hit, I want to invoke a function (or two functions) to do two things:
The image shakes from left to right
The image briefly turns red (or a light shade of red)
This, of course also goes for the player character upon being hit. I've scoured the internet trying to find the right functions or code to use, but every time I type in similiar questions it usually only refers to camera shake. What code do I need to use to accomplish this?
Answer by hfpngaming · Jun 04, 2016 at 04:32 AM
This should work and fit your needs, but you might want to tweak it to your needs. Also my script is called by pressing space, you can change that to being called when damage is dealt.
public class EnemyDamage : MonoBehaviour {
public GameObject enemy;
private SpriteRenderer enemyRenderer;
public float damageTime = 0.1f; // duration of shake and red color
public float shakeRange = 20f; // shake range change be changed from inspector,
//keep it mind that max it can go is half in either direction
// Use this for initialization
void Start () {
//by saving the renderer you will not need to use GetComponent<> again and again
enemyRenderer = enemy.GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Space))
{
StartCoroutine(Damage());
StartCoroutine(EnemyShake());
}
}
private IEnumerator Damage()
{
Color originalColor = enemyRenderer.color;
WaitForSeconds wait = new WaitForSeconds(damageTime);
enemyRenderer.color = new Color32(255, 0, 0, 255); //adjust color to your needs
yield return wait;
enemyRenderer.color = originalColor;
}
private IEnumerator EnemyShake()
{
float elapsed = 0.0f;
Quaternion originalRotation = enemy.transform.rotation;
while (elapsed < damageTime)
{
elapsed += Time.deltaTime;
float z = Random.value * shakeRange - (shakeRange /2);
enemy.transform.eulerAngles = new Vector3(originalRotation.x, originalRotation.y, originalRotation.z + z);
yield return null;
}
enemy.transform.rotation = originalRotation;
}
}
Thanks alot! :D This really has saved me a from a headache or two.