先看一下做出来的效果图![在这里插入图片描述]
1.首先需要做一个小球围绕中心点做一个圆周运动
如图通过公式可以得出x和y的值,然后通过下面的方法实现小球的圆周运动
onLoad() {
this.zhuanpan.speed = 0.5; //转盘旋转速度
this.ball.speed = 2.5; //小球速度
this.circleCenter = new cc.Vec2(0, 0); //中心点位置坐标
this.circleRadius = 250; //半径
this.radian = 0; //弧度
this.schedule(this.circleMove, 0.01); //开始执行下面的方法,小球就会做圆周运动
}
//在update中让转盘自转
update(dt) {
this.zhuanpan.rotation += this.zhuanpan.speed;
},
circleMove(dt) {
// 先计算弧度
this.radian += dt * (this.ball.speed);
let x = this.circleRadius * Math.cos(this.radian) + this.circleCenter.x;
let y = this.circleRadius * Math.sin(this.radian) + this.circleCenter.y;
let angle = 360 - 180 / Math.PI * this.radian;
//this.ball.rotation = angle;
this.ball.position = cc.v2(x, y);
},
2.然后让小球做向心运动,即减小小球的半径
调用下面这个方法小球就开始做向心运动了
startBallRotate(dt) {
this.circleRadius -= 15 * dt;
let ballPos = this.nodeConvertToNodeSpaceAR(this.ball, this.zhuanpan);
this.result = 5; // 这个是最后小球到达的数字位置,这个数字写成参数,就可以控制每一轮的结果了。就可以实现手动操控结果了...
let str = ""+ this.result;
let dist = ballPos.sub(this.zhuanpan.getChildByName(str).position).mag();
if (this.circleRadius < 180 && dist < 50) {
if (this.isrotate) {
let ballPos1 = this.nodeConvertToNodeSpaceAR(this.ball, this.zhuanpan.getChildByName(str));
this.ball.setPosition(ballPos1);
}
this.ball.parent = this.zhuanpan.getChildByName(str);
this.isrotate = false;
}
if (!this.isrotate) {
this.startJumpAni(dt);
//this.moveToPos();
}
},换坐标,使两个物体处于相同坐标系
nodeConvertToNodeSpaceAR(node, target) {
var worldPos = node.convertToWorldSpaceAR(cc.p(0, 0));
var pos = target.convertToNodeSpaceAR(worldPos);
return pos;
}
3.最后是小球要到达的位置
如图,我在每个数字的位置分别创建了一些点数,让其随着转盘一起运动,让小球的位置到达这些点数的位置就可以实现了
为了让效果更加真实,我写了一系列动画模拟碰撞效果。(这里的假动画有点粗糙,有需要的话可以写的详细一点,逼真一点)
startJumpAni(dt) {
if (this.isadd) {
this.ball.x += dt * 100;
this.ball.y += dt * 50;
console.log("ball---y",this.ball.y);
if (this.ball.y > -20) {
this.ball.x -= dt * 300;
this.ball.y -= dt * 100;
this.moveToPos();
this.isadd = false;
}
}
},
moveToPos() {
let moveCenterUp = cc.moveTo(0.2,cc.p(0,48));
let moveUp1 = cc.moveTo(0.2,cc.p(-30,44));
let moveUp2 = cc.moveTo(0.2,cc.p(30,44));
let moveLeft = cc.moveTo(0.2, cc.p(-24, 0));
let moveSmall1 = cc.moveTo(0.2,cc.p(-2,4));
let moveSmall2 = cc.moveTo(0.3,cc.p(3,7));
let moveRight = cc.moveTo(0.2, cc.p(24, 0));
let moveCenter = cc.moveTo(0.3, cc.p(0, 0));
let action = cc.sequence(moveCenterUp,moveLeft,moveUp1,moveRight,moveUp2,moveSmall1,moveSmall2,moveCenter);
this.ball.runAction(action);
this.ball.position.sub(this.zhuanpan.getChildByName("number").getChildByName("0").position).mag();
},