实现吃到宝石后宝石上升且渐隐的效果
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gem : MonoBehaviour
{
public float speed = 5f;
private SpriteRenderer sr;
private void Start()
{
sr = GetComponent<SpriteRenderer>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
StartCoroutine(FlyAway());
}
}
IEnumerator FlyAway()
{
float alpha = 1f;
while (true)
{
transform.Translate(Vector3.up * speed * Time.deltaTime);
alpha -= Time.deltaTime * 1.5f;
sr.color = new Color(sr.color.r, sr.color.g, sr.color.b, alpha);
if (alpha <= 0)
break;
yield return null;
}
yield return new WaitForSeconds(2f);
Destroy(gameObject);
}
}