简体   繁体   English

如何获取b2Body并将其在屏幕上移动? (cocos2d,box2d,iphone)

[英]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. 我想在屏幕周围移动屏幕上触摸的任何b2body。 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/ 我发现: 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). 但是如果我只是将ccTouch方法复制到一个新项目中(当然,标头中的变量),我也会给我带来很多错误。 Eg world->Query <- NO MEMBER FOUND 例如world-> Query <-没有找到会员

May someone make a tut/a new project and upload it here. 可能有人做一个tut /一个新项目并在这里上传。 Or is there a better way? 或者,还有更好的方法?

First you have to create b2QueryCallback subclass: 首先,您必须创建b2QueryCallback子类:

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: 然后在您的touchBegan方法中:

    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). 您会注意到,第一个是创建mouseJoint,第二个是使您的身体运动并控制它的速度(而不是位置!-碰撞时它将提供非物理行为,因为速度为零)。 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. 另外,您可能希望在移动时锁定身体的旋转。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM