其他分享
首页 > 其他分享> > c – 在Box2D中制作一个涡旋

c – 在Box2D中制作一个涡旋

作者:互联网

我试图通过施加力在C / Objective C上的Box2D中制作螺旋涡旋.
我想要意识到的是一个漩涡,它将身体从一个点推出,或吸引它们.
我想我将不得不申请多个部队.

我在这个问题上的切入点是:

我想我必须施加3种力量:
– 从中​​心吸引或排斥身体的冲动.
– 让它在螺旋上横向移动的冲动,但……怎么样?
– 如果冲动对我不起作用,则转动身体本身的扭矩.

解决方法:

我曾经做过一个旋转平台,制作了一个圆形传感器,它通过圆形矢量场给予身体切向速度变化.我使用的圆形矢量场是这样的:

V = (y, -x)

可以在此处找到此向量字段的直观表示:
http://kasadkad.files.wordpress.com/2009/09/derham1.png?w=450&h=427

y和x是身体与传感器中心的相对位置,因此您可以执行以下操作:

Vector getTangentVector(Vector relativePosition, bool invert)
{
    Vector vec;
    if(invert) //if it's cw or ccw
    {
        vec.setY(relativePosition.x());
        vec.setX(-relativePosition.y());
    }
    else
    {
        vec.setY(-relativePosition.x());
        vec.setX(relativePosition.y());
    }
    return vec;
}

然后在我的程序的更新方法我做这样的事情:

for (b2ContactEdge* ce = platformBody->GetContactList(); ce; ce = ce->next)
{

    b2Contact* c = ce->contact;

    if(c->IsTouching())
    {
        const b2Body* bodyA = c->GetFixtureA()->GetBody();
        const b2Body* bodyB = c->GetFixtureB()->GetBody();

        const b2Body* targetBody = (bodyA == platformBody)?bodyB:bodyA;

        Vector speed = getTangentImpulse(
                          getRelativePosition(platformBody, targetBody),
                          true);


        speed *= CONSTANT; // CONSTANT = 1.8, 
                           // this is to account for the targetBody attrition, 
                           // so it doesn't slip on the platform

        Vector currentSpeed;
        currentSpeed.setX(targetBody->GetLinearVelocity().x);
        currentSpeed.setY(targetBody->GetLinearVelocity().y);



        Vector diff = speed - currentSpeed;
        diff *= 0.01; //should depend on time, but this worked nicely. It makes the
                      //body change its linear velocity to be the same as "speed" at a 
                      //0.01 change rate.

        currentSpeed += diff;
        targetBody->SetLinearVelocity(
                               b2Vec2(currentSpeed.x(), 
                               currentSpeed.y()));

    }

}

这个解决方案有很多变通方法,例如,我不使用冲动并手动改变速度,它对我来说效果更好.另外,我使用常数来计算损耗.

它仍然产生了我需要的效果,所以我希望它对你有用.对于漩涡,我猜你只需要连接一个关节,如鼠标关节,连接到中心并抓住身体.如果仅使用关节,则很难使其足够强壮以抓住身体,但足够弱以使其围绕中心旋转.与我的代码一起,通过玩常量可能更容易实现这一点.

我希望这有帮助.

编辑:我只记得,通过平台代码,您还可以确保旋转方向,这对于关节来说是不可能的.

标签:c,objective-c,box2d,quartz-graphics,physics
来源: https://codeday.me/bug/20191007/1865377.html