使用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)
}
再次运行程序并点击开始
按钮,运行效果已经跟前面的效果一模一样了。
资源和代码获取
关注干货悦读
公众号,点击源码
菜单获取下载链接。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。