Box2D:让身体随机间隔下降

时间:2013-11-20 19:02:14

标签: c++ opengl timer 2d box2d

我正在尝试开发一种游戏,其中我有几个b2PolygonShape个身体,它们应该从顶部掉下来。但我想要的是我希望他们从随机位置跌落并有一些延迟。到目前为止我所做的并没有让我这样做,即身体确实摔倒了,但是它们会一起掉下来。我不知道有多么迟迟地打电话给这个功能!我甚至无法从display函数调用它。 init函数只被调用一次。 这是我到目前为止所尝试的:

aadBrick实际上适用于身体的功能

b2Body* addBrick(int x,int y,int w,int h,bool dyn=true)
{
    b2BodyDef bodydef;  
    bodydef.position.Set(x*P2M,y*P2M);   //Setting body position
    if(dyn)
    {
            bodydef.type=b2_dynamicBody;  // dynamic body means body will move

    }

    brick=world->CreateBody(&bodydef);        //Creating box2D body

    b2PolygonShape shape;            //Creating shape object
    shape.SetAsBox(P2M*w,P2M*h);

    ////////////// Adding Fixtures(mass, density etc) //////////////


    brickFixture.shape=&shape;
    brickFixture.density=1.0;
    circleFixture.restitution = 0.7;
    brick->CreateFixture(&brickFixture);
    return brick;
}

这是init函数

void init()
{
    glMatrixMode(GL_PROJECTION);
    glOrtho(0,WIDTH,HEIGHT,0,-1,1);
    glMatrixMode(GL_MODELVIEW);
    glClearColor(0,0,0,1);

    world=new b2World(b2Vec2(0.0,5.8));

    addGround(WIDTH/2,HEIGHT-80,WIDTH,10,false); 

    addBrick(80,0,10,10);// these bricks should fall with some delay not together
    addBrick(100,0,10,10);

    actor=addActor(80,460,50,70,false); // static body

}

这是计时器功能,如果它与延迟有关!

void Timer(int t)
{
world->Step(1.0/30.0,8,3);

glutPostRedisplay();
glutTimerFunc(1000/30,Timer,1);
}

1 个答案:

答案 0 :(得分:2)

我建议下一个解决方案:

    int mCounter = 0;

    #define MAX_DELAY 60

    void Timer(int t)
    {
        if (mCounter <= 0)
        {
            // rand() % 100 - random value in range 0 - 99
            addBrick(rand() % 100, 0,10,10);

            mCounter = rand() % MAX_DELAY;
        }
        mCounter -= t;

        world->Step(1.0/30.0,8,3);

        glutPostRedisplay();
        glutTimerFunc(1000/30,Timer,1);
    }