基于DOTween插件实现金币飞行到指定位置功能

 

 

前言

通过使用 DOTween 插件实现金币两段飞行效果,第一段在物体周围随机生成指定数量的金币,第二段将金币移动到指定位置。


一、DOTween是什么?

DoTween 是Unity的一款插件,主要用于控制物体的移动和变换。

二、使用步骤

1.导入DOTween插件

在Unity官方插件商店找到DOTween插件

https://assetstore.unity.com/packages/tools/animation/dotween-hotween-v2-27676
在这里插入图片描述

导入DOTween插件

在这里插入图片描述

启用DOTween插件

请添加图片描述

2.代码逻辑

金币飞行代码

public class FlyControl : MonoBehaviour {
private Vector3 endPos;
private Vector3 startPos;
private Vector3 vec1;
private Vector3 vec2;
[NonSerialized]public bool fly = true;
public GameObject coin;
//第一段位移 控制随机出现在父物体周围
public void FlyCoinOne() {
startPos = transform.position;
float randomX = Random.Range(-50, 50);
float randomY = Random.Range(-50, 50);
vec1 = startPos + new Vector3(randomX, randomY, 0);
coin.transform.DOMove(vec1, 0.3f).SetTarget(this);
}
//第二段位移 移动到指定位置
public void FlyCoinTwo(Transform targetPos) {
endPos = targetPos.position;
vec2 = endPos;
coin.transform.DOMove(vec2, 0.6f).SetTarget(this);
float timer1 = 0;
DOTween.To(() => timer1, x => timer1 = x, 1, 0.3f)
.OnStepComplete(() => { this.gameObject.GetComponent<Image>().DOFade(0, 0.3f).SetTarget(this); });
float timer = 0;
DOTween.To(() => timer, x => timer = x, 1, 0.61f)
.OnStepComplete(() => {
fly = false;
//Destroy(this.gameObject);
});
}
}

控制飞行效果代码

public class CoinEffect : MonoBehaviour{
[LabelText("金币预制体")] public GameObject prefab;
public Transform parent;
[LabelText("金币数量")] public int num;
[LabelText("最终目的地")] public Transform targetPos;
[LabelText("金币飞行速度")] public float time = 1;
private int childNum = 0;
public bool isEnd = false;
private List<FlyControl> ts = new List<FlyControl>();
public void StartEffect(){
for (int i = 0; i < num; i++){
GameObject go = Instantiate(prefab, parent, false);
go.transform.position = gameObject.transform.position;
FlyControl cc = go.GetComponent<FlyControl>();
if (cc != null){
cc.gameObject.SetActive(true);
ts.Add(cc);
childNum++;
}
ts[i].FlyCoinOne();
}
}
IEnumerator StartEffect1(){
yield return new WaitForSeconds(0.6f);
for (int i = 0; i <= ts.Count; i++){
this.DOKill();
yield return new WaitForSeconds(0.1f);
var rm = Random.Range(0, ts.Count);
yield return new WaitForSeconds(0.01f);
ts[rm].FlyCoinTwo(targetPos);
// ts.Remove(ts[rm]);
Debug.Log(rm);
i = 0;
}
MyLogger.PrintLog("飞行结束");
}
/// <summary>
/// 金币飞行效果,在Update里面调用
/// </summary>
public void CoinEffectShow(){
//第一次飞行
StartEffect();
//第二次飞行
StartCoroutine(StartEffect1());
}
private void Update(){
if (childNum == 0){
return;
}
foreach (var control in ts){
if (control.fly){
return;
}
}
isEnd = true;
if (Input.GetKeyDown(KeyCode.R)){
CoinEffectShow();
}
}
}

3.物体配置

1.物体上装配CoinEffect脚本

在这里插入图片描述

2.在金币预制体上装配FlyControl脚本

在这里插入图片描述

三、效果展示

请添加图片描述

 
posted @   星空探险家  阅读(209)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· [翻译] 为什么 Tracebit 用 C# 开发
· 腾讯ima接入deepseek-r1,借用别人脑子用用成真了~
· Deepseek官网太卡,教你白嫖阿里云的Deepseek-R1满血版
· DeepSeek崛起:程序员“饭碗”被抢,还是职业进化新起点?
· RFID实践——.NET IoT程序读取高频RFID卡/标签
点击右上角即可分享
微信分享提示