Question by
craig395 · Nov 12, 2018 at 07:43 PM ·
shadershader programming
2D texture to world space shader
Hi,
I am trying to get the texture to be stuck to the world coordinates instead of the object. so if the object is moved the texture will not. I have done some Googling but have not found anything helpful, although that may be due to my lack of understanding of shaders.
Currently, I have used an unlit shader as the base and am only trying to do this in 2D, essentially a tile that is only viewed from the top down. I have got as far as to have a squished line of the image stick to the world. my code is below with an example at the end although it's not a great quality gif.
any Idea where I may be going wrong with this?
// Upgrade NOTE: replaced '_Object2World' with 'unity_ObjectToWorld'
Shader "Unlit/UnlitWorldTileShader"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
// make fog work
//#pragma multi_compile_fog
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
//UNITY_FOG_COORDS(1)
float4 vertex : SV_POSITION;
float4 worldPos: TEXCOORD2;
};
sampler2D _MainTex;
float4 _MainTex_ST;
v2f vert (appdata v)
{
v2f o;
float ofset = float4(0, 1000, 0, 0);
//o.vertex = UnityObjectToClipPos(v.vertex);
o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
o.worldPos = mul(unity_ObjectToWorld, v.vertex);
//o.worldPos = ComputeScreenPos(o.vertex);
//o.uv = mul(unity_ObjectToWorld, v.vertex).xyz;
//UNITY_TRANSFER_FOG(o,o.vertex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
// sample the texture
//fixed4 col = tex2D(_MainTex, i.uv);
fixed4 col = tex2D(_MainTex, i.worldPos.xy);//i.worldPos.xy
// apply fog
//UNITY_APPLY_FOG(i.fogCoord, col);
return col;
}
ENDCG
}
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612182021im_/https://answers.unity.com/themes/thub/images/avi.jpg)