- Home /
Moving rigidbody2d towards mouse click using AddForce
I cant get my rigidbody2d game object to move to where i click the mouse. The first click works. The object travels to the mouse click and stops. But the second time (or the third time) i click the object travels in som direction but its not quite correct and it never reaches the target! What am i not getting right?
if (Input.GetMouseButtonDown (0)) {
var mouseClick = Input.mousePosition;
mouseClick.z = player.transform.position.z - Camera.main.transform.position.z;
target = Camera.main.ScreenToWorldPoint (mouseClick);
rotateToTarget = false;
travelToTarget = true;
print ("NEW TARGET: " + target);
Debug.DrawLine (Camera.main.transform.position, target, Color.red, 10f);
}
if (rotateToTarget == false && travelToTarget == true) {
var distanceToTarget = Vector3.Distance (player.transform.position, target);
if (distanceToTarget > 2) {
print ("Distance: " + distanceToTarget);
target.z = 0;
player.rigidbody2D.AddForce (target * travelSpeed);
} else {
travelToTarget = false;
print ("travelling COMPLETE");
}
}
Answer by MaGuSware™ · Feb 10, 2014 at 12:09 AM
player.rigidbody2D.AddForce (target * travelSpeed); <-- this is where you are going wrong.
You need to get the direction of the target in relation to the object, so you need to do some basic 2d vector math, subtract your position from the target position... then normalize it.
In C#
Vector2 direction = (target.transform.position - player.transform.position).normalized;
player.rigidbody2D.AddForce (direction * travelSpeed);
I should probably also mention that travel speed doesn't equal force in that way so it might give you undesired results depending on what your players mass is.
Brilliant $$anonymous$$aGuSware - that resolved my problem I had too when trying to implement "fake" gravity in 2d. now when I launch ships they correctly follow the pull of gravity.
When I try this I get a notice in monodeveloper that target(Vector 3) has no method transform.
Thank you so much! I've been working on this for days!
Your answer
Follow this Question
Related Questions
Rotate towards velocity (2D) 2 Answers
Connecting SpringJoint2D to Rotating Rigidbody2D With Correct Anchor 0 Answers
Ignore sub-colliders for center of mass in Rigidbody2d? 1 Answer
Platformer2D Player sticks to platform corners 0 Answers
increasing knockback of a rigidbody as received damage increases (like super smash) 1 Answer