Search Unity

Can't convert mat2 to float2x2.

Discussion in 'Shaders' started by zero4444, Oct 10, 2021.

  1. zero4444

    zero4444

    Joined:
    Aug 14, 2017
    Posts:
    7
    Hi there, Sorry I'm new to shaders.
    I'm having trouble to converting a mat2 Type function(GLSL). I have normally seen vec2 functions, but I can't seem to find out how to call the equivalent float2x2(HLSL).

    GLSL
      mat2 Rot(float a) {
    float s = sin(a);
    float c = cos(a);
    return mat2(c, -s, s, c);
    }


    HLSL
        float2x2 Rot(float a) {
    float s = sin(a);
    float c = cos(a);
    return float2x2(c, -s, s, c);
    }


    OR
    float2 Rot(float a) {
    float s = sin(a);
    float c = cos(a);
    return float2x2(c, -s, s, c);
    }


    Function call:
      float map(float3 p){
    p.xy*=Rot(_Time*0.06);
    }


    Getting error:: "type mismatch at line xx" ie "p.xy*=Rot(_Time*0.06);"
    How do I rewrite the original mat2 function? This seem to run fine on GLSL. I think "rotate" is expecting float2 but that doesn't work.
     
    Last edited: Oct 10, 2021
  2. AcidArrow

    AcidArrow

    Joined:
    May 20, 2010
    Posts:
    11,794
    How is rotate defined? Why aren't you using Rot?

    I'm not sure what you want to do exactly, but here is how to rotate some vertices in a shader.

    Code (CSharp):
    1.             half4 Rotate (half4 vertex, half degrees) {
    2.                 half alpha = degrees * UNITY_PI / 180;
    3.                 half sina, cosa;
    4.                 sincos(alpha, sina, cosa);
    5.                 half2x2 m = half2x2(cosa, -sina, sina, cosa);
    6.                 return half4(mul(m, vertex.xy), vertex.zw).xyzw;
    7.             }
     
  3. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,352
    When you multiply a vector and a matrix together in GLSL you can do
    myVector *= myMatrix
    to get the equivalent of
    myMatrix * myVector
    .

    But in HLSL you don’t use the
    *
    operator for matrices this way. You instead need to use the
    mul()
    function to multiply matrices by vectors or vice versa. That also means there’s no
    *=
    operator where the right hand variable is a matrix, unless the left hand is also a matrix.

    So you’ll want:
    Code (CSharp):
    1. p.xy = mul(rotate(_Time.y * 0.06), p.xy);
    Also note Unity’s
    _Time
    is a
    float4
    where
    _Time.y
    is the unmodified game time.
     
    lovewessman and AcidArrow like this.
  4. zero4444

    zero4444

    Joined:
    Aug 14, 2017
    Posts:
    7
    Thanks, I meant to put in "p.xy*=Rot(_Time*0.06);" I don't think there's anything wrong with "Rot". I think I calling it incorrectly ""p.xy*=Rot(_Time*0.06)"
     
  5. zero4444

    zero4444

    Joined:
    Aug 14, 2017
    Posts:
    7
    WOW. Thanks. This worked. -> p.xy = mul(rotate(_Time.y * 0.06), p.xy);