0
\$\begingroup\$

I am trying to rotate my player along the centre of the world in Unity3D. All the tutorials and references I have looked through till now have left me to this working code:

void MoveAlongCurve(bool moveClockwise) {
    if (!moveClockwise)
        timeCounter += moveSpeed*Time.fixedDeltaTime;
    else
        timeCounter -= moveSpeed*Time.fixedDeltaTime;

    float x = Mathf.Cos (timeCounter);
    float y = Mathf.Sin (timeCounter);

    transform.position = new Vector3 (distFromCentre*x, distFromCentre*y,0);
}

Also this seems to work fine as well:

transform.RotateAround (Vector3.zero,new Vector3(0,0,1),speed);

Now my question is how do i move my player using velocity? I was forced to keep my body as 'kinematic rigidbody2D' however I want my player to be a 'dynamic rigidbody2D'.

My reason for this is several: 1. Movement via velocity makes it independent of the timeCounter. 2. Dynamic Bodies enable collisionDetection. Hence it is basically a requirement for my game.

Thank you so much for taking the time to read this! Any suggestions or nudges in the right direction would be greatly appreciated and if you find anything wrong in my code or approach please comment!

\$\endgroup\$
2

1 Answer 1

0
\$\begingroup\$

You can transform any arbitrary position change into a velocity:

Vector2 VelocityToReach(Vector2 destination) {
    Vector2 displacement = destination - body.position;
    return displacement/Time.fixedDeltaTime;
}
\$\endgroup\$
2
  • \$\begingroup\$ The code is working, but I don't understand why we are dividing the displacement by Time.fixedDeltaTime? More accurately, when I just return displacement the code does not work...As I understand it , it should still work but with a smaller speed, as displacement is indeed in the correct tangential direction! But my player seems to be going in an arcing semcircle trajectory! \$\endgroup\$ Commented Mar 22, 2018 at 8:13
  • \$\begingroup\$ Because velocity is movement: crossing through a distance, over time. The shorter your timestep, the faster your velocity needs to be to reach your destination in one step. \$\endgroup\$
    – DMGregory
    Commented Mar 22, 2018 at 11:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .