Search Unity

Question [SOLVED] Rounding Time not working in HLSL.

Discussion in 'Shaders' started by TRDP90_, Dec 2, 2022.

  1. TRDP90_

    TRDP90_

    Joined:
    Jan 12, 2021
    Posts:
    3
    Hi everyone,

    I'm having an issue with rounding time.
    I want to have a stepping effect when I shift my textures like a stop motion effect.

    Normally its done like:

    i.normal_uv.x += _Time.y*0.1;

    This works properly.


    However when I round time for a stepping effect:

    i.normal_uv.x += round(_Time.y*0.1);

    It does not move at all.


    i.normal_uv.x += round(_Time.y)*2.5;

    But this works properly. However, I can't increase the speed (multiplier at 2.5).

    This method should work like my attempt in shadergraph.
    Casting to int or truncating does not work. Neither does a manual floor or ceil conversion to simulate truncation/rounding.

    Does anyone have a fix?

    Thanks!:)
     
  2. Invertex

    Invertex

    Joined:
    Nov 7, 2013
    Posts:
    1,546
    Rounding like that is going to result in the UV only ever shifting over a full UV range, thus no noticeable change will be seen unless the UVs map was setup in a manner that spanned several UV spaces.
    If in the import settings on your texture you set Repeat to "Clamp", you'd notice your texture would probably become black after the first frame.

    So rounding to a whole number is not what you want, you'll want to do some sort of fractional rounding. You can get the integer and fractional part of the number. Multiply the fractional by your step amount, floor it, divide it by your step, then add it back to the integer and finally add that result to the UV.

    Code (CSharp):
    1. float whole = trunc(_Time.y);
    2. float fractional = frac(_Time.y);
    3. fractional = floor(fractional * _Step) / _Step;
    4. i.normal_uv.x += whole + fractional;
     
    Last edited: Dec 2, 2022
    TRDP90_ likes this.
  3. TRDP90_

    TRDP90_

    Joined:
    Jan 12, 2021
    Posts:
    3
    This works!
    Thanks for the explanation :)
    May I know why you divide the fractional by the step number ? Is it to turn it back to a float with a fractional value? I understand floor as a conversion to the lower integer.
     
  4. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,338
    UVs display a texture between a 0.0 to 1.0 range. Outside of that range by default it repeats the texture as if it's being displayed with only the fractional part of the UV. So if you add to the UV with an integer, nothing will happen (at least until the UVs start to break down due to floating point precision). You have to add a fractional to the UV if you want to see anything change.
     
    TRDP90_ likes this.