[ad_1]
I’m using Box2D and rebounding a box whenever it hits the bottom or top of the screen. I’m using world positions here; the maximum is 20.0f which is the value of boundarySize
:
void Game::ClampScreenY( Box* pBox)
{
bool isColliding = false;
auto pos = static_cast<b2Vec2>( pBox->GetPosition() );
auto aabb = pBox->GetAABB();
auto angle = pBox->GetAngle();
if( aabb.upperBound.y >= boundarySize )
{
pos.y = boundarySize - boxSize;
isColliding = true;
}
else if( aabb.lowerBound.y <= -boundarySize )
{
pos.y = -boundarySize + boxSize;
isColliding = true;
}
if( isColliding && !pBox->GetWasColliding())
{
auto vel = static_cast<b2Vec2>( pBox->GetVelocity() );
vel.y *= -1;
pBox->SetVelocity( vel );
pBox->SetPosition( pos );
}
// update
pBox->SetWasColliding( isColliding );
}
I’ve been testing this on a box with angularVelocity = 0
and angle = 0
and it works. However this rebound effect is not working for boxes that are rotating or that have an angle != 0
. Why is this happening? I’m getting out of bounds drawing. There’s obviously something wrong with this math.
Angle = 0
works fine and rebounds perfectly:
Angle != 0
crashes:
The ClampScreenY
function is called in the UpdateModel
function I created, which is responsible for updating the logic of the game.
After the game calls the UpdateModel
, it calls the ComposeFrame
which draws all objects (I just have one here):
void Game::ComposeFrame()
{
auto vertices = box->GetVertices(); // for debugging
box->Draw();
}
The call to box->Draw()
crashes when colliding with top of the window in the situation of the second image (when angle != 0
). Taking a look at the 4 vertices’ values, I see that:
vertex[2] {
x=-0.651163101
y=20.7524509
}
So y > boundarySize
. This shouldn’t be happening since the Clamp function was supposed to take care of this. What gives?
Maybe when I call SetPosition
, it only updates the box in the next iteration?
[ad_2]