這一節 我將實現讓小怪物跟隨我的觸摸方向移動,同時觸摸的地方產生一個四周發散的效果
效果如下:
代碼下載:http://www.kuaipan.cn/file/id_25348935635744782.htm?source=1
打開MainLayer.js,把onDidLoadFromCCB函數修改如下,讓觸摸可用;
MainLayer.prototype.onDidLoadFromCCB = function () {
if (sys.platform == 'browser') {
this.onEnter();
}
else {
this.rootNode.onEnter = function () {
this.controller.onEnter();
};
}
this.rootNode.schedule(function (dt) {
this.controller.onUpdate(dt);
});
this.rootNode.onExit = function () {
this.controller.onExit();
};
this.rootNode.onTouchesBegan = function (touches, event) {
this.controller.onTouchesBegan(touches, event);
return true;
};
this.rootNode.onTouchesMoved = function (touches, event) {
this.controller.onTouchesMoved(touches, event);
return true;
};
this.rootNode.onTouchesEnded = function (touches, event) {
this.controller.onTouchesEnded(touches, event);
return true;
};
this.rootNode.setTouchEnabled(true);
};
在文件底部加入 觸摸開始,觸摸移動,觸摸結束函數;
MainLayer.prototype.onTouchesBegan = function (touches, event) {
var loc = touches[0].getLocation();
}
MainLayer.prototype.onTouchesMoved = function (touches, event) {
cc.log("onTouchesMoved");
}
MainLayer.prototype.onTouchesEnded = function (touches, event) {
cc.log("onTouchesEnded");
}
MainLayer.prototype.monsterMove = function (x, y) {
this.monster.stopAllActions();
cc.AnimationCache.getInstance().addAnimations("Resources/snow_frame.plist");//添加幀動畫文件
var action0 = cc.Sequence.create(cc.MoveTo.create(5, cc.p(x, y))); //向前移動
var actionFrame = cc.Animate.create(cc.AnimationCache.getInstance().getAnimation("monster")); //獲取幀動畫
var action1 = cc.Repeat.create(actionFrame, 90000);
var action2 = cc.Spawn.create(action0, action1); //同步動畫
this.monster.runAction(action2);
}
觸摸結束時,加入monsterMove函數,這時觸摸一個點,小怪物會立刻移動到該位置;
MainLayer.prototype.onTouchesEnded = function (touches, event) {
cc.log("onTouchesEnded");
var loc = touches[0].getLocation();
this.monsterMove(loc.x, loc.y);
}
按照之前博客教過的在particles目錄下創建一個發散粒子,現在在觸摸的地方加入發散效果,效果週期爲3秒,3秒後消失;
再次打開MainLayer.js,加入創建粒子的函數
MainLayer.prototype.createParticle = function (name, x, y) {
var particle = cc.ParticleSystem.create("Resources/particles/" + name + ".plist");
particle.setAnchorPoint(cc.p(0.5, 0.5));
particle.setPosition(cc.p(x, y));
particle.setPositionType(1);
particle.setDuration(3);
this.rootNode.addChild(particle);
}
同時在觸摸結束時加入粒子函數;
MainLayer.prototype.onTouchesEnded = function (touches, event) {
cc.log("onTouchesEnded");
var loc = touches[0].getLocation();
this.monsterMove(loc.x, loc.y);
this.createParticle("around", loc.x, loc.y);
}
點擊運行;一切OK;
下一篇文章 我會介紹cocos2d-x editor的音樂和音效 筆者(李元友)
資料來源:cocos2d-x editor