前言:
这一节主要讲解矩形碰撞,在碰撞要求不是很严格的时候,简单的矩形碰撞可以帮助我们;
游戏规则很简单,雪球一直射击中,小怪物躲避就行;
效果图
代码下载
https://github.com/makeapp/cocoseditor-samples (snow-collision)
代码分析
1 更新函数里面,隔二秒产生一个新的雪球以及雪球函数newSnowBall();
MainLayer.prototype.onUpdate = function (dt) { this.currentTime += dt; if (this.currentTime - this.lastSnowBall > 2) { this.newSnowBall(); this.lastSnowBall = this.currentTime; }
MainLayer.prototype.newSnowBall = function () { var snowBall = cc.Sprite.createWithSpriteFrameName("m_snowball_roll_2.png"); snowBall.setPosition(cc.p(360, 200)); snowBall.setZOrder(100); snowBall.setAnchorPoint(cc.p(0.5, 0.5)); snowBall.setTag(-100); snowBall.newTime = this.currentTime; snowBall.speedX = (this.monster.getPosition().x - snowBall.getPosition().x) / 8; snowBall.speedY = (this.monster.getPosition().y - snowBall.getPosition().y) / 8; this.rootNode.addChild(snowBall); }
下面有四种:可以把代码注释,分别查看四种不同的效果
1 碰撞一 普通,直接通过getBoundingBox函数获取精灵矩形,这种不是很精准
2 //碰撞二 通过rectCreate函数缩小矩形范围 达到更精准;
3 //碰撞三 扩大碰撞区域 200dp就发生了碰撞,这个在一些游戏需要把某个区域的怪物都杀死的时候可以应用,比如发射了炸弹,方圆500px都要消除
4 //碰撞四 两个精灵中心距离小于40时 这个是高中数学知识,两点距离
for (var i = 0; i < this.rootNode.getChildrenCount(); i++) { var child = this.rootNode.getChildren()[i]; if (child.getTag() == -100) { // cc.log("ball"); var monsterX = this.monster.getPosition().x; var monsterY = this.monster.getPosition().y; var childX = child.getPositionX(); var childY = child.getPositionY(); /*var followX = childX + (this.currentTime - child.newTime) * (monsterX - childX) / 5; var followY = childY + (this.currentTime - child.newTime) * (monsterY - childY) / 5;*/ var followX = childX + (this.currentTime - child.newTime) * child.speedX; var followY = childY + (this.currentTime - child.newTime) * child.speedY; child.setPosition(cc.p(followX, followY)); if (child && child.getPositionY() > 1500) { child.removeFromParent(true); continue; } //碰撞一 普通 /*if (cc.rectIntersectsRect(child.getBoundingBox(), this.monster.getBoundingBox())) { this.createParticle("around", monsterX, monsterY); cc.AudioEngine.getInstance().playEffect("res/sounds/bomb.mp3", false); child.removeFromParent(true); }*/ //碰撞二 缩小矩形范围 更精准; /*if (cc.rectIntersectsRect(cc.rectCreate(child.getPosition(), [10, 10]), cc.rectCreate(this.monster.getPosition(), [20, 20]))) { this.createParticle("around", monsterX, monsterY); cc.AudioEngine.getInstance().playEffect("res/sounds/bomb.mp3", false); child.removeFromParent(true); }*/ //碰撞三 扩大碰撞区域 200dp就发生了碰撞 /*if (cc.rectIntersectsRect(cc.rectCreate(child.getPosition(), [10, 10]), cc.rectCreate(this.monster.getPosition(), [200, 200]))) { this.createParticle("around", monsterX, monsterY); cc.AudioEngine.getInstance().playEffect("res/sounds/bomb.mp3", false); child.removeFromParent(true); }*/ //碰撞四 两个精灵中心距离小于40时 var distance = cc.pDistance(child.getPosition(), this.monster.getPosition()); if (distance < 40) { this.createParticle("around", monsterX, monsterY); cc.AudioEngine.getInstance().playEffect("res/sounds/bomb.mp3", false); child.removeFromParent(true); } } }
over