Rotation and getBounds() in Phaser

1.9k views Asked by At

I'm using Phaser 2.3.0 and I want to know the bounds of a rotated sprite.

But when I change sprite.rotation, the values of sprite.getBounds() don't change:

sprite = game.add.sprite(0, 0, "img"); // game.load.spritesheet("img", "grid.png", 32, 32);
console.log(sprite.getBounds()); // Object { x: 0, y: 0, width: 32, height: 32, type: 22 }
sprite.rotation = 0.52; // 30°
console.log(sprite.getBounds()); // Object { x: 0, y: 0, width: 32, height: 32, type: 22 }

What's wrong?

How can I get the correct bounds?

2

There are 2 answers

0
Kamen Minkov On

As far as I know, getBounds() will return the smallest possible rectangle that the object fits in and since Phaser.Rectangle doesn't have a rotation property, you will get the same rectangle both times.

0
Kleber On

It's being 6 years since this question, but just for the people who end up here after a Google search, the right answer is that the getBounds() is based on the object's worldTransform which is updated at the end of the render() cycle. So changing something in the object and in the next line trying to get its bounds will give you the old value. The solution is to wait a frame or call updateTransform():

const sprite = game.add.sprite(0, 0, "img");
console.log(sprite.getBounds());
// Phaser.Rectangle { x: 0, y: 0, width: 32, height: 32, type: 22 }

sprite.rotation = 0.52; // 30°
sprite.updateTransform();
console.log(sprite.getBounds());
// Phaser.Rectangle {x: -15.900164410999576, y: 0, width: 43.67037816068437, height: 43.67037816068437, type: 22}

https://photonstorm.github.io/phaser-ce/Phaser.Sprite.html#getBounds

Keep in mind that if the object is inside an hierarchy of objects, you should call updateTransform() in the highest object.