原文链接: cocos 简单时钟
上一篇: cocos 粒子同心圆 跟随鼠标
下一篇: cocos 扇形进度条
效果, 每次走的是一个单位, 所以只有在秒针真正转完一圈时, 分针才会走一格
基本思想
秒针: 1秒6度, 60秒转360度
分针: 1秒十分之一度, 60秒转6度, 3600秒转360度
时针: 1秒一百二十分之一度, 3600秒转30度, 12个小时转一圈
每次走一格的思想是设置一个世界时间, 每次增加一秒, 然后只有在秒针走完一圈时才进行进位处理
const { ccclass, property } = cc._decorator;
const MAX_DEGREE = 24 * 60 * 60 * 360;
@ccclass
export default class NewClass extends cc.Component {
@property(cc.Label)
label: cc.Label = null;
@property(cc.Node)
hNode: cc.Node = null;
@property(cc.Node)
mNode: cc.Node = null;
@property(cc.Node)
sNode: cc.Node = null;
@property
text: string = "hello";
// 时间
h = 0;
m = 0;
s = 0;
time = 0;
// 每隔多少时间, 秒针走一格
speed = 1000;
@property(cc.Button)
incBtn: cc.Button = null;
@property(cc.Button)
decBtn: cc.Button = null;
handler = null;
onLoad() {
this.incBtn.node.on(cc.Node.EventType.MOUSE_DOWN, () => {
this.speed *= 2;
});
this.decBtn.node.on(cc.Node.EventType.MOUSE_DOWN, () => {
this.speed /= 2;
});
console.error(this.hNode);
}
setTime(t) {
this.time = t % MAX_DEGREE ;
// 秒针的位置
this.s = this.time % 360;
// 分针角度
this.m = ((this.time - this.s) / 60) % 360;
// 时针角度
this.h = ((this.time - this.s - this.m * 60) / 3600) % 360;
this.sNode.rotation = this.s;
this.mNode.rotation = this.m;
this.hNode.rotation = this.h;
const s = [(this.h / 6) | 0, (this.m / 6) | 0, (this.s / 6) | 0].join(":");
this.label.string = s;
}
update(dt) {
const dx = (dt * this.speed) | 0;
this.time += dx;
this.setTime(this.time);
}
}
连续移动
const { ccclass, property } = cc._decorator;
const MAX_DEGREE = 24 * 60 * 60;
@ccclass
export default class NewClass extends cc.Component {
@property(cc.Label)
label: cc.Label = null;
@property(cc.Node)
hNode: cc.Node = null;
@property(cc.Node)
mNode: cc.Node = null;
@property(cc.Node)
sNode: cc.Node = null;
@property
text: string = "hello";
// 时间
h = 0;
m = 0;
s = 0;
// 一天24小时的秒数
time = 0;
// 每隔多少时间, 秒针走一格
speed = 1;
@property(cc.Button)
incBtn: cc.Button = null;
@property(cc.Button)
decBtn: cc.Button = null;
handler = null;
onLoad() {
this.incBtn.node.on(cc.Node.EventType.MOUSE_DOWN, () => {
this.speed = this.speed * 2;
});
this.decBtn.node.on(cc.Node.EventType.MOUSE_DOWN, () => {
this.speed = (this.speed / 2) | 0;
});
console.error(this.hNode);
setInterval(() => {
this.time += this.speed;
console.log("===", this.time);
this.setTime(this.time);
}, 100);
}
setTime(t) {
this.time = t % MAX_DEGREE;
// 秒针的位置
this.s = this.time % 360;
// 分针角度
this.m = this.time / 10;
while (this.m >= 360) this.m -= 360;
// 时针角度
this.h = this.time / 120;
while (this.h >= 360) this.h -= 360;
this.sNode.angle = -this.s;
this.mNode.angle = -this.m;
this.hNode.angle = -this.h;
const h = ((this.time / 3600) | 0) % 24;
const m = ((this.time / 60) | 0) % 60;
const s = (this.time | 0) % 60;
const str = [h, m, s].join(":");
this.label.string = str;
}
}