Search Unity

Question Update and FixedUpdate changing the same var

Discussion in 'Scripting' started by yaireren, Apr 12, 2021.

  1. yaireren

    yaireren

    Joined:
    Dec 20, 2020
    Posts:
    1
    Hi All
    I am trying to wrap my head around this issue:
    I have a variable that control the direction of movement which is changes in two scenarios:
    1) According to player Input:
    Code (CSharp):
    1.   if (Input.GetButtonDown("Up"))
    2.         {
    3.             if (yDirection == -1)//down
    4.                 yDirection = 1; //change to up
    5.             else //we go up
    6.                 xDirection *= -1;//change the x direction
    7.          
    8.         }
    9.         else if (Input.GetButtonDown("Down"))
    10.         {
    11.             if (yDirection == 1)//we go up
    12.                 yDirection = -1; // change to down
    13.             else //we go down
    14.                 xDirection *= -1; //change the x direction
    15.          }
    16.  
    2) When the game object gets to a point:
    Code (CSharp):
    1. if (transform.position.y < (-4.18f) || transform.position.y > 4.37f)
    2.         {
    3.                 yDirection *= -1;        
    4.         }
    5.         if (transform.position.x < (-7.4f) || transform.position.x > 7.39f)
    6.         {
    7.                   xDirection *= -1;    
    8.         }
    According to my understanding, the first code should be in the Update method cause we dealing with inputs, while the second should be in FixedUpdate. But those lines changes the same var that eventually goes to this line:
    Code (CSharp):
    1.   transform.Translate(xySpeed * (float)xDirection * Time.deltaTime, xySpeed * (float)yDirection * Time.deltaTime, 0);
    2.         }
    Would it be glitchy?
    And where should i put the transform.Translate line?

    Thanks in advance!
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,700
    The only time you need FixedUpdate is if you're using Physics, eg, Rigidbody or Rigidbody2D.

    If you're NOT using physics, do NOT use FixedUpdate.

    And if you are using Physics, you must NOT move things by using .Translate() or setting the .position field directly.

    Instead you must use the .MovePosition() method on Rigidbody.

    The reason: setting the position outside of MovePosition constitutes a "teleport" and you will surprise the physics system and cause glitchy movement.
     
    yaireren likes this.