开发者

How to grab a b2Body and move it around the screen? (cocos2d,box2d,iphone)

I want to move any b2body that is touched on the screen around the screen. I've heard something about mouse joints..

I found that: http://iphonedev.net/2009/08/05/how-to-grab-a-sprite-with-cocos2d-and-box2d/

but I just gives me a lot of errors if i just copy the ccTouch Methods into a new project (of course the variables in the header too). E.g. world->Query <- NO MEMBER FOUND

May someone make a tut/a new project开发者_开发技巧 and upload it here. Or is there a better way?


First you have to create b2QueryCallback subclass:

class QueryCallback : public b2QueryCallback
{
public:
    QueryCallback(const b2Vec2& point)
    {
        m_point = point;
        m_object = nil;
    }

    bool ReportFixture(b2Fixture* fixture)
    {
        if (fixture->IsSensor()) return true; //ignore sensors

        bool inside = fixture->TestPoint(m_point);
        if (inside)
        {
             // We are done, terminate the query.
             m_object = fixture->GetBody();
                 return false;
        }

        // Continue the query.
        return true;
    }

    b2Vec2  m_point;
    b2Body* m_object;
};

Then in your touchBegan method:

    b2Vec2 pos = yourTouchPos;
// Make a small box.
b2AABB aabb;
b2Vec2 d;
d.Set(0.001f, 0.001f);
aabb.lowerBound = pos - d;
aabb.upperBound = pos + d;

// Query the world for overlapping shapes.
QueryCallback callback(pos);
world_->QueryAABB(&callback, aabb);         

b2Body *body = callback.m_object;
if (body)
    {
        //pick the body
    }

There are two ways I see you can control the picked body. The first one, as you notices - to create a mouseJoint and the second is to make your body kinematic and control it's velocity (not position! - it will provide non-physical behavior when collide because the speed will be zero). In first case if you will move your objects very fast there will be some delay when moving. I did not try the second way myself because in this case the body will not collide with other kinematic and static bodies.

Also you may want to lock body's rotation when moving.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜