c++ - Box2D:让 body 随机下降

标签 c++ opengl timer 2d box2d

我正在尝试开发一个游戏,其中有多个 b2PolygonShape 主体,它们应该从顶部掉落。但我想要的是我希望它们从随机位置掉落并有一些延迟。到目前为止我所做的并不能使我工作,即 body 确实会掉落但它们会一起掉落。我不知道如何延迟调用该函数!我什至无法从 display 函数中调用它。 init 函数只被调用一次。 到目前为止,这是我尝试过的:

aadBrick 实际是针对应该掉落的body的函数

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;
}

这是初始化函数

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);
}

最佳答案

我建议下一个解决方案:

    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);
    }

关于c++ - Box2D:让 body 随机下降,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20104648/

相关文章:

c++ - 使用 cocos2d-x 将 Sprite 内容保存为 .png 文件

c++ - 即使在顶点着色器中使用,glGetUniformLocation() 也返回 -1

c++ - GoogleTest for Android NDK C++ with CMake

c++ - 互斥锁指针双重NULL检查的原因是什么

opengl - Mesa 与 OpenGL 驱动程序有何不同?

opengl - 片段着色器 GLSL 中的颜色插值?

timer - 如果 NodeMCU 计时器中的代码在我设置的计时器间隔内执行,会发生什么情况?

java - timer.schedule() 根本不工作(在 Java 中)

c++ - OpenGL 中的地形小 map ?

c# - 'timer' 是否占用更多 CPU 资源?