Jump to content

Simple sprite rotation with P2 body


Markarz
 Share

Recommended Posts

Hi guys, 

 

I'm wondering if there's an easier solution for rotating a static sprite with a p2 body on it. I've searched around quite a bit and it seems like the issue is that having P2 enabled on a sprite continuously adjusts the rotation values, so setting rotation or angle gets overwritten. 

 

I've had good luck with using sprite.body.scale.x *= 1 to flip the sprite horizontally, but that doesn't work with a symmetrical sprite. If you imagine a D, flipping it vertically would not change the appearance, and you would really want to rotate it by 90 degrees to face it upwards. 

 

I've also read about solutions with making adjustments in the update method, but this seems like a waste of resources compared to just rotating the sprite once upon initialization. I ended up using one right-facing image and flipping with body.x *= -1, and one up-facing image and flipping that with body.y *= -1. This works out pretty well for what I want, but I end up maintaining 2 objects (or if this were a group, potentially hundreds of objects) in memory. 

 

Anyone have any other ideas I could try out? 

Link to comment
Share on other sites

I tried using body.fixedRotation and had no luck with it. I'll try to play with it some more and see if I can get it working, but the documentation is a little light on that property. I'm still not sure if it only affects the rotation on the body directly, or the sprite angle, or what exactly. In my case, I change the rotation based on what direction the player is facing, so I may have to do something like 

 

if(direction == 1) { 

body.fixedRotation = false;

sprite.angle = 90; 

body.fixedRotation = true;

}

 

or possibly use body.rotateLeft(?) instead of the sprite angle. Even then, it would probably be more ideal to not lock the rotation so the projectiles can rotate based on P2 collisions if necessary. Using two separate sprites should allow that to happen normally, I think. 

Link to comment
Share on other sites

Ah, you're right. I was trying to set the angle on the sprite, but the body angle must override the sprite angle. That must be why setting fixedRotation on the p2 body allows the sprite angle through. Setting the angle directly on the p2 body should work how I wanted since that will set as a starting angle and still allow the angle to change with collisions.

 

Thanks @chongdashu!

 

For easier reference, the code above:

 

if(direction == 1) { 

  body.fixedRotation = false;

  sprite.angle = 90;   

  body.fixedRotation = true;

can be converted to: 

 

if(direction == 1) {  

  sprite.body.angle = 90; 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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