본문 바로가기
[ChatGPT] Sample Code 샘플 코드

[ChatGPT][Box2D] Box2D 박스 2D 기본 샘플 코드

by byungwoo733 2023. 3. 19.
728x90
반응형
SMALL

Here's an example code for creating a simple Box2D simulation without any other dependencies

다른 의존성 없이 간단한 Box2D 시뮬레이션을 생성하기 위한 예제 코드

#include <Box2D/Box2D.h>
#include <iostream>

int main() {
    // Define the gravity vector
    b2Vec2 gravity(0.0f, -9.81f);

    // Create a Box2D world with the defined gravity
    b2World world(gravity);

    // Create a ground body
    b2BodyDef groundBodyDef;
    groundBodyDef.position.Set(0.0f, -10.0f);
    b2Body* groundBody = world.CreateBody(&groundBodyDef);

    // Create a ground shape
    b2PolygonShape groundBox;
    groundBox.SetAsBox(50.0f, 10.0f);

    // Create a fixture for the ground body
    b2FixtureDef groundFixtureDef;
    groundFixtureDef.shape = &groundBox;
    groundBody->CreateFixture(&groundFixtureDef);

    // Create a dynamic body
    b2BodyDef bodyDef;
    bodyDef.type = b2_dynamicBody;
    bodyDef.position.Set(0.0f, 20.0f);
    b2Body* body = world.CreateBody(&bodyDef);

    // Create a shape for the dynamic body
    b2PolygonShape dynamicBox;
    dynamicBox.SetAsBox(2.0f, 2.0f);

    // Create a fixture for the dynamic body
    b2FixtureDef fixtureDef;
    fixtureDef.shape = &dynamicBox;
    fixtureDef.density = 1.0f;
    fixtureDef.friction = 0.3f;
    body->CreateFixture(&fixtureDef);

    // Set up the time step and iterations for the simulation
    float32 timeStep = 1.0f / 60.0f;
    int32 velocityIterations = 6;
    int32 positionIterations = 2;

    // Run the simulation for 1000 steps
    for (int i = 0; i < 1000; i++) {
        // Update the Box2D world
        world.Step(timeStep, velocityIterations, positionIterations);

        // Print the position of the dynamic body
        b2Vec2 position = body->GetPosition();
        std::cout << "Position: (" << position.x << ", " << position.y << ")" << std::endl;
    }

    return 0;
}

====================

Here's an example of a header file for a simple Box2D simulation

다음은 간단한 Box2D 시뮬레이션을 위한 헤더 파일의 예입니다.

#ifndef BOX2D_EXAMPLE_H
#define BOX2D_EXAMPLE_H

#include <Box2D/Box2D.h>

class Box2DExample {
public:
    Box2DExample();
    ~Box2DExample();

    void run();

private:
    b2World* m_world;
};

#endif
728x90
LIST

댓글