using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ClickEffect : MonoBehaviour
{
///
/// 屏幕特效原始资源
///
public GameObject fxSample;
///
/// 屏幕特效的生命时长,超过后会进行缓存
///
public float fxLifeTime = 1.0f;
///
/// 屏幕特效的容器(父对象)
///
public RectTransform fxContainer;
///
/// 屏幕特效渲染使用的相机
///
public Camera fxRenderCamera;
private Queue pool = new Queue(20);
private List activatedFXList = new List();
private void Awake()
{
if (fxSample == null)
{
Debug.LogErrorFormat("没有找到屏幕特效");
this.enabled = false;
}
else
{
fxSample.SetActive(false);
}
}
private void Update()
{
for (int i = activatedFXList.Count - 1; i >= 0; --i)
{
GameObject fx = activatedFXList[i];
float fxTime = float.Parse(fx.name);
if (Time.time - fxTime > fxLifeTime)
{
RecycleFX(fx);
activatedFXList.RemoveAt(i);
}
}
if (Application.isMobilePlatform)
{
for (int i = 0; i < Input.touchCount; ++i)
{
Touch touch = Input.GetTouch(i);
if (touch.phase == TouchPhase.Began)
{
PlayFX(touch.position);
}
}
}
else
{
if (Input.GetMouseButtonDown(0))
{
PlayFX(Input.mousePosition);
}
}
}
private void PlayFX(Vector2 tapPos)
{
GameObject fx = CreateFX();
fx.name = Time.time.ToString();
activatedFXList.Add(fx);
RectTransform fxRectTrans = fx.GetComponent();
Vector2 fxLocalPos;
RectTransformUtility.ScreenPointToLocalPointInRectangle(fxContainer, tapPos, fxRenderCamera, out fxLocalPos);
fxRectTrans.SetParent(fxContainer);
fxRectTrans.anchoredPosition3D = fxLocalPos;
fx.SetActive(true);
}
private GameObject CreateFX()
{
GameObject newFX = null;
if (pool.Count > 0)
{
newFX = pool.Dequeue();
}
else
{
newFX = Instantiate(fxSample);
}
return newFX;
}
private void RecycleFX(GameObject fx)
{
fx.SetActive(false);
pool.Enqueue(fx);
}
//简单,无法显示在最上层
// Vector3 point;
// GameObject effectGo;
// void Start()
// {
// effectGo = Resources.Load("Prefabs/EffectClick");
// }
// void Update()
// {
// if (Input.GetMouseButtonDown(0))
// {
// point = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 4f);//获得鼠标点击点
// point = Camera.main.ScreenToWorldPoint(point);//从屏幕空间转换到世界空间
// GameObject go = Instantiate(effectGo);//生成特效
// go.transform.position = point;
// Destroy(go, 0.5f);
// }
// }
}