Unity使用DOTween实现金币飞入效果

 1 public GameObject showRewardPanel;
 2 public Text SetCoinText;
 3 public Text SetLevelText;//经验exp
 4 private int getCoin;
 5 private int getExp;
 6 public Image coinImage;
 7 public Image targetImage;
 8 public Camera mainCamera;
 9 public TextMesh coinNumTextMesh;
10 public TextMesh coinNumShadeTextMesh;
11 
12 
13 
14 //根据获得的金币数,生成相应的预制体,展示动画效果
15 for (int i = 0; i < getCoin; i++)
16 {
17     Vector3 startPosition = coinImage.rectTransform.position + new Vector3(i * 50f, 0, 0);
18     Image newCoinImage = Instantiate(coinImage, coinImage.transform.parent);
19     newCoinImage.rectTransform.position = startPosition;
20     newCoinImage.rectTransform.localScale = coinImage.rectTransform.localScale;
21     Vector3 targetPosition = targetImage.transform.position;
22     Vector3 screenPosition = mainCamera.WorldToScreenPoint(targetPosition);
23     Vector3 scatterPosition = startPosition + new Vector3(0, UnityEngine.Random.Range(-200f, 200f), 0);
24 
25     newCoinImage.rectTransform.DOMove(scatterPosition, 0.6f)
26         .SetEase(Ease.OutQuad)
27         .OnComplete(() =>
28         {
29             newCoinImage.rectTransform.DOMove(screenPosition, 0.7f)
30                 .SetEase(Ease.InOutQuad)
31                 .OnComplete(() =>
32                 {
33                     coinNumTextMesh.text = UserSave.coins.ToString();
34                     coinNumShadeTextMesh.text = UserSave.coins.ToString();
35                 });
36         });
37 }

 这段代码种,coinImgae相当于金币的预制体(仅仅是相当于,因为它只是一个图片,2D游戏中也不只需要一个图片即可)。

代码的总体思路是,获取起始位置,即coinImage的位置,在这个位置生成更多的金币Imgae,再获取我们金币栏的位置,即终点位置,然后我们使用DOTween插件的DOMove函数进行移动,对于DOTween插件,这里不做详细的介绍,感兴趣的可以去了解一下,这是个很好用的2D动画插件。