In fact, the maximum speed limit in Box2D

I want to limit the maximum speed at which the body can travel.

The problem is that even if I am something like this answer suggests:

/* after applying forces from input for example */
b2Vec2 vel = body->GetLinearVelocity();
float speed = vel.Normalize();//normalizes vector and returns length
if ( speed > maxSpeed ) 
    body->SetLinearVelocity( maxSpeed * vel );

What if, for example, right before I pinch speed, I apply tremendous force to the body? Even if linear speed is limited by maxSpeed ​​at the moment, in the next timestep Box2D takes into account the value of b2Body :: m_force and effectively moves my body faster than maxSpeed.

So, I came up with this (I had to move the b2Body :: m_force file):

if ( speed > maxSpeed ) {
    body->SetLinearVelocity( maxSpeed * vel );
    body->m_force = b2Vec2(0, 0)
}

However, this still does not cope with the problem.

, , maxSpeed, , m_force , ?

, , , , -, , .

, Box2D?

+4
2

, , , , my - , n b2World::Step, n :

// source code taken form above link and modified for my purposes
for (int i = 0; i < nStepsClamped; ++ i)
{
    resetSmoothStates_ ();

    // here I execute whole systems that apply accelerations, drag forces and limit maximum velocities
    // ...
    if ( speed > maxSpeed ) 
         body->SetLinearVelocity( maxSpeed * vel );
    // ...

    singleStep_ (FIXED_TIMESTEP);

    // NOTE I'M CLEARING FORCES EVERY SUBSTEP to avoid excessive accumulation
    world_->ClearForces ();
}

, ( , ), <= maxSpeed. : , b2World::Step.

, , , , ,

  • Box2D\Dynamics\b2Body.h
  • float32 m_max_speed -1.f, .
  • Box2D\Dynamics\b2Island.cpp.
  • 222.
  • :

    m_positions[i].c = c;
    m_positions[i].a = a;
    
    if (b->m_max_speed >= 0.f) {
        float32 speed = v.Normalize();
        if (speed > b->m_max_speed)
            v *= b->m_max_speed;
        else v *= speed;
    }
    
    m_velocities[i].v = v;
    m_velocities[i].w = w; 
    

, , , , , .

+1

, . Box2D . , . , - normalImpulses tangentImpulses. , , b2BodyDef:: gravityScale. , - .

, box2d . , , , .

, box2d . , , . , Dynamics/b2Island.cpp: 219 (b2Island:: Solve) w v.

+1

All Articles