Hello,
I cannot get the ball to bounce off the ground in this simulation. I am using SFML to render the graphics and Chipmunk Physics for the physics. When the physics simulation is ran, all it does is the ball drops to the ground without bouncing off of the ground.
const int MAX_WIDTH = 800;
const int MAX_HEIGHT = 600;
const int MAX_DEPTH = 32;
bool GameRunning = true;
sf::RenderWindow GameWin;
sf::Event event;
sf::RectangleShape ground;
sf::CircleShape ball;
bool Paused = true;
cpVect gravity;
cpSpace* space;
cpShape* groundShape;
cpBody* groundBody;
cpFloat radius = 10;
cpFloat mass = 1;
cpFloat moment;
cpBody* ballBody;
cpShape* ballShape;
cpFloat timeStep;
GameWin.create(sf::VideoMode(MAX_WIDTH, MAX_HEIGHT, MAX_DEPTH), "Physics Test - [Chipmunk Physics & SFML]");
ground.setPosition(sf::Vector2f(0, 540));
ground.setSize(sf::Vector2f(800, 560));
ground.setFillColor(sf::Color(128, 128, 128));
ball.setPosition(sf::Vector2f(0, 15));
ball.setRadius(radius);
ball.setFillColor(sf::Color(255, 0, 0));
gravity = cpv(0, 50);
space = cpSpaceNew();
cpSpaceSetGravity(space, gravity);
groundShape = cpSegmentShapeNew(space->staticBody, cpv(-ground.getPosition().x, ground.getPosition().y), cpv(-ground.getPosition().x, ground.getPosition().y), 0);
cpShapeSetFriction(groundShape, 1);
cpSpaceAddShape(space, groundShape);
groundBody = cpBodyNew(0, 560);
cpVect groundPos = cpBodyGetPosition(groundBody);
cpBodySetPosition(groundBody,groundPos);
groundBody->userData = &ground;
cpFloat moment = cpMomentForCircle(mass, 1, radius, cpvzero);
ballBody = cpSpaceAddBody(space, cpBodyNew(mass, moment));
cpBodySetPosition(ballBody, cpv(ball.getPosition().x, ball.getPosition().y));
ballShape = cpSpaceAddShape(space, cpCircleShapeNew(ballBody, radius, cpvzero));
cpShapeSetFriction(ballShape, 1.0);
cpShapeSetElasticity(ballShape, 0.5);
ballBody->userData = &ball;
timeStep = 1.0 / 600.0f;
while (GameRunning)
{
while (GameWin.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
GameWin.close();
GameRunning = false;
}
if (event.type == sf::Event::KeyPressed)
{
if (event.key.code == sf::Keyboard::Escape)
{
GameRunning = false;
GameWin.close();
}
if (event.key.code == sf::Keyboard::P && Paused == true)
{
Paused = false;
}
else if (event.key.code == sf::Keyboard::P && Paused == false)
{
Paused = true;
}
}
}
if (!Paused)
{
cpVect pos = cpBodyGetPosition(ballBody);
cpVect vel = cpBodyGetVelocity(ballBody);
cpFloat angle = cpBodyGetAngle(ballBody);
ball.setPosition(pos.x, pos.y);
ball.setRotation(angle);
cpSpaceStep(space, timeStep);
}
DrawGame();
}
}