1
\$\begingroup\$

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");
             }        
      }
\$\endgroup\$
  • \$\begingroup\$ It looks ok at first glance. The debugDrawLine looks correct? What is the output on the second click? \$\endgroup\$ – karmington Feb 9 '14 at 22:29
  • \$\begingroup\$ The output is always correct. But the movement is not. :P \$\endgroup\$ – Daarwin Feb 9 '14 at 22:49
  • \$\begingroup\$ I notice you set target.z to 0 after drawing the debugLine, perhaps that could cause something. I suggest you print out the values and go step by step with pen and paper to make sure all the variables are what you'd expect. \$\endgroup\$ – karmington Feb 9 '14 at 23:13
2
\$\begingroup\$

This is the error:

player.rigidbody2D.AddForce (target * travelSpeed);

You are ignoring the players current position, which is why it only works once because the initial position is (0,0,0).

Use (target - player.transform.position) * travelSpeed instead.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.