Home Game Development c++ – Clamping position and reflecting velocity of a box crashes when the box is angled

c++ – Clamping position and reflecting velocity of a box crashes when the box is angled

0
c++ – Clamping position and reflecting velocity of a box crashes when the box is angled

[ad_1]

I have a box object, which I created with Box2d. I set its angular velocity and angle to 0, so that it doesn’t rotate for now.

I’m checking every frame to see if the box is hitting the top of the screen and if it is, I clamp it and make it bounce in the opposite direction.

(also I know I should probably use the dot product here, but this is just a simple example with a linear velocity set to 0 in the x, and 7 in the y, so that the box only goes up or down).

Anyways, I do it like so:

void Game::ClampScreenY( Box* pBox)
{
    bool isColliding = false;
    auto pos = static_cast<b2Vec2>( pBox->GetPosition() );
    auto aabb = pBox->GetAABB();
    
    if( pos.y + boxSize >= boundarySize )
    {
        pos.y = boundarySize - boxSize;
        isColliding = true;
    }
    else if( pos.y - boxSize <= -boundarySize )
    {
        pos.y = -boundarySize + boxSize;
        isColliding = true;
    }

    if( isColliding )
    {
        auto vel = static_cast< b2Vec2 >( pBox->GetVelocity() );
        vel.y *= -1;
        pBox->SetVelocity( vel );
        pBox->SetPosition( pos );
    } 

Now this works if the box angle is 0 like in the following image:

screenshot of working case

This is fine, it works as expected.

But if I change the angle of the box to be different than 0 like so:

screenshot of failure case

My program crashes.

How can I fix this, and why exactly is this happening?

I thought about using an Axis Aligned Bounding Box and somehow work this through, I’m just not sure how to use the AABB to help me fix this issue.

edit

So I’ve try to make a quick edit:

if( aabb.upperBound.y >= boundarySize )
{
    pos.y = boundarySize - boxSize;
    isColliding = true;
}

but this ended up making the box with angle 0, which was bouncing fine until then, it’s stuck at the top now. Seems like this if-statement is always executing if I use the AAAB.

[ad_2]