Make physics sprite dynamic on collision?

How can I make something active on collision? For example, I have a cat in a tree. The cat should be fixed where it is initially until it is hit with a rock, at which point it should fall. I have my code so far below.

var timeHeld = 0;
var prjctle;
var cat;
var cat2;
var score = 0;
var catAmt = 2;
class Game extends Phaser.Scene{
  constructor(){
    //super() inherits all the characteristics of the Phaser "scene" class
    super("game"); //Identify the current class with "playGame"
  }

  create(){
    var gnd = this.physics.add.staticGroup();
    gnd.create(0, 376, 'gnd').setOrigin(0,0).setScale(8,8).refreshBody();
    cat = this.physics.add.staticImage(300,100,'cat').setOrigin(0,0).setScale(4,4).refreshBody();
    cat2 = this.physics.add.staticImage(360,180,'cat').setOrigin(0,0).setScale(4,4).refreshBody();
    var basket = this.physics.add.staticImage(310,354,'catBskt').setOrigin(0,0).setScale(6,6).refreshBody();
    prjctle = this.physics.add.sprite(32, 256, 'pebble').setScale(8,8);
    prjctle.disableBody(false, true); //So we dont let our first projectile fall down before getting launched
    this.physics.add.collider(gnd, prjctle);
    this.physics.add.collider(basket, prjctle);
    this.physics.add.collider(cat, prjctle, hitCat, null, this);
    this.physics.add.collider(cat2, prjctle, hitCat, null, this);

    this.input.on('pointerup', function () {
      prjctle.enableBody(true, 32, 256, true, true);
      this.physics.velocityFromRotation(60, timeHeld, prjctle.body.velocity);
    },this);
  }

  update(){
    timeHeld = this.input.activePointer.getDuration();
    if(timeHeld > 1000){
      timeHeld = 1000;
    }
    else if(timeHeld < 300){
      timeHeld = 300;
    }
  }
}

function hitCat(cat, prjctle){ //Collision check
// ADD CODE TO MAKE CAT FALL HERE
}

The only way to “convert” a body from static to dynamic is to re-create it. What I’d suggest instead is to make the cats dynamic bodies, but make them stationary:

cat.body.moves = false;

You can then set the property to true in hitCat to make them move.

3 Likes

Would this work if all the cats were in a physics group()?

Would I be able to set all cats to stationary until interacted with?

Right now, my code to get them moving isn’t working. The code runs fine but upon hitting the cat, the cat doesn’t fall:

function hitCat(cats, prjctle){ //Collision check
  cats.moves = true;
  cats.disableBody(true,true);
  cats.setTint(0xff0000);
  score+=1;
  if (score == catAmt){
    this.gameOverText.visible = true; //Only become visible on win
  }
}

My cats are in a group like this:

cats = this.physics.add.group();
cats.create(200, 100, 'cat').setOrigin(0,0).setScale(4,4);
cats.children.iterate(function (child){
    child.body.moves = false; //Make every cat stationary until hit
})

EDIT: Nvm I fixed it. The order of the args for hitCat() were backwards