Calculate correct impluse or force to move a Box2D body to a specific position - Box2D

前端 未结 2 372
终归单人心
终归单人心 2021-01-07 07:12

i have a question about moving a Box2D body to a specific position without using this for example.

body->SetTransform(targetVector,body->GetAngle())
<         


        
2条回答
  •  再見小時候
    2021-01-07 08:00

    I think you have it mostly correct, but you are not checking to see if the body will overshoot the target in the next time step. Here is what works for me:

    b2Vec2 targetPosition = ...;
    float targetSpeed = ...;
    
    b2Vec2 direction = targetPosition - body->GetPosition();
    float distanceToTravel = direction.Normalize();
    
    // For most of the movement, the target speed is ok
    float speedToUse = targetSpeed;
    
    // Check if this speed will cause overshoot in the next time step.
    // If so, we need to scale the speed down to just enough to reach
    // the target point. (Assuming here a step length based on 60 fps)
    float distancePerTimestep = speedToUse / 60.0f;
    if ( distancePerTimestep > distanceToTravel )
        speedToUse *= ( distanceToTravel / distancePerTimestep );
    
    // The rest is pretty much what you had already:
    b2Vec2 desiredVelocity = speedToUse * direction;
    b2Vec2 changeInVelocity = desiredVelocity - body->GetLinearVelocity();
    
    b2Vec2 force = body->GetMass() * 60.0f * changeInVelocity;
    body->ApplyForce( force, body->GetWorldCenter(), true );
    

提交回复
热议问题