How to rotate physicsbody accordingly to sprite

How to rotate physicsbody accordingly to sprite
0

#1

I create a sprite, rotate it and then create and add a physics body to it. Everything works fine if there is no rotation applied (look at 1.) but when I rotate by 90 degrees the physicsbody does not match the sprite rotation (look at 2.). What should I do so that after the rotation the physicsbody looks like in 3.?

My current code:

auto sprite = Sprite::create(filepath);
sprite->setRotation(90);                              
auto physicsBody = PhysicsBody::createBox(sprite->getContentSize(),
                                           PhysicsMaterial(10.0f, 1.0f, 2.0f));
physicsBody->setDynamic(true);
sprite->setPhysicsBody(physicsBody);
addChild(sprite);

#2

What version of Cocos2d-x?

Do you have your debug draw on so you can see what is happening?


#3

@slackmoehrle
I’m using the 3.16 version of cocos and yes, I have debug mode on. It looks liek this

Any ideas whats wrong or how to fix this?


#4

Wow that is weird. I thought the body should rotate too. It does in one of my games but I’m still using 3.13 I think in that game


#5

@slackmoehrle
Can You check it plzzzz? :stuck_out_tongue: Because I’m a bit stuck right now.


#6

bump :stuck_out_tongue:


#7

Maybe a shape is missing?


#8

Is this the only code you are using for the sprite and body?


#9

@slackmoehrle
yes this is the only code I’m currently using and it’s behaving wrong (as seen on the image above). :confused:

@dreifrankensoft
What do You mean? Can You elaborate?

EDIT:
Found it! I went through the cpp tests and I found the Bug3988 and again, I had the same code besides one thing… The trick was to set the rotation AFTER! setting the physics body. So the solution looks like this:

auto sprite = Sprite::create(filepath);                         
auto physicsBody = PhysicsBody::createBox(sprite->getContentSize(),
                                           PhysicsMaterial(10.0f, 1.0f, 2.0f));
physicsBody->setDynamic(true);
sprite->setPhysicsBody(physicsBody);
sprite->setRotation(90);     
addChild(sprite);

I’m not sure if this is a known issue @slackmoehrle but I think it should be addressed at one point (or maybe it is in newer cocos versions dunno). I just don’t think that in this case the order of the calls should matter and in my opinion both cases should work. If I’m wrong please elaborate on why I’m wrong :wink: