Search code examples
javascriptgame-physicsphaser-framework

P2 physics body not colliding after setRectangle() called phaserJS


I am creating a fish sprite. Colliding it with foodCollisionGroup. Fish eats some food. Game play works fine. After that i resize it (increase the fish size) and it stops colliding with food. I think it might be not colliding with food because of setRectangle called. i have another problem that the fishFoodCount is incremented twice. how to solve these two problems

Fish.prototype.create = function(x, y){
    this.fish = game.add.sprite(x, y, this.spriteName);
    this.fish.physicsBodyType = Phaser.Physics.P2JS;
    game.physics.p2.enable(this.fish);
    this.fish.enableBody = true;
    this.fish.anchor.setTo(0.5,0.5);
    this.fish.body.collideWorldBounds = true;
    this.fish.animations.add('idle', [3 + (this.index * 8)], 10, false);
    this.fish.animations.add('move', this.getAnimationFramesArrayFor(this.index) , this.AnimationFrameRate, true);  
    this.fish.play('idle');
    this.fish.body.fixedRotation = true;
}

-------

Fish.prototype.setFishSize = function(width, height){
    this.fish.width = width;
    this.fish.height = height;
    this.fish.body.setRectangle(height/2, width/1.8, width/3.3, 0);
}

-------

Fish.prototype.eatFood = function(fish, food) {

    if(this.fishFoodCount > 9){
        this.setFishSize(game.width/25, game.height/4);
    }
    this.fishFoodCount += 1;
        food.sprite.kill();

}

Solution

  • You need to apply collision groups again after using setRectangle().