Box2D Forums

It is currently Thu May 23, 2013 1:41 am

All times are UTC - 8 hours [ DST ]




Post new topic Reply to topic  [ 3 posts ] 
Author Message
PostPosted: Sun Feb 12, 2012 5:04 am 
Offline

Joined: Sat Jan 28, 2012 11:13 am
Posts: 6
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:
    // 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.


Top
 Profile  
 
PostPosted: Sun Feb 12, 2012 8:42 am 
Offline

Joined: Tue Jun 24, 2008 8:25 pm
Posts: 1517
Location: Tokyo
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:
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


Top
 Profile  
 
PostPosted: Sun Feb 12, 2012 10:23 am 
Offline

Joined: Sat Jan 28, 2012 11:13 am
Posts: 6
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.


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 3 posts ] 

All times are UTC - 8 hours [ DST ]


Who is online

Users browsing this forum: No registered users and 2 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
Powered by phpBB® Forum Software © phpBB Group