本节课的内容是点击英雄然后在场景中添加一个label,使其分数每次加10。通过这次的作
.业又将之前的label相关的知识又进行了回顾。和单点触摸知识的回顾,分数累加的代码应该在ontouchbegan这个函数中进行,因为每点击一下就要加10。后来查阅相关API运用到了label.setString这个函数。刚开始的label是个静止的”0”。那么想让它进行累加,就要把它单拿出来,然后将分数赋给它就完成了分数的累加。核心代码如下:
var fenshu = 0;
var HelloWorldLayer = cc.Layer.extend({
sprite:null,
ctor:function () {
this._super();
cc.log("构造");
var npc=new cc.Sprite(res.npc01_png);
npc.setPosition(200,200);
npc.setTag(110);
this.addChild(npc);
var label = new cc.LabelTTF("0","黑体","50");
label.setPosition(200,300);
label.setTag(100);
this.addChild(label);
return true;
},
onEnter:function()
{
this._super();
cc.log("初始化完成");
//添加触屏事件
cc.eventManager.addListener({
event:cc.EventListener.TOUCH_ONE_BY_ONE,
swallowTouches:true,//吞噬事件 不再传递
onTouchBegan:this.touchbegan,
onTouchMoved:this.touchmoved,
onTouchEnded:this.touchended
},this);
},
onExit:function()
{
this._super();
cc.log("即将消失");
},
touchbegan:function(touch,event){
cc.log("按下");
var nownpc=event.getCurrentTarget().getChildByTag(110);
fenshu = fenshu + 10;
var act=cc.sequence(
cc.scaleBy(0.1,0.9),
cc.scaleBy(0.1,1.1),
cc.scaleBy(0.05,1));
var fenshuxiangjia=event.getCurrentTarget().getChildByTag(100);
fenshuxiangjia.setString(fenshu.toString());
nownpc.runAction(act);
return true;
},
touchmoved:function(touch,event)
{
var nownpc=event.getCurrentTarget().getChildByTag(110);
nownpc.setPosition(touch.getLocation().x,touch.getLocation().y);
cc.log("移动");
},
touchend:function(touch,event)
{
cc.log("抬起");
}
});
var HelloWorldScene = cc.Scene.extend({
onEnter:function () {
this._super();
var layer = new HelloWorldLayer();
this.addChild(layer);
}
});
最后附上作业链接:
http://www.cocoscvp.com/usercode/2016_04_17/9d3403b9a5fe1c839015006d9e771260d4b88fb2/
原文链接:https://www.f2er.com/cocos2dx/339521.html