📖规则说明

规则说明

找到时机向木桩投出飞刀,注意:不能插在已经击中的位置

💻代码实现

实现代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100

@ccclass
export default class Game extends cc.Component {
// 木桩(投掷目标)节点
@property(cc.Node)
targetNode:cc.Node = null
// 小刀(投掷物示意)节点
@property(cc.Node)
knifeNode:cc.Node = null
//小刀预制件
@property(cc.Prefab)
knifePrefab:cc.Prefab = null
// 已投出的小刀列表
knifeList:cc.Node[] = []
// 当前是否可以投掷
canThrow:boolean = true
// 旋转速度
rotateSpeed:number = 150
// 旋转半径(木桩半径)
rotateRadius:number = 0
onLoad () {
// 点击屏幕,触发丢出飞刀事件
this.node.on(cc.Node.EventType.TOUCH_START, this.throwKnife, this)
this.rotateRadius = this.targetNode.width / 2
}
onDestroy(): void {
// 销毁飞刀事件
this.node.off(cc.Node.EventType.TOUCH_START, this.throwKnife, this)
}
// 每隔2s进行变速
changeSpeed(){
let dir = Math.random() > 0.5? 1: -1
let speedNum = Math.max(200, Math.abs(this.rotateSpeed) + 150 * (Math.random() - 0.5))
if(speedNum > 200){
speedNum -= Math.random() * 150
}
this.rotateSpeed = dir * speedNum
}

// 丢出飞刀
throwKnife(){
if(this.canThrow) {
this.canThrow = false
this.targetNode.zIndex = 1
let action = cc.sequence(
// 垂直飞到木桩的圆周上
cc.moveTo(0.15, new cc.Vec2(this.knifeNode.x, this.targetNode.y - this.targetNode.height / 2)),
cc.callFunc(()=>{
// 判定是否和已经插在上面的飞刀碰撞:遍历knifeList,判断是否有旋转角小于gap的小刀
let isHit = this.knifeList.some(knife=>{
let gap = 5
let angle = Math.abs(knife.angle)
return angle < gap || (360 - angle) < gap
})
// 当检查到小刀旋转的角度小于5时,判定撞击
if(isHit){
// 弹回
let action = cc.sequence(
cc.spawn(
cc.moveTo(0.5, this.knifeNode.x, -cc.winSize.height),
cc.rotateBy(0.5, -360)
),
cc.callFunc(()=>{
// 游戏重新开始
cc.director.loadScene('game')
})
)
this.knifeNode.runAction(action)
}else{
// 没有碰撞,创建一把新的小刀,代替knifeNode插在上面,knifeNode复位
this.canThrow = true
let newKnife = cc.instantiate(this.knifePrefab)
newKnife.setPosition(this.knifeNode.position)
this.node.addChild(newKnife)
this.knifeList.push(newKnife)
this.knifeNode.setPosition(new cc.Vec2(0, -300))
}
})
)
this.knifeNode.runAction(action)
}
}
start () {
// 定时变速
setInterval(()=>this.changeSpeed(), 2000)
}
update (dt) {
// 木桩旋转
this.targetNode.angle = (this.targetNode.angle + this.rotateSpeed * dt) % 360
//小刀和木桩旋转一致,要计算相对木桩圆心的位移位置
this.knifeList.forEach((knife:cc.Node)=>{
knife.angle = (knife.angle + this.rotateSpeed * dt) % 360
let rad = Math.PI * (knife.angle - 90) / 180
knife.x = this.targetNode.x + this.rotateRadius * Math.cos(rad)
knife.y = this.targetNode.y + this.rotateRadius * Math.sin(rad)

})
}
}