I'm working on a game and I'm wondering what is the proper way to rotate a single Box2D body using the accelerometer? (i.e. so that the body is always facing "up") I found that there used to be a method in the b2Body class "SetAngle()" that would make this process very simple and straightforward. However, that method is no longer a part of the API. Any suggestions?
Using Accelerometer to rotate Box2D body
(8 posts) (5 voices)-
Posted 1 year ago #
-
zzt4,
Try using
body->SetTransform(position, angle)instead. (Just pass the current position if you don't want to change it).Regards,
QPosted 1 year ago # -
Awesome, I didn't know there was a SetTransform method with an angle passed in... Unfortunately I'm not sure on the math to get from accel.x and accel.y to an angle. Hmm.... Any trig-gifted people on here? lol
Posted 1 year ago # -
I tried using body->SetTransform(position, angle) and my game crashes. I tried calling it in my layer's init method and my when I comment it out, my game runs perfectly. Here's my line of code, where rockBody is a b2Body. Any ideas?
rockBody->SetTransform( rockBody->GetPosition(), 0.0f);Posted 1 year ago # -
I am just a newbie myself, but may I suggest assigning rockBody->getPosition() to a variable first and then passing it in in SetTransform method.
Maybe it crashes because you're referencing object to itself?Posted 1 year ago # -
Math is just simple trig :-) cos(x), sin(y)...
Is rockBody pointing to a valid b2Body? Check it isn't nil before doing the SetTransform.
Regards,
StevePosted 1 year ago # -
For anyone else who is interested, I figured out the errors with my accelerometer not working... Silly me I had commented out this line of code
self.isAccelerometerEnabled = YES;hahaha.On the math side, I worked with my Computer Graphics teacher to figure it out. The angle to rotate the body you want to keep pointed towards the top of the screen is
float angle = atan2(acceleration.x, -acceleration.y);Where atan2 returns an angle in radians between zero and 2*pi. Keep in mind that box2D and chipmunk both take the angle in radians, so if you want to use the angle for CCSprites, you'll need to convert it to degrees using CC_RADIANS_TO_DEGREES. Just posting my solutions to my own issues, hoping it will help others.
Posted 1 year ago # -
Hey zzt4,
It works but the object rotates only a quarter not all the way around. Does anyone have a fix for that?
Posted 4 months ago #
Reply
You must log in to post.