1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
|
// SFML 2 specific headers required
#include <SFML\Graphics.hpp>
// Box2D specific header required
#include <Box2D\Box2D.h>
// Other headers required
#include <iostream>
int main ()
{
// Create a SFML window
sf::RenderWindow GameWindow(sf::VideoMode(800, 600, 32), "SFML and Box2D Physiks");
// Set the window position
GameWindow.setPosition(sf::Vector2i(55, 174));
// Create the SFML event handler
sf::Event Event;
// Create a SFML shape with a Rectangle
sf::RectangleShape rect;
rect.setSize(sf::Vector2f(100, 50));
rect.setPosition(0, 0);
rect.setFillColor(sf::Color(127, 0, 0, 255));
// Create the image buffer
sf::Texture Image;
if(!Image.loadFromFile("Block.png"))
return 1;
// Create SFML sprite
sf::Sprite Block;
// Set the sprites Texture
Block.setTexture(Image);
// Set the sprites position
Block.setPosition(400, 400);
// Initalizate Box2D
// Creating a Box2D world
// Set the gravity
b2Vec2 gravity(0.0f, -10.0f);
bool doSleep = true;
// Create new world object
b2World world(gravity, doSleep);
// Create new ground body
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);
// Creating a dynamic body
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(0.0f, 4.0f);
b2Body* body = world.CreateBody(&bodyDef);
// attach polygon shape
b2PolygonShape dynamicBox;
dynamicBox.SetAsBox(1.0f, 1.0f);
// Fixture definition
b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicBox;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.3f;
body->CreateFixture(&fixtureDef);
// Box2D simulating
// initializate the time steps
float32 timeStep = 1.0f / 60.0f;
int32 velocityIterations = 6;
int32 positionIterations = 2;
// Game loop
while(GameWindow.isOpen())
{
// Event handler loop
while(GameWindow.pollEvent(Event))
{
// Box2D simulationsloop
for (int32 i = 0; i < 60; ++i)
{
world.Step(timeStep, velocityIterations, positionIterations);
b2Vec2 position = body->GetPosition();
float32 angle = body->GetAngle();
printf("%4.2f %4.2 %4.2\n", position.x, position.y, angle);
}
switch(Event.type)
{
case::sf::Event::Closed:
std::cout << "Window was closed." << std::endl;
GameWindow.close();
break;
default:
break;
}
}
// Clear the Game Window
GameWindow.clear(sf::Color(0, 255, 255));
GameWindow.display();
}
return 0;
}
|