Jump to content

How do we bounce shapes


Recommended Posts

I'm on Phaser 3.13

I'm playing around with shapes and created a rectangle in arcade mode....

var r1 = this.add.rectangle(200, 200, 10, 148, 0x6666ff);  
r1.setStrokeStyle(2, 0x1a65ac);

I would like to get this shape bouncing within the boundaries of my Phaser game, so I attempted to do this...

r1.body.setVelocity(100, 200).setBounce(1, 1).setCollideWorldBounds(true);

But it throws the following error in the counsel...


game.js:208 Uncaught TypeError: Cannot read property 'setVelocity' of null

Is this not allowed for shapes at the moment?


Link to comment
Share on other sites

setVelocity is a method only available to Arcade Physics objects, like ArcadeImage and ArcadeSprite. To enable a Shape you need to do it like this:

    var r1 = this.add.rectangle(200, 150, 148, 148, 0x6666ff);

    var r2 = this.add.rectangle(400, 150, 148, 148, 0x9966ff).setStrokeStyle(4, 0xefc53f);


    r1.body.velocity.x = 100;
    r1.body.velocity.y = 100;
    r1.body.bounce.x = 1;
    r1.body.bounce.y = 1;
    r1.body.collideWorldBounds = true;

    r2.body.velocity.x = -100;
    r2.body.velocity.y = 100;
    r2.body.bounce.x = 1;
    r2.body.bounce.y = 1;
    r2.body.collideWorldBounds = true;


Link to comment
Share on other sites

?Thank you so much Rich! Works perfectly and it also teaches me about Arcade Physics objects a little bit more now.  Many thanks!   And just for fun, I ended up making it a reusable function in the event I wanted something in parallel...


  let r1 = this.add.rectangle(200, 200, 10, 148, 0x6666ff);
  let r2 = this.add.rectangle(400, 200, 10, 148, 0x6666ff).setStrokeStyle(2, 0x1a65ac);

  const bounceShape = (ctx, getShape, vx=-100, vy=100, bx=1, by=1, cb=true) => {
    getShape.body.velocity.x = vx;
    getShape.body.velocity.y = vy;
    getShape.body.bounce.x = bx;
    getShape.body.bounce.y = by;
    getShape.body.collideWorldBounds = cb;

  bounceShape(this, r1);
  bounceShape(this, r2);


Link to comment
Share on other sites


  • Recently Browsing   0 members

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