这两天在学校里,由于项目遇到了不能独自解决的问题。偷偷摸了两天鱼,突然想起在暑假公司实习中用CocosCreator完成了一个laya引擎的demo工程,于是把这个过程记录一下。
效果:
上述为这个项目的完成的效果图,由于实习时这个demo给的时间不长(几小时左右),于是没有记录分数以及死亡,但游戏大体还是出来了,在我的demo中bullet与box的移动均在update完成(也可使用cc.tween完成)
game.js
cc.Class({ extends: cc.Component, properties: { box: { type: cc.Prefab, default: null, }, bullet: { type: cc.Prefab, default: null, } }, // LIFE-CYCLE CALLBACKS: onLoad() { this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this); cc.director.getPhysicsManager().enabled = true;//开启物理属性 setInterval(() => { this.createBox(); }, 500); // //对象池使用 //请使用对象池进行创建enmey // this.enemyPool = new cc.NodePool(); // let initCount = 5; // for (let i=0;i<initCount;i++){ // this.boxs = cc.instantiate(this.box); // this.enemyPool.put(this.boxs)//将对象放入对象池 // } }, createBox() {//请使用对象池进行创建 let viewWidth = cc.view.getCanvasSize().width;//宽度 this.box = cc.instantiate(this.box); this.node.addChild(this.box); let x = -viewWidth / 2 + Math.random() * viewWidth; if (x <= -viewWidth / 2 + this.box.width / 2) { x += this.box.width + 10; } else if (x >= viewWidth / 2 - this.box.width / 2) { x -= this.box.width + 10; } this.box.x = x, this.box.y = 500; }, onTouchStart(event) { let viewWidth = cc.view.getCanvasSize().width;//宽度 let viewHeight = cc.view.getCanvasSize().height;//高度 // cc.log(event.getLocationX()) let bullet = cc.instantiate(this.bullet) this.node.addChild(bullet) bullet.setPosition(event.getLocationX() - viewWidth / 2, event.getLocationY() - viewHeight / 2) }, start() { }, update(dt) { }, });box.js
cc.Class({ extends: cc.Component, properties: { }, // LIFE-CYCLE CALLBACKS: onLoad () { this.a=Math.floor(Math.random()*5)+1//随机数 this.hp = this.node.getChildByName('hp').getComponent(cc.Label); }, start () { }, onBeginContact(contact,selfCollider,otherCollider){ otherCollider.node.destroy(); // this.hp = selfCollider.node.getChildByName('hp').getComponent(cc.Label).string this.a-=1; cc.log(this.hp.string); }, update (dt) { this.hp.string = this.a; this.node.y-=8; if(this.node.y<-1000){ this.node.destroy(); cc.log('box销毁') } if(this.hp.string == 0){ this.node.destroy(); cc.log('hp==0') } }, });bullet.js
cc.Class({ extends: cc.Component, properties: { }, // LIFE-CYCLE CALLBACKS: // onLoad () {}, start () { }, update (dt) { this.node.y+=10; }, });给bullet和box添加刚体属性,将两个脚本分别挂载在两预制体上。然后打开碰撞监听器即可完成。
