Search Unity

Mathf.PingPong inside a FixedUpdate not smooth

Discussion in 'Scripting' started by AlexandreH5, Sep 11, 2019.

  1. AlexandreH5

    AlexandreH5

    Joined:
    Sep 24, 2013
    Posts:
    24
    Hello guys,

    I want to use this part of code.
    Code (CSharp):
    1.     void FixedUpdate () {
    2.         if (IsStun == false) {
    3.             if (CameraScreenShotMap.activeSelf == false) {
    4.                 GetComponent<Rigidbody> ().position = Vector3.Lerp (StartPosition, EndPosition, Mathf.PingPong (Time.time / PatrolSpeed, 1f));
    5.             }
    6.         }
    7.     }
    The problem is that the patrol is not smooth. it jerks a little. I need to do a fixedupdate patrol that's why I do not put it in update and in addition it's a rigidbody.

    Thank you.

    Alexandre
     
  2. Boz0r

    Boz0r

    Joined:
    Feb 27, 2014
    Posts:
    342
    Line breaks are not your enemy and please cache your GetComponent call. :)

    How does it look if you put it in Update instead?
     
  3. AlexandreH5

    AlexandreH5

    Joined:
    Sep 24, 2013
    Posts:
    24
    Thank you for the reply :)

    Everything is working now with Update method. My bad!
     
  4. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    6,340
    The issue probably has to do with FixedUpdated getting called unrelated to frame rate. FixedUpdate can be called several times or 0 times between frames.
     
    Ryiah likes this.
  5. cmyd

    cmyd

    Joined:
    Oct 29, 2017
    Posts:
    26
    It has to do with the FPS, let me explain, by default FixedUpdate() is called every 0.02 seconds.
    Here you have two problems, Never use GetComponenet often, if you need to often cache it,
    Code (CSharp):
    1. RigidBody myRigidBody = GetComponent<RigidBody>();
    believe it or not but this will have noticeable difference in the FPS.
    The Second problem is in
    Code (CSharp):
    1. Vector3.Lerp (StartPosition, EndPosition, Mathf.PingPong (Time.time / PatrolSpeed, 1f));
    You need to multiply your 3rd parameter with Time.fixedDeltaTime;

    Code (CSharp):
    1. Vector3.Lerp (StartPosition, EndPosition, Mathf.PingPong (Time.time / PatrolSpeed, 1f) * Time.fixedDeltaTime);
    Note: In Update() you should use Time.deltaTime instead of Time.fixedDeltaTime.