文章目录
- 一、前言
- 二、下载DoTween插件
- 三、Setup DOTween
- 四、使用DOTween函数
- 五、运行测试
一、前言
嗨,大家好,我是新发。下班坐地铁的时候,好几次看到其他人在玩消消乐,既然大家都这么喜欢玩,那我就写个Unity
制作水果消消乐的教程吧。
游戏运行效果如下:
最终的Demo
工程已上传到GitHub
,感兴趣的同学可以自行下载下来学习。
GitHub
地址:https://github.com/linxinfa/UnityXiaoXiaoLeDemo 注:我使用的Unity
版本为2020.1.14f1c1
。
本篇讲使用DOTween
插件实现水果的滑动效果,本篇的效果:
二、下载DoTween插件
DOTween
官网下载地址:http://dotween.demigiant.com/download.php
点击Download
下载,下载下来后是一个zip
压缩包,将其放到工程的Assets
文件夹中。
三、Setup DOTween
解压后,回到Unity
编辑器中,会看到下面这个弹框,点击Open DOTween Utility Panel
。
点击Setup DOTween
。
点击Apply
,然后关闭窗口。
四、使用DOTween函数
我们之前写的设置水果的坐标函数是这样的。
// FruitItem.cs
/// <summary>
/// 设置坐标
/// </summary>
public void UpdatePosition(int rowIndex, int columIndex)
{
this.rowIndex = rowIndex;
this.columIndex = columIndex;
var targetPos = new Vector3((columIndex - GlobalDef.COLUM_COUNT / 2f) * GlobalDef.CELL_SIZE + GlobalDef.CELL_SIZE / 2f, (rowIndex - GlobalDef.ROW_COUNT / 2f) * GlobalDef.CELL_SIZE + GlobalDef.CELL_SIZE / 2f, 0);
m_selfTransform.localPosition = targetPos;
}
现在我们可以使用DOTween
插件的函数来实现差值移动,实现一个滑动的效果了。
首先引入命名空间。
using DG.Tweening;
修改UpdatePosition
函数为如下:
// FruitItem.cs
/// <summary>
/// 设置坐标
/// </summary>
public void UpdatePosition(int rowIndex, int columIndex, bool dotween = false)
{
this.rowIndex = rowIndex;
this.columIndex = columIndex;
var targetPos = new Vector3((columIndex - GlobalDef.COLUM_COUNT / 2f) * GlobalDef.CELL_SIZE + GlobalDef.CELL_SIZE / 2f, (rowIndex - GlobalDef.ROW_COUNT / 2f) * GlobalDef.CELL_SIZE + GlobalDef.CELL_SIZE / 2f, 0);
if(dotween)
{
// 0.3秒移动到目标点
m_selfTransform.DOLocalMove(targetPos, 0.3f);
}
else
{
m_selfTransform.localPosition = targetPos;
}
}
接着,交换水果的时候,调用UpdatePosition
时,第三个参数dotween
传true
。
// FruitSpawner.cs
/// <summary>
/// 交换水果
/// </summary>
private void Exchange(FruitItem item1, FruitItem item2)
{
SetFruitItem(item1.rowIndex, item1.columIndex, item2);
SetFruitItem(item2.rowIndex, item2.columIndex, item1);
int tmp = 0;
tmp = item1.rowIndex;
item1.rowIndex = item2.rowIndex;
item2.rowIndex = tmp;
tmp = item1.columIndex;
item1.columIndex = item2.columIndex;
item2.columIndex = tmp;
item1.UpdatePosition(item1.rowIndex, item1.columIndex, true);
item2.UpdatePosition(item2.rowIndex, item2.columIndex, true);
m_curSelectFruit = null;
}
五、运行测试
运行Unity
,测试效果如下:
下一篇讲水果的消除检测,实现消除效果。