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) } 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(()=>{ let isHit = this.knifeList.some(knife=>{ let gap = 5 let angle = Math.abs(knife.angle) return angle < gap || (360 - angle) < gap }) 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{ 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) }) } }
|