T
T
Toshegg2015-02-19 22:18:38
Physics
Toshegg, 2015-02-19 22:18:38

How to move an object in a circle using rigidbody?

Hello!
There was such problem: I do particle simulation, and it is necessary for me that on mouse click the particle if it is in the set radius, began to rotate around the mouse pointer. I found a solution where movement happens by changing transform.position:

if (Input.GetMouseButton (1)) {
      timer += Time.deltaTime;
      transform.position = new Vector3 (2*Mathf.Cos(Mathf.Deg2Rad*timer), 2*Mathf.Sin(Mathf.Deg2Rad*timer), 0);
    }

But this solution does not suit me, because, firstly, other forces could act on the particle before the click, and I need it to move taking into account these forces, and secondly, so that it retains energy after the user releases the mouse.
It would be ideal to do this through AddForce.
It should be added that all the action takes place in a two-dimensional plane.
I would be grateful if you could help me write the code!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daniil Basmanov, 2015-02-20
@Toshegg

First drag the particle towards the mouse, and when it is close enough, drag it along the tangent of the desired orbit.

var toMouse = mousePosition - rigidbody.position;
if (toMouse.sqrMagnitude > sqrRadius)
{
    rigidbody.AddForce(toMouse);
}
else
{
    var velocity = rigidbody.velocity;
    Vector3.OrthoNormalize(ref toMouse, ref velocity);
    rigidbody.AddForce(velocity);
}

Vector3.OrthoNormalize will give you the direction of the tangent, you may need to specify a binormal.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question