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

耗尽温柔 提交于 2019-12-05 07:05:50

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/5282254/how-to-grab-a-b2body-and-move-it-around-the-screen-cocos2d-box2d-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!