0
\$\begingroup\$

I would like to move a object towards Vector2(0, 0), but every time I use this script, the object always goes down, instead of going towards the center of the coordinate system.

        void Update()
         {
    //Object rotation
             if (!Input.GetMouseButtonDown(0))
             {
                 _angle += speed * Time.deltaTime;
                 var offset = new Vector2(Mathf.Sin(_angle), Mathf.Cos(_angle)) * radius;
                 transform.position = _centre + offset;
             } else
             {
//Moving object towards center
                 rb.transform.position = Vector2.MoveTowards(transform.position, Vector2.zero, speed * Time.deltaTime);
             }
\$\endgroup\$
0
\$\begingroup\$

Your objects rigidbody is being affected by gravity. Either set the rigidbody's type to Kinematic in the inspector, or set the gravity to zero from Edit --> Project Settings --> Physics2D --> Gravity

Note:I assume you are working on 2D. Hope this helps!

\$\endgroup\$
4
  • \$\begingroup\$ Thank you for your answer, but that was not the issue. The problem is that whenever I press the mouse button, my object moves only along the Y-axis and I would like the object to move towards the 0, 0 point. \$\endgroup\$
    – John
    Jun 3 '17 at 18:20
  • \$\begingroup\$ Did you try the solution? Because I have directly copied and pasted your code, only switched _centre with Vector2.zero and if I don't set the rigidbody to kinematic, it starts to fall down on Y-Axis. But when I set the body to kinematic, it starts to move towards center. Try to change the GetMouseButtonDown(0) to GetMouseButton(0) to see the effect clearly. \$\endgroup\$
    – Tolga Şen
    Jun 3 '17 at 18:36
  • \$\begingroup\$ Thanks to your answer I solved it, thank you. And I was wondering how can I send the object towards the center, but if it collides with an object on its way to the center, it stops? Right now it collides but it also ends up in the center, because I send it to 0, 0, so is there a way to fix that? \$\endgroup\$
    – John
    Jun 3 '17 at 21:14
  • \$\begingroup\$ You can use a trigger collider and surround the movement code with a boolean flag. And inside the OnTriggerEnter2D() function, set that boolean to false inorder to cancel movement. \$\endgroup\$
    – Tolga Şen
    Jun 3 '17 at 23:31

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.