Box2d的HelloWorld范例
box2d版本:2.4.0
cmake版本:3.16
vs版本:2017
1. 编写cmakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(box2d_helloWorld)
# 指定box2d模块的cmake文件
set(box2d_DIR "X:/development/box2d/lib/cmake/box2d"
find_package(box2d REQUIRED)
set(DEMO_SRC
main.cpp)
add_executable(HelloWorld ${DEMO_SRC})
# 添加box2d的依赖库
target_link_libraries(HelloWorld box2d::box2d)
2. 编写main.cpp文件,根据box2d的文档,编写helloWorld,最简单的范例
#include <iostream>
#include <box2d/box2d.h>
int main(int argc, char* argv[])
{
b2Vec2 gravity(0.0f, -10.0f);
b2World world(gravity);
// groundbox
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0.0f, -10.0f);
b2Body* groundBody = world.CreateBody(&groundBodyDef);
b2PolygonShape groundBox;
groundBox.SetAsBox(50.0f, 10.0f);
groundBody->CreateFixture(&groundBox, 0.0f);
// dynamic body
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(0.0f, 4.0f);
b2Body *body = world.CreateBody(&bodyDef);
b2PolygonShape dynamicBox;
dynamicBox.SetAsBox(1.0f, 1.0f);
b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicBox;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.3f;
body->CreateFixture(&fixtureDef);
// simullation.
float timeStep = 1.0f / 60.0f;
int32 velocityIterations = 6;
int32 positionIterations = 2;
// simulation
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;
}
3. 使用cmake构建项目
>> cmake -S ./ -B ./build
在build目录下生成了vs的解决方案
4. 使用vs2017编译解决方案
>>devenv HelloWorld.sln /Build "Debug|win32"
5. 运行结果,得到输出结果
>>.\HelloWorld.exe

-----------------勿在浮沙筑高台

浙公网安备 33010602011771号