Search Unity

Question on OnTriggerStay2D and use or not use of time.fixeddeltaTime

Discussion in 'Scripting' started by Devastadus, Jan 20, 2021.

  1. Devastadus

    Devastadus

    Joined:
    Jan 27, 2015
    Posts:
    80
    So i making a 2D spaceship game using the built in physics engine Rigidbody2D and i want my ship to boost. when hitting an area. it works but some questions on Unity - Scripting API: MonoBehaviour.OnTriggerStay2D(Collider2D) (unity3d.com)

    It has the following code.
    Code (CSharp):
    1. void OnTriggerStay2D(Collider2D other)
    2.     {
    3.         other.attachedRigidbody.AddForce(-0.1F * other.attachedRigidbody.velocity);
    4.     }
    Shouldn't have a Time.fixedDeltaTime in it to be framerate independent? wouldn't it give inconsistent results on the speed of the computer? Shouldn't it be the following

    Code (CSharp):
    1. void OnTriggerStay2D(Collider2D other)
    2.     {
    3.         other.attachedRigidbody.AddForce(-0.1F * other.attachedRigidbody.velocity *Time.fixedDeltaTime);
    4.     }
    Also looking at the unity runtime execution order. onTriggerXXX happen in the physics cycle. I'm just curious. why it is written that way and if there are issues or not
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,911
    No. OnTriggerXXX functions run as part of the physics update. This means they are simulated at a fixed rate, just like FixedUpdate().

    Besides, Time.fixedDeltaTime is a constant value (doesn't change frame to frame like Time.deltaTime), and therefore would not be suitable for doing variable-framerate adjustment.
     
    Devastadus likes this.
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    The general rules for using delta or not is this:

    - if YOU are doing the movement calculation, then YOU should multiply by the delta time.

    - if you expect the PHYSICS engine to move stuff, then do NOT multiply by delta time

    The first would apply in the case of changing positions in code and calling .MovePosition()

    The second would apply to AddForce, AddTorque, velocities, etc.
     
    Devastadus and PraetorBlue like this.
  4. Devastadus

    Devastadus

    Joined:
    Jan 27, 2015
    Posts:
    80
    Whoa thanks i was doing it wrong all along.
     
    Kurt-Dekker likes this.