I decided to make a pong-like game with "improved physics", and decided to use Box2D. But for some reason, the ball always bounces perpendicular to the walls after a while. Is there any way to solve this?
If it helps, here's the code adapted to the testbed:
Code:
#ifndef PONG_H
#define PONG_H
class Pong : public Test
{
public:
Pong()
{
m_world->SetGravity(b2Vec2(0.0f, 0.0f));
b2BodyDef bodyDef;
b2PolygonDef polyDef;
bodyDef.position.Set(-51.f,0.f);
polyDef.SetAsBox(1.f,38.5f);
polyDef.friction = 0.1f;
b2Body* framel = m_world->CreateBody(&bodyDef);
framel->CreateShape(&polyDef);
bodyDef.position.Set(51.f,0.f);
b2Body* framer = m_world->CreateBody(&bodyDef);
framer->CreateShape(&polyDef);
bodyDef.position.Set(0.f,38.5f);
polyDef.SetAsBox(51.f,1.f);
b2Body* framet = m_world->CreateBody(&bodyDef);
framet->CreateShape(&polyDef);
bodyDef.position.Set(0.f,-38.5f);
b2Body* frameb = m_world->CreateBody(&bodyDef);
frameb->CreateShape(&polyDef);
b2CircleDef circleDef;
circleDef.radius = 1.5f;
circleDef.friction = 0.4f;
circleDef.density = 1.f;
circleDef.restitution = 1.25f;
bodyDef.position.Set(0.f,0.f);
b2Body* ball = m_world->CreateBody(&bodyDef);
ball->CreateShape(&circleDef);
ball->SetMassFromShapes();
ball->SetBullet(true);
ball->SetLinearVelocity(b2Vec2(200.f,0.f));
bodyDef.position.Set(-45.f,0.f);
polyDef.SetAsBox(1.5f,6.f);
polyDef.density = 10.f;
polyDef.friction = 0.4f;
circleDef.density = 5.f;
circleDef.localPosition.Set(0.f,6.f);
circleDef.restitution = 0.5f;
b2Body* paddle1 = m_world->CreateBody(&bodyDef);
paddle1->CreateShape(&polyDef);
paddle1->CreateShape(&circleDef);
circleDef.localPosition.Set(0.f,-6.f);
paddle1->CreateShape(&circleDef);
paddle1->SetMassFromShapes();
bodyDef.position.Set(45.f,0.f);
b2Body* paddle2 = m_world->CreateBody(&bodyDef);
paddle2->CreateShape(&polyDef);
paddle2->CreateShape(&circleDef);
circleDef.localPosition.Set(0.f,6.f);
paddle2->CreateShape(&circleDef);
paddle2->SetMassFromShapes();
b2PrismaticJointDef jointDef;
b2Vec2 worldAxis(0.0f, 1.0f);
jointDef.motorSpeed = 0.0f;
jointDef.maxMotorForce = 10e4f;
jointDef.enableMotor = true;
jointDef.collideConnected = true;
jointDef.Initialize(paddle1, frameb, paddle1->GetWorldCenter(), worldAxis);
paddle1joint = (b2PrismaticJoint*)m_world->CreateJoint(&jointDef);
jointDef.Initialize(paddle2, frameb, paddle2->GetWorldCenter(), worldAxis);
paddle2joint = (b2PrismaticJoint*)m_world->CreateJoint(&jointDef);
ball->AllowSleeping(false);
paddle1->AllowSleeping(false);
paddle2->AllowSleeping(false);
}
void Keyboard(unsigned char key)
{
switch (key)
{
case 'e':
{
paddle1joint->SetMotorSpeed(-100.f);
}
break;
case 'd':
{
paddle1joint->SetMotorSpeed(100.f);
}
break;
case 'i':
{
paddle2joint->SetMotorSpeed(-100.f);
}
break;
case 'k':
{
paddle2joint->SetMotorSpeed(100.f);
}
break;
}
}
static Test* Create()
{
return new Pong;
}
b2PrismaticJoint* paddle1joint;
b2PrismaticJoint* paddle2joint;
};
#endif