Posted by: Morten Nobel-Jørgensen | September 17, 2011

Mirror texture coordinates in Unity


In Unity there is two settings of a texture UV mode: Repeat: simply repeat that the textures (usable for tileable texture images) and Clamp: clamps the UV coordinates to  a value between 0.0 and 1.0. In this blog I’ll show how to get a third option: Mirror: mirrors the texture whenever the UV crosses a integer number.

The three UV texture modes are:

Even though Unity’s texture import settings only has the repeat and clamp, it is very easy to get a mirror effect as well. All it takes is to create a new shader that mirrors the texture coordinates before looking up in the texture.

To create a mirror effect you can use the following cg-code:

// makes the UV repeat between 0.0 and 2.0
float2 t = frac(IN.uv_MainTex*0.5)*2.0; 
float2 length = {1.0,1.0};
// compute the mirror effect
float2 mirrorTexCoords = length-abs(t-length); 

I have created a diffuse shader with the mirrored UV coordinates (it is based on “Normal-Diffuse.shader” from Builtin Unity Shaders):

Shader "Custom/DiffuseUVMirrowShader" {
Properties {
	_Color ("Main Color", Color) = (1,1,1,1)
	_MainTex ("Base (RGB)", 2D) = "white" {}
}
SubShader {
	Tags { "RenderType"="Opaque" }
	LOD 200

CGPROGRAM
#pragma surface surf Lambert

sampler2D _MainTex;
float4 _Color;

struct Input {
	float2 uv_MainTex;
};

void surf (Input IN, inout SurfaceOutput o) {
	// makes the UV repeat between 0.0 and 2.0
	float2 t = frac(IN.uv_MainTex*0.5)*2.0; 
	float2 length = {1.0,1.0};
	float2 mirrorTexCoords = length-abs(t-length); 
	// compute the mirror effect
	half4 c = tex2D(_MainTex,  mirrorTexCoords) * _Color;
	o.Albedo = c.rgb;
	o.Alpha = c.a;
}
ENDCG
}

Fallback "VertexLit"
}
Advertisement

Responses

  1. execuse me, but seems your image is missed, i can not see the images, but only the words.

  2. Hi there,

    Thanks so much for posting this code and also for posting your answer in the unity answers forum. Your example is the only one I’ve found so far to help with this issue.

    I really need this mirroring functionality in a game that I’m designing, and I’m trying to recreate you code in a node-based shader editor (Shader Forge). I’m not a programmer, I’m a designer, so trying to work out the code is very difficult for me.

    Could I ask you to please break down the steps a bit more for me, so that I can work out what you’re doing in the code?

  3. Great stuff! Thanks for sharing this, helped me out when importing from C4D to Unity.

  4. For the people who need the shader forge version, check this image out. The image is in the link below.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Categories

%d bloggers like this: