cocos creator从零开发简单转盘
使用cocos creator从零开发简单转盘,先看效果。因为是mp4转换成gif的,所以动图很糊。

开发环境
- Cocos Creator 2.4.8,安装参考 cocos creator安装
- TypeScript
创建项目

资源导入
新建textures目录并把资源导入。

场景设置
新建scripts目录并在其下新建Game脚本。


新建scenes目录并在其下新建game场景。

双击game场景打开场景,Canvas节点宽高设置成750x1334并适配宽度,再把Game脚本挂载上去。

转盘布局
拖动textures/外圈到Canvas节点下,拖动textures/内圆到Canvas节点下并把Y属性设置成5,拖动textures/指针到Canvas节点下并把Y属性设置成5,拖动textures/开始按钮到Canvas节点下并把Y属性设置成-400再挂载一个Button组件。





奖项布局
简单起见,这里直接顺时针布局1-8数字。
内圆节点创建空节点并重命名为item,item节点下新建Label组件重命名为text并把Y属性设置成240。



代码生成奖项
编辑scripts/Game脚本,内容如下。
const { ccclass } = cc._decorator
@ccclass
export default class Game extends cc.Component {
private circleNode: cc.Node = null
private itemNum: number = 8 //转盘分成了多少份
protected onLoad(): void {
this.init()
}
private init() {
this.circleNode = this.node.getChildByName('内圆')
const btnStart = this.node.getChildByName('开始按钮')
btnStart.on('click', this.onBtnStart, this)
this.initItem()
}
private initItem() {
const stepAngle = 360 / this.itemNum
const itemPrefab = this.circleNode.children[0]
itemPrefab.active = false
// 顺时针生成奖项
for (let i = 0; i < this.itemNum; i++) {
const item = cc.instantiate(itemPrefab)
item.parent = this.circleNode
item.active = true
item.angle = -(i * stepAngle)
const text = item.getChildByName('text')
text.getComponent(cc.Label).string = (i + 1).toString()
text.color = cc.Color.RED
}
itemPrefab.destroy()
}
private onBtnStart() {
cc.log('点击了开始按钮')
}
}
运行程序后,发现奖项都生成好了,点击开始按钮也输出了日志。


实现转盘效果
编辑scripts/Game脚本,修改onBtnStart方法。
private _isClick = false
private onBtnStart() {
if (this._isClick) return
this._isClick = true
const idx = this.randRange(0, this.itemNum - 1) //随机奖项
const degree = -360 + (idx * 45) //奖项到指针位置转盘需要设置的角度
cc.log(`随机奖项:${idx + 1}`)
// 6 秒转 8 圈
cc.tween(this.circleNode).to(6, { angle: -8 * 360 + degree }, cc.easeSineInOut()).call(() => {
this._isClick = false
// 转完后调整转盘的角度在 360 度以内
this.circleNode.angle = this.circleNode.angle % 360
}).start()
}
// 整数范围随机 [min, max]
private randRange(min: number, max: number): number {
return Math.round(Math.random() * (max - min) + min)
}
再次运行程序并点击开始按钮,运行效果已经跟前面的效果一模一样了。
资源和代码获取
关注干货悦读公众号,点击源码菜单获取下载链接。
本作品采用《CC 协议》,转载必须注明作者和本文链接
关于 LearnKu
缺个cocos的专栏