1
var GameLayer = cc.Layer.extend({
    ball:[],
    number:[],
    label:[],
    numberofballs:8,
    _order:0,
    ctor:function () {
        this._super();
        this.init();
    },
    init:function(){
        this._order=0;
        cc.log(this._order);
        this.setBall();
    },
    setCoordX:function(){
        var coordX=Math.random()*1000%330+50;
        cc.log(coordX);
        return coordX;
    },
    setCoordY:function(){
        var coordY = Math.random()*700%700+50;
        cc.log(coordY);
        return coordY;
    },
    onTouchBegan:function(touch, event){
        var target = event.getCurrentTarget();
        var PosInScreen = target.convertToNodeSpace(touch.getLocation());
        var Size = target.getContentSize();
        var rect = cc.rect(0, 0, Size.width, Size.height);

        if(cc.rectContainsPoint(rect, PosInScreen)){

            if(target.getTag()==this._order) {
                target.removeFromParent();
                this._order++;
            }

        }
        return false;
    },
    setBall:function(){
        for(var i=0;i<this.numberofballs;i++){
            this.number.push(Math.round(Math.random()*100));
        }
        this.number.sort(function(left,right){
            return left-right;
        });
        for(var i=0;i<this.numberofballs;i++){
            var eventListener = cc.EventListener.create({
                event: cc.EventListener.TOUCH_ONE_BY_ONE,
                swallowTouches: true,
                onTouchBegan: this.onTouchBegan});


            this.ball[i]=cc.Sprite.create(res.ball_png);
            this.ball[i].x=this.setCoordX();
            this.ball[i].y=this.setCoordY();
            this.ball[i].setTag(i);
            this.addChild(this.ball[i]);

            var label=new cc.LabelTTF(this.number[i],"Ariel",25);
            label.x=50;
            label.y=55;
            this.ball[i].addChild(label);
            cc.eventManager.addListener(eventListener, this.ball[i]);

        }

    }
});

var GameScene = cc.Scene.extend({
    onEnter:function () {
        this._super();
        var layer = new GameLayer();
        this.addChild(layer);
    }
});

这是我的全部代码。

首先,在 setBall 函数中,我添加了

 cc.eventManager.addListener(eventListener, this.ball[i]);

我想直接用 this.ball 数组进行触摸事件。

其次,在 onTouchBegan 函数中,this._order 为空。我不知道为什么。

我该如何解决?

4

1 回答 1

2

this._order未定义,因为在onTouchBegan函数中,cc.EventListener类的实例。

如果你想让它成为GameLayer的实例,你可以绑定它:

var eventListener = cc.EventListener.create({
    event: cc.EventListener.TOUCH_ONE_BY_ONE,
    swallowTouches: true,
    onTouchBegan: this.onTouchBegan.bind(this)});
于 2014-10-27T11:08:34.100 回答