Search Unity

Make rigidbody keep its velocity

Discussion in 'Physics' started by kqmdjc8, Aug 19, 2019.

  1. kqmdjc8

    kqmdjc8

    Joined:
    Jan 3, 2019
    Posts:
    86
    Hello. I've made a simple script which lets me drag a rigidbody with my mouse. When I release mouse button rigidbody loses it's momentum and stops instantly. How do I convince a rigidbody that it has velocity and needs to lose some speed before instantly stopping?
     
  2. kqmdjc8

    kqmdjc8

    Joined:
    Jan 3, 2019
    Posts:
    86
    (To move a rigidbody I am using rb.MovePosition)
     
  3. Edy

    Edy

    Joined:
    Jun 3, 2010
    Posts:
    1,548
    Move it with AddForce in ForceMode.VelocityChange.

    While the mouse button is pressed you have to compute the velocities that keep the rigidbody under the cursor. When the mouse button is released then the rigidbody would remain with the velocity it had at that time.
     
    kqmdjc8 likes this.
  4. kqmdjc8

    kqmdjc8

    Joined:
    Jan 3, 2019
    Posts:
    86
    Thank you. I thought that computing velocity would be hard but now I see that it is just difference of position in 2 frames.
     
    Edy likes this.
  5. kqmdjc8

    kqmdjc8

    Joined:
    Jan 3, 2019
    Posts:
    86
    Hey. Tried to implement this and I think that I am missing something. This is how I calculate velocity:

    Code (CSharp):
    1. public void CalculateVelocity()
    2.     {
    3.         prevPos = newPos;
    4.         newPos = clickedObject.transform.position;
    5.         velocity = newPos - prevPos;
    6.     }
    On releasing mouse button I am giving rigidbody this computed velocity and it doesn't work. I mean it does work but velocity is super small like 0.01 on X axis. Tried to give a rigidbody just constant Vector3(1,0,0) velocity and it works well, the speed looks real. What am I doing wrong?

    EDIT: multiplying computed velocity by 100 seems to give quite realistic results, but I guess there is a better way to do this
     
    Last edited: Aug 20, 2019
  6. koirat

    koirat

    Joined:
    Jul 7, 2012
    Posts:
    88
    should be " velocity = (newPos -prevPos)/dTime " where dTime is time between prevPos and newPos.


    Alos move prevPos = newPos; to the end.
     
    kqmdjc8 likes this.