Setting coordinates in Phaser where the body and the sprite are offset from each other

If you're using Phaser with matter physics, sometimes you might need to set a body of a different size from your sprite. That's pretty easy, simply by setting the width and height of the body. But if your physics body is offset from where the sprite is, then one has to use the setOrigin method to fix this. This can be tricky. This diagram might help explain how origin is used, where 'visual' is the sprite, and 'body' is the physics hitbox:
And finally, if you do some algebra to find the origin, you can use the following code:
    // SPDX-License-Identifier: Apache-2.0
    const visualX = 150;
    const visualY = 150;
    const visualWidth = 120;
    const visualHeight = 120;
    const bodyX = 200;
    const bodyY = 200;
    const bodyWidth = 180;
    const bodyHeight = 180;

    const originX = (bodyX - visualX) / visualWidth + 0.5;
    const originY = (bodyY - visualY) / visualHeight + 0.5;

    const sprite = this.matter.add.sprite(bodyX, bodyY, 'mage');

    sprite.setBody({
      type: 'rectangle',
      width: bodyWidth,
      height: bodyHeight
    }, {
      isSensor: true,
    });

    sprite.setOrigin(originX, originY);

Comments

Popular posts from this blog

Dark Fonts and Colors for light theme in VS 11

Laptop Surprises: Lenovo Yoga Slim 7i