Search Unity

Moving kinematic objects... Update or FixedUpdate?

Discussion in 'Scripting' started by SVC-Games, Sep 29, 2015.

  1. SVC-Games

    SVC-Games

    Joined:
    May 21, 2013
    Posts:
    137
    Hi all,

    I already know that "only physics related operations should be in fixedupdate" and that's nice when using functions such as "AddForce" (IE: 2D characters in unity demos)

    But if I want to actually move a character/object altering it's transformation?

    I've created a quick and dirty script for moving two objects when pushing some keys:
    Code (CSharp):
    1.  
    2.     void Update () {
    3.         if(PlayerId == 0)
    4.         movePlayer(false);
    5.     }
    6.  
    7.     void FixedUpdate()
    8.     {
    9.         if(PlayerId == 1)
    10.         movePlayer(true);
    11.     }
    12.  
    13.     void movePlayer(bool usingFixedTime)
    14.     {
    15.         float transformX = 0;
    16.         float transformY = 0;
    17.      
    18.         if (usingFixedTime)
    19.         {
    20.             if (Input.GetKey(b_left[0])) { transformX = -speed * Time.fixedDeltaTime; }
    21.             if (Input.GetKey(b_right[0])) { transformX = speed * Time.fixedDeltaTime; }
    22.             if (Input.GetKey(b_up[0])) { transformY = speed * Time.fixedDeltaTime; }
    23.             if (Input.GetKey(b_down[0])) { transformY = -speed * Time.fixedDeltaTime; }
    24.         }
    25.         else
    26.         {
    27.             if (Input.GetKey(b_left[0])) { transformX = -speed * Time.deltaTime; }
    28.             if (Input.GetKey(b_right[0])) { transformX = speed * Time.deltaTime; }
    29.             if (Input.GetKey(b_up[0])) { transformY = speed * Time.deltaTime; }
    30.             if (Input.GetKey(b_down[0])) { transformY = -speed * Time.deltaTime; }
    31.         }
    32.  
    33.         this.transform.position += new Vector3(transformX, 0, transformY);
    34.     }
    I notice that moving the object within fixed update cause sttutering (because it doesn't always match the screen frame rate). Should I move objects in Update, even though they have a rigidbody attached?
     
  2. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,334
    Don't set transform.position on physics objects, as it causes a bunch of overhead due to recalculations happening in the background.

    Instead, use Rigidbody.MovePosition. According to the docs, that also does interpolation, so things will look smooth, and you can put your behaviour in FixedUpdate, where physics objects should be moved.

    Also note that your code can be simplified; Time.deltaTime is set to the fixedDeltaTime when inside of a FixedUpdate, so you'll see the exact same results if you remove the usingFixedTime bool.
     
  3. SVC-Games

    SVC-Games

    Joined:
    May 21, 2013
    Posts:
    137
    Thanks for the reply. It was just some dirty code for the example. Thank you for your advice :D