Search Unity

Quick question on RigidBody.MovePosition()

Discussion in 'Physics' started by kavs, Aug 26, 2016.

  1. kavs

    kavs

    Joined:
    Jun 29, 2012
    Posts:
    25
    I'm following this tutorial and ran into something I wasn't sure of the answer to.
    https://unity3d.com/learn/tutorials/projects/survival-shooter/player-character?playlist=17144

    Code (csharp):
    1.  
    2. void Move (float h, float v)
    3. {
    4.     // Set the movement vector based on the axis input.
    5.     movement.Set (h, 0f, v);
    6.  
    7.     // Normalise the movement vector and make it proportional to the speed per second.
    8.     movement = movement.normalized * speed * Time.deltaTime;
    9.  
    10.     // Move the player to it's current position plus the movement.
    11.     playerRigidbody.MovePosition (transform.position + movement);
    12. }
    13.  
    In the example, the RigidBody is a child component of the player prefab. Does RigidBody.MovePosition update the parent object transform as well? It doesn't state it as such in the documention, but I was really confused as to how I was moving the parent when it felt like I was only moving the RigidBody.

    I noticed if I just wrote "this.transform.position += movement;" I got seemingly identitical effects, presumably because I moved the parent object and the RigidBody had to move with it? What's the difference between setting transform.position and RigidBody.MovePosition()?

    TL;DR: How does moving a child object move the parent? I assume RigidBody.MovePosition must update the parent object transform?

    BONUS: What's the difference between setting transform.position and RigidBody.MovePosition()?

    Thanks!
     
  2. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    899
    Unless there is a joint or something, moving a child shouldn't move the parent.

    Moving with transform.position is like teleporting an object. The physics engine can get "confused" and interactions with other objects might be weird. When you move an object with Rigidbody.MovePosition(), the object will interact with other physics objects along the "path" from the current position to the new position. If you try to move the object through an other object with a collider, it will stop. If you do the same thing using transform.position, your object will get stuck inside the obstacle, at least for a while until the physics engine squeezes them apart.
     
    finches likes this.