Search code examples
cocos2d-xspritecocos2d-js

cocos2d trying to keep sprites within the screen


So I have theses sprites that move left to right diagonally going upwards. The problem is that they will go upwards infinitely, and moving out of the screen. I want them to move inside a certain boundary.

I tried using clamp but it won't work. I'm fairly new to cocos2d-js so I don't have many ideas. if anybody could help I'll appreciate it.

for(var i=0;i<minions.length;i++){

        var x = Math.floor((Math.random() * size.width));
        var y = Math.floor((Math.random() * size.height / 10) + size.height / 50);

        var ms = Math.floor((Math.random() + 1));
        var mas = (size.width - x) / size.width * ms
        var m2s = x / size.width * ms;


        var move = cc.MoveBy.create(mas, cc.p(size.width - x, y));
        var moveaway = cc.MoveBy.create(ms, cc.p(-size.width, -y));
        var move2 = cc.MoveBy.create(m2s, cc.p(x, y));

        var minSeq = cc.Sequence.create(move, moveaway, move2);

        minions[i].runAction(minSeq).repeatForever();

        minions[i].setPosition(cc.p(cc.clampf(minions[i].x,0,size.width),cc.clampf(minions[i].y,0,400)));
        this.addChild(minions[i]);
    }

before this I tired an if loop like

if(minions[i].position == 0){//move upwards}

when I was having problems with the sprites going downwards continuously. it would only work the very first time when the sprites appear below the screen, but after that, it wouldn't have any impact on the sprites


Solution

  • Let's define the boundaries in screen coordinates first

    var xMin = 0, yMin = 0, xMax = 320, yMax = 240;
    

    Also let's assume there's a global variable which holds array of your minions.

    var minions = [];
    

    I'm pretty sure you've scheduled update already, using scheduleUpdate() so now you can do this check in the update function

    update: function(dt){
       //your code
       minions.forEach(function(minion){
          var p = minion.getPosition();
          if (p.x > pMax) {
             //change minion speed to go down
          } 
          if (p.x < pMin){
            //change minion speed to go up
          }
          // same for y-axis
       });
    }