Search code examples
ioscocos2d-iphonebox2dgravity

Mixing Box2D Accelerometer + Gravity?


I have 2 questions:
1. Is it possible to retrieve the current X Coordinate of a b2Body? I know the API GetPosition but that is not specific enough, I need the X coordinate specifically.
2. Is it possible to add gravity to my specific b2Body in my UIAccelerometer delegate method?

What I am trying to do is move the b2Body with the current UIAccelerometer input with Box2D gravity in one line using Apply Force. This is what I have so far, doesn't anyone know how I can incorporate #1+#2 into this line?:

body->ApplyForce(b2Vec2(accelX*100, -30.0f), body->GetPosition());

Thanks!

Edit1: Thanks for answering those questions, that cleared it up for me! This leaves me 3 more questions:
1. Now that I understand how to get the x coordinate of b2Body, how would I set it?
Would it be something like this?

body->GetPosition().x = 30;

2. With these x coordinates it is the same X coordinate as if I was using UIKit correct? I know UIKit frames things different I just want to make sure that if I did something similar in UIKit, it would output the same X coordinate, is that correct?


Solution

  • Answer to 1)

    b2Vec pos = body->GetPosition();
    float x = pos.x;
    // do whatever you need to do with x
    

    You can also write

    float x = body->GetPosition().x;
    

    Answer to 2)

    Store whatever values you need from the UIAccelerometer didAccelerate method in an instance variable. For example accelX:

    accelX = acceleration.x;
    

    In your world update method simply use those values to calculate the force in whatever way you need it. Then apply the force like you posted:

    body->ApplyForce(b2Vec2(accelX*100, -30.0f), body->GetPosition());