"Grabbing" bodies - are there better ways than what I have?

I'm working on a 2D game engine, and I would like to have something that allows you to "grab" bodies.
So far, my idea works a bit like this:

Set an AABB that contains the mouse coordinates to within 25 square pixels.

Code:
b2AABB Bounds;
Bounds.upperBound.Set(xmouse + 2.5, ymouse + 2.5);
Bounds.lowerBound.Set(xmouse - 2.5, ymouse - 2.5);


Get the closest bodies that might intersect those bounds.

Code:
b2Shape * Buffer[4]; // We don't want to have to calculate this for very many shapes.
int num = World->Query(Bounds, Buffer, 4);
float mDist = -1;
b2Body * Cur = 0;
for (int i = 0; i < num; i++)
{
    float t = distance ( Buffer[i]->GetBody()->GetPosition(), b2Vec2 ( xmouse, ymouse ) );
    if ( mDist == -1 || t < mDist )
    {
        Cur = Buffer[i]->GetBody();
        mDist = t;
    }
}


Then set some data to store that body and it's current/starting angle and the distance from it to the mouse.

Code:
myPointer = Cur;
TheDistance = mDist;
TheAngle = atan2 ( (Cur->GetPosition().y - ymouse), (Cur->GetPosition().x - xmouse) );
LastAngle = Cur->GetAngle();
BodyGrabbed = true;


Then on the update event, test and see if a body is being gripped. If it is, apply forces to the body.

Code:
if ( BodyGrabbed )
{
    TheAngle += (myPointer->GetAngle() - LastAngle);
    myPointer->AddForce ( b2Vec2 ( cos ( direction([you know the drill]) ) * TheForceIWantToApply, sin ( direction(...) ) * TheForceIWantToApply ),
    b2Vec2 ( cos ( TheAngle ) * TheDistance, sin ( TheAngle ) * TheDistance ) );
}


Note: I also have a scale between the physics positions and the pixel coordinates, so don't worry about things being too large. 🙂

I haven't tested this but it seems like it will work, I will run a test a bit later and see how it goes. Are there any better ways than this?

If so, please post a reply with your way and I will see which one works better.

Thanks,
Sgt. Sparky

😀
Maybe I'm misunderstanding you, but... it sounds like you're reinventing the mouse joint, which works just fine.
mayobutter wrote:
Maybe I'm misunderstanding you, but... it sounds like you're reinventing the mouse joint, which works just fine.


There is a mouse joint? :O
I didn't know that.

Thanks for telling me. 😀
No problem. BTW, if you want the mouse joint to freeze rotation as well, you can just use two mouse joints, one offset a large distance from the mouse position.

Original thread: https://box2d.org/forum/viewtopic.php?t=1657