Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

make a GameObject perfectly copy another GameObject's position with AddForce?

Discussion in 'Scripting' started by ml785, Jan 23, 2021.

  1. ml785

    ml785

    Joined:
    Dec 20, 2018
    Posts:
    119
    Does anyone know how to make a GameObject perfectly copy another GameObject's position with AddForce? (MovePosition causes massive stuttering for some reason.)

    This causes it to follow the original object with a delay, rather than exactly be on top of it.


    Code (CSharp):
    1.  private void FixedUpdate() {
    2.        rb.AddForce(targetTransform.transform.position - this.transform.position, ForceMode.Acceleration);
    3. }

    In case anyone's curious, the stuttering MovePosition code is:



    Code (CSharp):
    1.   private void FixedUpdate()
    2.     {
    3.         rb.MovePosition(targetTransform.position);
    4.         rb.MoveRotation(targetTransform.rotation);
    5.     }
    6. }
    It causes the object to fly and blink around rapidly even though it's the only Rigidbody in the scene and even if I choose 'Interpolate'. Crazy stuff. So that's why I'm trying to use AddForce instead...
     
  2. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    It's moving like that because MovePosition with "Interpolate" moves it smooths between frames, it's not a "go here smoothly over time" function.

    try this
    Code (CSharp):
    1.         rb.MovePosition((targetTransform.position - myTransform.position).normalized * speed * deltaTime);
    2.