首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TimeStep请勿迭代| Box2D

TimeStep请勿迭代| Box2D
EN

Stack Overflow用户
提问于 2021-10-24 03:32:06
回答 1查看 33关注 0票数 0

在多年的缺席之后,我又回到了box2d,我想从零开始。最重要的是,这次决定使用C++版本(过去使用Javascript版本)

由于某种原因,box2d.org中描述的第一个程序不能正常运行。当我编译它时,我没有得到任何错误,但是结果是错误的。

结果是0.00 4.00 0.00,并且保持不变。但是随着时间步长的每次迭代,position.x.y应该会减小(position.x .x和angle应该保持不变)

代码语言:javascript
复制
#include "include/box2d/box2d.h"
#include <iostream>
#include <stdio.h>

    
int main(){
  b2Vec2 gravity(0.0f, -10.0f); // define the gravity vector
  b2World world(gravity);       //create the world object

//Creating static Ground Body
  b2BodyDef groundBodyDef;      //body definition
    groundBodyDef.position.Set(0.0f, -10.0f);

  b2Body* groundBody = world.CreateBody(&groundBodyDef); // body definition is passed to the world object to create the ground body

  b2PolygonShape groundBox;    //create a ground polygon.
    groundBox.SetAsBox(50.0f, 10.0f);   //We use the SetAsBox shortcut to form the ground polygon into a box shape

  groundBody->CreateFixture(&groundBox, 0.0f);  //creating the shape fixture

//Creating Dynamic Body
  b2BodyDef bodyDef;
  bodyDef.type = b2_dynamicBody;  //By default bodies are static, so we should set the b2BodyType at construction time to make the body dynamic
  bodyDef.position.Set(0.0f, 4.0f);
  b2Body* body = world.CreateBody(&bodyDef);

  b2PolygonShape dynamicBox;    //create a box shap
  dynamicBox.SetAsBox(1.0f, 1.0f);
//A dynamic body should have at least one fixture with a non-zero density. Otherwise you will get strange behavior.
  b2FixtureDef fixtureDef;    // fixture definition using the box
  fixtureDef.shape = &dynamicBox;
  fixtureDef.density = 1.0f;
  fixtureDef.friction = 0.3f;

  float timeStep = 1.0f / 60.0f;  //Integrators simulate the physics equations at discrete points of time -> ie timeStep

  int32 velocityIterations = 6;
  int32 positionIterations = 2;

  for (int32 i = 0; i < 60; ++i)  {
      world.Step(timeStep, velocityIterations, positionIterations);
      b2Vec2 position = body->GetPosition();
      float angle = body->GetAngle();
      printf("%4.2f %4.2f %4.2f\n", position.x, position.y, angle);
  }

      //return 0;
}

为noobie的问题道歉,但找不到我的错误。我几乎要复制粘贴所有的东西!

EN

回答 1

Stack Overflow用户

发布于 2021-10-28 00:38:32

我实际上忘记了包含body->CreateFixture(&fixtureDef);

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69693665

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档