Search Unity

Is there a way to set the speed and/or max force of Rigidbody2D's .MovePosition?

Discussion in 'Physics' started by reppeti, Oct 20, 2021.

  1. reppeti

    reppeti

    Joined:
    Jun 29, 2021
    Posts:
    44
    Hello everyone!

    So I implemented a very basic drag and drop system that actually reponds to physics. Is there a way to somehow cap the speed and/or drag force of an object? I looked at

    My code sofar is:
    Code (CSharp):
    1. private void Awake()
    2.     {
    3.         cam = Camera.main;
    4.     }
    5.  
    6.     private void OnMouseDown()
    7.     {
    8.         dragOffset = new Vector2( transform.position.x, transform.position.y) - GetMousePos();
    9.     }
    10.     private void OnMouseDrag()
    11.     {
    12.         Vector2 stuff = GetMousePos() + dragOffset;
    13.         this.GetComponent<Rigidbody2D>().MovePosition(stuff);
    14.     }
    15.  
    16.     Vector2 GetMousePos()
    17.     {
    18.         var mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
    19.         mousePos.z = 0;
    20.         return mousePos;
    21.     }
    Is there any way to do the above mentioned things? The unity documentation shows no possible solutions for this.

    Wish everyone a nice day/evening!
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,491
    The body is not moving and there's no force, you're just instantly setting a new position (teleporting) so any capping of movement would be down to you.

    I would recommend using the TargetJoint2D for this as is demonstrated in my PhysicsExamples2D GitHub Project.

     
    reppeti likes this.