Jump to content

Collision Groups and Timers


Recommended Posts


I am working on my first Phaser project  and can't figure out how I should work this out well.  I am build a simple JS game where I have fruits dropping and a player collecting them, whenever I collect a fruit I need it to re-spawn at a random position, which I am achieving well, but then I tried adding a timer event to the fruit, which after 5 sec of the fruit that has spawned, the player will lose the fruit and add to the missed fruit counter. I am using the P2 Physics by the way, below are parts of my code attached.

    //setting up the fruits
    fruits = game.add.group();
    fruits.enableBody = true;
    fruits.physicsBodyType = Phaser.Physics.P2JS;
        //creating the fruit scale, position and anchor
        fruit = fruits.create(this.rnd.realInRange(50,800), this.rnd.realInRange( 50, 50), 'cherry');
        fruit.anchor.setTo(0.5, 0.5);
        fruit.body.data.gravityScale = 2;
        fruit.game.time.events.add(Phaser.Timer.SECOND * 5, fruitMissed, this.fruit);
        //set collision group

        // setting to which grps the fruit can collide
        fruit.body.collides([fruitCollisionGroup, playerCollisionGroup]);
        fruit.body.collides(rockCollisionGroup, fruitHitRock, this);


I am adding a time event to the fruit, which will call the fruitMissed function after 5 sec, which will de-spawn and collect the fruit, add score and will reset the position of the fruit, but whenever I reset the position I want to attach a timer again which I am unable to. Below is the fruitCollected function, where I need to respawn the fruit again. .


function fruitCollected (body1, body2) {
    console.log('Fruit Collected');

    body2.reset(this.rnd.realInRange(900, 50), 35);
    //increase the score
    score += 50;
    scoreText.text = 'Score: ' + score;

What are your thoughts on how I should tackle this.


Link to comment
Share on other sites


  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Create New...