ApplyLinearTransform help

Hello,

I have an object on the layer. When a user touches a place on the screen I want the object to have an initial force applied and head in that direction. I just can't get my head around the vector maths to apply the force in the right direction.

Here is a diagram with an example what I am trying to achieve:
http://imgur.com/uCXuq


Code: Select all

    // Need to apply a force between the object current location and where the user clicked.
    b2Vec2 force = b2Vec2(clickLocation.x/PTM_RATIO, clickLocation.y/PTM_RATIO);
    gameObject.body->SetLinearVelocity(force);



The setLiniearVelocity seems to apply the force I require but there is one huge flaw, the objects ALWAYS go to the right. If I click left to the object I want the object to go left. I think the problem is I am always passing a positive vector in.
You are using the touch location as a direction.... it's not a direction, it's only a location!
To get the direction from the body to the touch location you could try something like:

Code: Select all

b2Vec2 touchPos(clickLocation.x/PTM_RATIO, clickLocation.y/PTM_RATIO);
b2Vec2 fromBodyToTouch = touchPos - body->GetPosition();
float distanceFromBodyToTouch = fromBodyToTouch.Normalize();//makes the vector length 1, returns the original length
float power = ... whatever ...; //maybe use the distance to alter the power?
b2Vec2 forceToApply = power * fromBodyToTouch;
body->ApplyForce( forceToApply, body->GetWorldCenter() );//or ApplyLinearImpulse, or SetLinearVelocity
You are incredible, thank you irresistible force. You helped me with a previous problem I was having with cocos2d aswell 🙂

Thank you so much. Keep up the good work for replying when others are not.

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