Reputation: 260
Heyas there,
I am trying to achieve a gradient shader that rotates the color around the center, just like this one on shadertoy, but this one is a fragment shader
This is my first experience with shaders, and I've been studying for two days now, but I have trouble translating and getting used to many terms in linear algebra, and I haven't get a touch of it since native spoken school lessons.
So I have rotation matrix that I pass through a script:
public class RotationMatrix : MonoBehaviour
{
public float rotationSpeed = 10f;
public Vector2 texPivot = new Vector2(0.5f, 0.5f);
Renderer _renderer;
void Start()
{
_renderer = GetComponent<Renderer>();
}
protected void Update()
{
Matrix4x4 t = Matrix4x4.TRS(-texPivot, Quaternion.identity, Vector3.one);
Quaternion rotation = Quaternion.Euler(0, 0, Time.time * rotationSpeed);
Matrix4x4 r = Matrix4x4.TRS(Vector3.zero, rotation, Vector3.one);
Matrix4x4 tInv = Matrix4x4.TRS(texPivot, Quaternion.identity, Vector3.one);
_renderer.material.SetMatrix("_Rotation", tInv * r * t);
}
}
In a shader that rotates the vertices like this:
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
sampler2D _MainTex;
float4 _MainTex_ST;
fixed4 _Color;
fixed4 _Color2;
fixed _Scale;
float4x4 _Rotation;
struct v2f {
float4 pos : SV_POSITION;
fixed4 color : COLOR;
float2 uv : TEXCOORD0;
};
v2f vert(appdata_full v)
{
v2f o;
o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
v.texcoord.xy = mul(_Rotation, v.texcoord.xy);
o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
o.color = lerp(_Color, _Color2, v.texcoord.x * _Scale);
return o;
}
fixed4 frag(v2f i) : SV_Target
{
float4 color;
color.rgb = i.color.rgb;
color.a = tex2D(_MainTex, i.uv).a * i.color.a;
return color;
}
ENDCG
}
}
Note that this is really a Frankenstein code that I crafted up from tutorials and forum posts, as everything is new to me in Cg/HLSL.
Here is what I get: Sorry for the eye cancer
Thanks for your time.
Upvotes: 0
Views: 1416
Reputation: 861
It seems your code works just as expected, except that the rotation occurs around the origin of the UV coordinates of the quad (0,0), which is in a corner. Considering your UVs are normalized you just need to offset before and after the transformation.
side note on optim: you probably don't need to set the matrix from code every frame, you can just create it on the fly in the shader since you can access a global _Time parameter.
half2 Rotate2D(half2 _in, half _angle) {
half s, c;
sincos(_angle, s, c);
float2x2 rot = { c, s, -s, c };
return mul(rot, _in);
}
thus your rotationSpeed parameter can be a material constant
Upvotes: 1