Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Unsure of a line of code used in a tutorial about applying gravity to a Kinematic Rigidbody2D

Discussion in 'Scripting' started by egonspengler_84, Jun 16, 2021.

  1. egonspengler_84

    egonspengler_84

    Joined:
    Jan 26, 2021
    Posts:
    153
    So I'm following a tutorial on how to apply gravity to a game object that has a Kinematic Rigidbody2D attached to it.

    Basically in the tutorial the tutor has a float variable called "gravityModifier" that acts as a way to modify the value of the gravity that is set within the game engine(Physics2D.gravity). So he has a Vector2 variable called velocity and he used the "+=" operator in order to store the modified gravity in the velocity variable.
    He then adds the value of velocity to the position of the Rigidbody2D which causes downward movement. However I don't understand why he needs to used Time.deltaTime twice in the code?

    Here is the code that is involved in the tutorial:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PhysicsObject : MonoBehaviour
    6. {
    7.  
    8.     public float gravityModifier = 1f;
    9.     public Vector2 velocity;
    10.     public Vector2 deltaPosition;
    11.     public Vector2 move;
    12.     private Rigidbody2D _rb;
    13.  
    14.     // Start is called before the first frame update
    15.     void Start()
    16.     {
    17.       _rb = GetComponent<Rigidbody2D>();
    18.  
    19.  
    20.     }
    21.  
    22.     // Update is called once per frame
    23.     void FixedUpdate()
    24.     {
    25.        velocity +=  gravityModifier * Time.deltaTime * Physics2D.gravity;
    26.        deltaPosition = velocity * Time.deltaTime;
    27.        move = Vector2.up * deltaPosition.y;
    28.      
    29.         _rb.position = _rb.position + move;
    30.  
    31.  
    32.  
    33.     }
    34.  
    35.  
    36. }
    37.  
    As you can see in the following lines he uses deltaTime twice but I don't understand why he needs to do so?:

    Code (CSharp):
    1. velocity +=  gravityModifier * Time.deltaTime * Physics2D.gravity;
    2. deltaPosition = velocity * Time.deltaTime;
    In the first line he's adding the value of gravityModifier multiplied by deltaTime multiplied by the value of gravity to the velocity variable. Then in the second line he's making the deltaPosition variable equal to velocity that is being multiplied by deltaTime. I don't understand why he needs to do this a second time if the value of deltaTime is stored within the velocity variable in the first line when it is being multiplied by gravityModifier and Physics2D.gravity?

    If it's any help here's a video of the actual tutorial:
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,756
    1. Because the velocity is being modified, it must only be modified proportionally to time passed.

    2. Because the position is being modified, it must only be modified proportionally to time passed.
     
  3. TheNightglow

    TheNightglow

    Joined:
    Oct 1, 2018
    Posts:
    201
    its just like physics for an accelerated movement, but simplified
    the position for accelerated movement is
    s = s_0 + v_0 * t + (a*t^2)/2

    so you will always get the time squared in your movement :)
     
  4. egonspengler_84

    egonspengler_84

    Joined:
    Jan 26, 2021
    Posts:
    153
    I don't understand at all. deltaPosition is basically the exact same thing as velocity in those two lines it's just that deltaPosition is being equaled to velocity multiplied by deltaTime.

    I don't even understand the purpose of the deltaTime variable?
     
  5. egonspengler_84

    egonspengler_84

    Joined:
    Jan 26, 2021
    Posts:
    153
    Is the equation you mention an example of a kinematic equation?

    The four kinematic equations that I'm aware of are the following that are shown in this image:https://ibb.co/Rj3b0YJ
    Is the equation you mentioned the third one shown in the image I linked?
     
  6. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,529
    That's incorrect. The velocity uses "+=" to change the velocity in a time-independent way but this just modifies velocity to its new value and it might be the same, decelerating or accelerating. This doesn't change position obviously so it's change velocity in a time-independent way.

    Now to change position you need to integrate velocity over that time-interval (Time.deltaTime - Still hate that shortcut) so you calculate how much of the velocity you're going to use for this update. Seems it's only interested in the vertical component of that but it's pretty simple.

    Just think about it. If you add to the position the velocity (let's say it's upwards and 10 meters/sec) without scaling by the elapsed timed you'll add 10 meters/sec per fixed-update here. If you have 50 fixed-updates/sec then in 1 second you'll move 500 meters and NOT 10 meters. Change your fixed-update to 100Hz and you'll move 1000 meters. Not what you want. This will happen because you're not adding the velocity scaled by the elapsed time.
     
  7. TheNightglow

    TheNightglow

    Joined:
    Oct 1, 2018
    Posts:
    201
    the equation i mentioned is the third one but not for the change in position but for the position itself

    and as the others also said, since you have an accelerated movement, not just your position changes over time, your velocity also needs to change over time (since it gets accelerated/ increased over time), and the position then changes over time based on the now changed velocity :)

    and for the purpose of deltaTime:
    if you do a movement completely independent of deltaTime it will still work fine but how fast something moves will be based on your frame count (because instead of a time based movement you would have a frame based movement)

    for instance in multiplayer, a player with high fps (frames per second) rate would move much faster than a player with a low fps (something Fallout 76 is notorious for ;) )

    thats why you want to scale your velocity by the passed time (deltaTime) within your frames
     
    MelvMay likes this.
  8. egonspengler_84

    egonspengler_84

    Joined:
    Jan 26, 2021
    Posts:
    153
    So you say that the relevant kinematic equation is the third one:
    changeInPosition = initialVelocity * time + (acceleration * time^2)/2

    However in your first message on this thread you wrote the equation in this way: s = s_0 + v_0 * t + (a*t^2)/2

    I understand what the other letters represent but what does the "s" and the "s_0" represent? Does "s" represent current position and "s_0" represents initial position?
     
  9. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,195
    changeInPosition in that equation is the
    v_0 * t + (a*t^2)/2
    part.


    But, in the simplest possible way, there's two instances of Time.deltaTime because:
    - acceleration happens over time
    - movement happens over time
     
  10. egonspengler_84

    egonspengler_84

    Joined:
    Jan 26, 2021
    Posts:
    153
    Code (CSharp):
    1.  velocity +=  gravityModifier * Time.deltaTime * Physics2D.gravity;
    2.        deltaPosition = velocity * Time.deltaTime;

    So are you saying that the first line refers to acceleration and the second line refers to movement? I thought velocity and acceleration were supposed to be different things? Are they the same in this context?
     
  11. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,195
    The first line is acceleration, the second line is velocity, yes. So they're not the same.

    And, I mean, they are different, but velocity is very much not independent from acceleration! Acceleration is change over time of velocity, velocity is change over time of position.
     
  12. TheNightglow

    TheNightglow

    Joined:
    Oct 1, 2018
    Posts:
    201
    well depends on your definition of "initial position", but yes, s_0 is the prior position, the position befor the change

    but... I just wanna say... the thing with your kinematic equations is that they are exchangeable and partly redundant....
    you derivate the velocity from the position, and the acceleration from the velocity
    (or in other words, the acceleration is basicly the velocity of the velocity as @Baste points out ;))

    if you simply exchange those equations around a little you get:
    v = v_0 + a * t
    aka
    v += a * t
    which is your first equation in the code

    and

    a = (v-v_0) / t
    which is your first kinematic equation but swapped to a
    substituting a in s(v_0, a, t) = s_0 + v_0 * t + (a*t^2)/2 to create s(v_0, v, t):
    s = s_0 + v_0 * t + ((v-v_0) / t * t^2)/2 //simplified (and ignoring the /2):
    s = s_0 + v_0 * t - v_0 * t + v * t //simplified:
    s = s_0 + v * t
    aka
    s += v * t
    which is the second equation in your code

    thus your 4 kinematic equations become:

    v += a * t
    s += v * t

    and in your case your a is:
    a = gravityModifier * Physics2D.gravity
     
    Last edited: Jun 17, 2021
  13. egonspengler_84

    egonspengler_84

    Joined:
    Jan 26, 2021
    Posts:
    153
    I don't understand what you mean when you say that velocity uses "+=" to change velocity in a "time independent" way? How is it being changed independent of time?
     
  14. TheNightglow

    TheNightglow

    Joined:
    Oct 1, 2018
    Posts:
    201
    see my post about the purpose of deltaTime and the difference between frame dependent changes and time dependent changes

    if you just "add" "something" to your velocity every frame using += then your movement is only dependent on the frame count, not the real time...
    so
    higher frame count --> faster velocity increase
    lower frame count --> slower velocity increase

    thats why you want to add to velocity your "something" multiplied by the passed time :)

    just to clarify, the "+=" is not the problem here, the point is that the operator alone does not result in a real time dependent behaviour
     
  15. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,529
    Change is refering to the fact that velocity is being changed (added to via "+="). The time specific comment was obviously because the change itself is scaled by the elapsed time.

    Given what's been said already above, I'd ignore my post as they cover it well.

    If it were me and I didn't understand, it'd ignore physics, Vector2 velocity or position. Just create a new script, and have a single float value then try to modify that per-frame so it increases by a fixed amount per second. This will reenforce the problem and solution.
     
  16. egonspengler_84

    egonspengler_84

    Joined:
    Jan 26, 2021
    Posts:
    153
    I know from school many years ago that velocity is the speed that an object is moving in a particular direction. And acceleration is the change of velocity over time?

    In the two lines that we're talking about the velocity variable is in simple terms having the value of gravity added to it every frame:
    Code (CSharp):
    1. velocity +=  gravityModifier * Time.deltaTime * Physics2D.gravity;
    2.        deltaPosition = velocity * Time.deltaTime;
    So I assume that because the first line has to do with the velocity variable being changed every frame that's the reason why it has more to do with acceleration?

    Whereas the second line is to do with the objects current position so that has more to do with velocity? Am I correct in thinking this? It's a bit confusing.
     
  17. TheNightglow

    TheNightglow

    Joined:
    Oct 1, 2018
    Posts:
    201
    just see my previous post where I show how your 4 kinematic equations become your 2 operations (v += a * t; s += v * t) by substituting one another^^

    s += v * t
    is just what happens when you substitute the acceleration in the formula
    s += v_0 * t + (a*t^2)/2
    using the formula
    v = v_0 + a * t <=> a = (v-v_0) / t
    (and ignore the division with 2 in the end)
     
  18. egonspengler_84

    egonspengler_84

    Joined:
    Jan 26, 2021
    Posts:
    153
    You say these things need to be modified proportionally to time passed so I would assume if I removed the "Time.deltaTime" part from the code it would not be modified to time passed?

    I know that Time.deltaTime is the interval from the last frame to the current one but I'm confused as to why this is necessary when the code is being executed within FixedUpdate rather than Update. Am I wrong to say that the code would be executed a guaranteed 50 times per frame(if the time step is set at 0.02)? I don't really understand why I need to use Time.deltaTime to make sure that the code would run smoothly if FixedUpdate guarantees that the code will run exactly 50 times per frame?
     
  19. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,529
    Do you really want to base all your constants such as speed as distance over "How many fixed updates per second" rather than distance over time? This is the question you have to ask yourself. Choose time because if you ever change FixedUpdate frequency then you'll move at a different speed. You don't change how long a second is so use that.
     
  20. TheNightglow

    TheNightglow

    Joined:
    Oct 1, 2018
    Posts:
    201
    well... while this is technically correct that in FixedUpdate anything you do is translateable to real time, its generally easier for humans to give and interpret acceleration and veleocity in second-based metrics

    lets say you want to make an object move at half a unit per second, if you were to use deltaTime you could simply insert a 0.5 in the inspector, if you dont use deltaTime you first need to calculate what 0.5 u/s would be within your fixed frame setting

    also if you ever change your fixed update frequency everything will get slower or faster

    also all the constants unity has assume a second-based time system, like Physics2D.gravity assumes seconds and not fixed frames
     
    egonspengler_84 likes this.
  21. egonspengler_84

    egonspengler_84

    Joined:
    Jan 26, 2021
    Posts:
    153
    My understanding is that the whole point of using Time.deltaTime is to make something change per second rather than based on the frames per second that the game is running at in a particular instance?

    So he's using Time.deltaTime because he wants both the value of velocity and the position to be modified PER SECOND as opposed to the values being modified per frame? Is this what you mean?
     
    Last edited: Jun 18, 2021
  22. egonspengler_84

    egonspengler_84

    Joined:
    Jan 26, 2021
    Posts:
    153
    Okay I understand what you mean regarding the usage of Time.deltaTime.
     
  23. egonspengler_84

    egonspengler_84

    Joined:
    Jan 26, 2021
    Posts:
    153
    Yeah I understand what you mean now.
     
  24. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,195

    yes
     
    egonspengler_84 likes this.