Search Unity

Why can't I use "equals" or "not equal" as a condition on a float

Discussion in 'Animation' started by BlaXun, Jan 13, 2015.

  1. BlaXun

    BlaXun

    Joined:
    Jan 8, 2015
    Posts:
    52
    Hello everybody,

    I just got started with animator and I got into a lil problem here.
    I started a 2D Jump n run engine.

    The char has animations for jump, walk and stand.
    I pass two float Parameters to my AnimationController

    xVelocity
    yVelocity

    When xVelocity is != 0 I want the Player to have the walking animation
    When yVelocity is < 0 or > 0 (you could say "does not equal 0") I want the jump animation to play.

    The problem is ...I can not use a "Equals" or "Not Equal" condition on float.
    Is my approach wrong? ...I don't quite get why I can not check if a float is equal / not equal to some value...however...with INT I can check this :(

    Thanks in advance
     
  2. Mecanim-Dev

    Mecanim-Dev

    Joined:
    Nov 26, 2012
    Posts:
    1,675
    Change your condition like this

    for the transition idle to walk, create 2 condition
    xVelocity Greater 0.1
    xVelocity Less -0.1

    for jump it almost the same thing too
    yVelocity Greater 0.1
    xVelocity Less -0.1

    There is no 'Equal' or 'Not equal' because float equality is not well define on the floating point unit, you can always have rounding error that make you believe that the current value is 0 but in fact it close to zero which make the condition fail even if what you see in the editor is 0.
     
  3. ArcaneTheWoof

    ArcaneTheWoof

    Joined:
    Jul 11, 2012
    Posts:
    3
    There IS a Mathf.Approximately() function though, so I'm not sure why Unity couldn't use that in the background for an Equals comparator in the animation, rather than make us have to do some jank like this~

    (Yes, I know this is a DEEP necro, but this thread is the first thing that pops up when you search for this issue on Google)
     
    DerDomme and Ishidres like this.
  4. icynotes

    icynotes

    Joined:
    May 17, 2017
    Posts:
    4
    A mild necro on a DEEP necro: converting the floats to bools based on their absolute value should work more cleanly for this:

    Code (CSharp):
    1. animator.SetBool("HasXVelocity", Mathf.Abs(xVelocity) > 0f);
    2. animator.SetBool("HasYVelocity", Mathf.Abs(yVelocity) > 0f);
     
    Alscenic likes this.
  5. Kybernetik

    Kybernetik

    Joined:
    Jan 3, 2013
    Posts:
    2,565
    Better yet:

    animator.SetBool("HasXVelocity", xVelocity != 0);

    Though the whole idea of arbitrarily dividing core game logic between scripts and a janky visual interface always seemed extremely foolish to me.
     
  6. LabOSM

    LabOSM

    Joined:
    Sep 5, 2019
    Posts:
    18
    Mathf.Approximately() almost never works reliably, for floats you have to define your own tolerances and use those to compare for equality