Unity使用DOTween實現金幣飛入效果

Jet清远發表於2024-10-09
 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動畫外掛。

相關文章