Search Unity

Problem with Mathf.Clamp

Discussion in 'Scripting' started by HardPot, May 16, 2020.

  1. HardPot

    HardPot

    Joined:
    May 6, 2020
    Posts:
    3
    I have this piece of script where i clamp my game object position. my object should stop at 3.7 but it goes till 5.7 then clamps to 3.7.

    any Help would be appreciated!!
    Thank You in advance.
     

    Attached Files:

  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    Maybe put your Clamping line at the end of the method after you do your movement.
     
  3. HardPot

    HardPot

    Joined:
    May 6, 2020
    Posts:
    3
    Thanks Mate It Worked. But can you explain the logic behind this?
     
  4. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    If you set x = 3 on one line, and then a few lines later you set x = 7, then when you're done x has a value of 7. It only remember the most recent value. At the moment you say "x = 7" it forgets that x used to be 3.

    "Clamp" is just a fancy way of changing a variable's current value; it doesn't have any effect on what happens to that variable in the future. You could set the same variable to a billion on the very next line of code, and the fact that you clamped it a moment ago would become irrelevant.
     
  5. HardPot

    HardPot

    Joined:
    May 6, 2020
    Posts:
    3
    Thanks for explaining :) it was really helpful.