chenxin
2020-11-27 841b66ef416a727a0c798ad2263b098247cb4aa7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class ClickEffect : MonoBehaviour
{
    /// <summary>
    /// 屏幕特效原始资源
    /// </summary>
    public GameObject fxSample;
 
    /// <summary>
    /// 屏幕特效的生命时长,超过后会进行缓存
    /// </summary>
    public float fxLifeTime = 1.0f;
 
    /// <summary>
    /// 屏幕特效的容器(父对象)
    /// </summary>
    public RectTransform fxContainer;
 
    /// <summary>
    /// 屏幕特效渲染使用的相机
    /// </summary>
    private Camera fxRenderCamera;
 
    private Queue<RecycleEffectc> pool = new Queue<RecycleEffectc>(20);
 
    private void Awake()
    {
        if (fxSample == null)
        {
            Debug.LogErrorFormat("没有找到屏幕特效");
            this.enabled = false;
        }
        else
        {
            fxSample.SetActive(false);
        }
 
        fxRenderCamera = GameObject.Find("UICamera").GetComponent<Camera>();
    }
 
    private void Update()
    {
        if (Application.isMobilePlatform)
        {
            Touch touch = Input.GetTouch(0);
            if (touch.phase == TouchPhase.Began)
            {
                PlayFX(touch.position);
            }
            // for (int i = 0; i < Input.touchCount; ++i)
            // {
 
            // }
        }
        else
        {
            if (Input.GetMouseButtonDown(0))
            {
                PlayFX(Input.mousePosition);
            }
        }
    }
 
 
    private void PlayFX(Vector2 tapPos)
    {
        if (Time.timeScale < 0.0001f) return;
        
        RecycleEffectc fx = CreateFX();
 
        RectTransform fxRectTrans = fx.gameObject.GetComponent<RectTransform>();
        Vector2 fxLocalPos;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(fxContainer, tapPos, fxRenderCamera, out fxLocalPos);
        fxRectTrans.SetParent(fxContainer);
        fxRectTrans.anchoredPosition3D = fxLocalPos;
        //fxRectTrans.localScale = Vector3.one;
        fx.gameObject.SetActive(true);
        fx.StartPlay(fxLifeTime, RecycleFX);
    }
 
 
    private RecycleEffectc CreateFX()
    {
        RecycleEffectc newFX = null;
        if (pool.Count > 0)
        {
            newFX = pool.Dequeue();
        }
        else
        {
            GameObject go = Instantiate(fxSample);
            newFX = go.AddComponent<RecycleEffectc>();
        }
        return newFX;
    }
 
    private void RecycleFX(RecycleEffectc fx)
    {
        fx.gameObject.SetActive(false);
        pool.Enqueue(fx);
    }
 
}