Search Unity

Best way to get object rotation

Discussion in 'Shaders' started by OndaOmar, Dec 15, 2014.

  1. OndaOmar

    OndaOmar

    Joined:
    Dec 15, 2014
    Posts:
    2
    I am attemting an unlit shader that color tints an object depending on its relation to the world axis. As an example, any normals of a rotating object facing the world-x axis would get tinted with agreen color.

    1. Is there any optimized way to get the world rotation from within the shader?

    2. Would it be better/(more optimized) to supply it as a parameter through code to the shader?
     
    Last edited: Dec 15, 2014
  2. GGeff

    GGeff

    Joined:
    Nov 11, 2014
    Posts:
    40
    Sounds like you don't need a shader, you just need a script that modifies the objects material based on its rotation.
     
  3. niko-belic

    niko-belic

    Joined:
    Sep 1, 2012
    Posts:
    67
    example in shader

    Code (CSharp):
    1. Properties {
    2. _RotationSpeed ("Rotation Speed", Float) = 2.0  
    3. }
    4.  
    5.      float sinX = sin ( _RotationSpeed * _Time );
    6.  
    7.             float cosX = cos ( _RotationSpeed * _Time );
    8.  
    9.             float sinY = sin ( _RotationSpeed * _Time );
    10.  
    11.             float2x2 rotationMatrix = float2x2( cosX, -sinX, sinY, cosX);
    12. }
    example : JS script :

    Code (JavaScript):
    1. var scrollSpeed = 0.90;
    2. var scrollSpeed2 = 0.90;
    3. function FixedUpdate()
    4. {
    5. var offset = Time.time * scrollSpeed;
    6. var offset2 = Time.time * scrollSpeed2;
    7. renderer.material.mainTextureOffset = Vector2 (offset2,-offset);
    8.  
    9. }
     
  4. OndaOmar

    OndaOmar

    Joined:
    Dec 15, 2014
    Posts:
    2
    @GGeff: If I was not dependent on the objects normals, a script would work. I think I would avoid iterating through all those meshes normals in script if I can put that work on the gpu instead.

    @Niko-belik: Thanks, but not quite what I am looking for. I need some way to get the rotation relation between the vertex normal and the world axis.
     
  5. OndaOmar

    OndaOmar

    Joined:
    Dec 15, 2014
    Posts:
    2
    Aha! Found what I was looking for, and ironically it brought me back to where I first started, with _Object2World. The reason it did not work before was the order:

    Code (CSharp):
    1.  
    2. //correct:
    3. normalize(mul((float3x3)_Object2World, i.normal).xyz);
    4.  
    5. //incorrect:
    6. normalize(mul(i.normal, ((float3x3)_Object2World).xyz);
    7.  
    The effect was that I no longer got the proper rotation of the normal if I had the wrong order. I hope anyone following in my footsteps can benifit from this.