Есть ли способ временно изменить цвет спрайта после столкновения с C# в Unity? - PullRequest
0 голосов
/ 29 января 2020

Я создаю 2D стрелялку сверху вниз. Я хочу добавить эффект урона противнику, когда пуля сталкивается с ним.

Есть ли способ повернуть белый спрайт со спрайтом на 0,5 секунды, а затем исчезнуть до нормального спрайта.

void OnCollisionEnter2D(Collision2D collision)
{
    if(collision.gameObject.tag == "Enemy")
    {
        EnemyController enemy = collision.transform.GetComponent<EnemyController>();
        if(enemy != null)
        {
            // Take the actual damage
            enemy.TakeDamage(damage);

            // Change sprite color temporarily here
        }
    }
}

Ответы [ 2 ]

1 голос
/ 29 января 2020

Я бы сделал это с сопрограммой:

public void TakeDamage()
{
    // Tints the sprite red and fades back to the origin color after a delay of 1 second
    StartCoroutine(DamageEffectSequence(sr, Color.red, 2, 1));
}

IEnumerator DamageEffectSequence(SpriteRenderer sr, Color dmgColor, float duration, float delay)
{
    // save origin color
    Color originColor = sr.color;

    // tint the sprite with damage color
    sr.color = dmgColor;

    // you can delay the animation
    yield return new WaitForSeconds(delay);

    // lerp animation with given duration in seconds
    for (float t = 0; t < 1.0f; t += Time.deltaTime/duration)
    {
        sr.color = Color.Lerp(dmgColor, originColor , t);

        yield return null;
    }

    // restore origin color
    sr.color = originColor;
}
0 голосов
/ 29 января 2020

Существует два простых способа добавить задержку к вашей функции

1.Invokes:

При столкновении измените цвет спрайта, получив спрайтовый компонент с помощью

Getcomponent<sprite>().color = color.white;
Invoke("revertcolor" , 0.5f); (it will add a time delay and then call the other function)

, затем создайте другую функцию, такую ​​как revertcolor () и верните цвет в этой функции с помощью Getcomponent (). color = originalcolor;

2.Coroutines : Другой простой метод - использование сопрограмм ..... просто создайте сопрограмму, используя

ienumerator revertcolor()
{
using Getcomponent<sprite>().color = originalcolor;
yield return new waitforseconds(0.5f);  // It will add a time delay in your function
}
> After creating this coroutine, just call it in you collision by using startcoroutine(revertcolor);
using Getcomponent<sprite>().color = color.white;
...