Jump to content

Rotated polygon physics body doesn't work properly with anchor point other than default


dnassler
 Share

Recommended Posts

Hi I tried to rotate a sprite and it's associated physics body as per the example but in my test (different from the example) I specify an anchor at 0.5,0.5. I set the sprite rotation and the physics body rotation (eg. sprite.body.polygon.rotate( rotationAmount) ) but the physics body rotates as if the anchor was not set... I guess because you have to set the physics anchor point too?? 

 

So can someone give me an example couple lines of code that tell me how to rotate a sprite with an anchor point set in the sprite, please? I'm really frustrated.

 

See the example which is does a sprite rotation without an anchor point:

http://examples.phaser.io/_site/view_full.html?d=collision&f=rotated+bounding+box.js&t=rotated%20bounding%20box

 

Thanks

Link to comment
Share on other sites

I found a way to rotate the physics body when the anchor point is set to other than the default of 0,0.

 

If you have, for example, a sprite with width/height of 100x100 called "shape":

 

shape.anchor.setTo(0.5,0.5);

shape.body.setPolygon( 0,0, 100,100, 0,100 );

shape.angle = Math.floor(Math.random() * 4) * 90;

shape.body.translate( -50,-50 );
shape.body.polygon.rotate(shape.rotation);
shape.body.translate( 50, 50 );
 
... the "translate" fixes it. But I don't like that the physics rotation is not kept in sync with the sprite rotation since that means that any automatic rotation will not affect the physics body... for example if you set the angular velocity of a sprite then it's physics body will not rotate with it and so, to me it seems, it is almost useless to have a non-circular/block shaped collision physics body.
 
I hope the next major release fixes this kind of thing.
Link to comment
Share on other sites

Hi, thank you for the fix, I ran into the very same problem and this is a major time saver!

You don't have to explicitly define the bounding box first though, you can take it as is after creating your sprite and simply translate the body by half its dimensions. Here, this worked for me:

 

var sprite = group.create(x, y, "sprite");sprite.anchor.setTo(0.5, 0.5);sprite.angle = angle; // I'm using degreessprite.body.translate(-sprite.width/2, -sprite.height/2);sprite.body.polygon.rotate(sprite.rotation);sprite.body.translate(sprite.width/2, sprite.height/2);

I agree that it would be more than useful to have an easier way of keeping the sprite and and bounding box in sync.

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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