- Home /
Shader distance between WorldSpaceCameraPos and Vertex
Hi. I want to create a shader based on WorldSpaceCameraPos and Vertex position. The effect that i want create is like that in the ACB when the player can't pass the map limits. I searched on the web but without results. I hope you will answer soon.
Comment
What help are you looking for? The variable _WorldSpaceCameraPos is that position...
Best Answer
Answer by qwee · Jan 04, 2013 at 12:45 PM
I have resolved in another way. I have created a simple alpha emissive shader which depends on vertices colors:
Shader "Custom/MyShader"
{
Properties
{
_Color("Main Color", Color) = (1,1,1,1)
_mul("Multiplier", Float) = 1
_addSubtract("Add / Subtract", Float) = 0
_alpha("Alpha", Range(0,1)) = .5
_MainTex("Base (RGB)", 2D) = "white"{}
_AlphaMap("Alpha Texture (RGB)", 2D) = "white"{}
}
SubShader
{
Tags { "Queue"="Transparent" }
CGPROGRAM
#pragma surface surf Lambert alpha
float4 _Color;
float _mul;
float _addSubtract;
float _alpha;
sampler2D _MainTex;
sampler2D _AlphaMap;
struct Input
{
float2 uv_MainTex;
float2 uv_AlphaMap;
float4 color : Color;
};
void surf (Input IN, inout SurfaceOutput o)
{
o.Emission = (tex2D(_MainTex, IN.uv_MainTex) * _mul + _addSubtract) * _Color.rgb * IN.color.rgb;
o.Alpha = saturate(tex2D(_AlphaMap, IN.uv_AlphaMap)) * _alpha * IN.color.a;
}
ENDCG
}
FallBack "Diffuse"
}
Then i have created a C# Script that controls the vertices colors in relation to the player position:
using UnityEngine;
using System.Collections;
public class VertexCtrl : MonoBehaviour
{
public float dist = 20;
Mesh mesh;
Vector3[] vertices;
Color[] colors;
void Start()
{
mesh = GetComponent<MeshFilter>().mesh;
vertices = mesh.vertices;
colors = new Color[vertices.Length];
}
void Update()
{
foreach(GameObject obj in FindSceneObjectsOfType(typeof(GameObject)))
{
if(obj.tag == "Player")
{
for(int i = 0; i < vertices.Length; i++)
{
if(Vector3.Distance(transform.TransformPoint(vertices[i]), obj.transform.position) > dist)
colors[i] = new Color(0, 0, 0, 0);
else
colors[i] = new Color(0, 0, 0, 1 - Vector3.Distance(transform.TransformPoint(vertices[i]), obj.transform.position) / dist);
}
mesh.colors = colors;
}
}
}
}
It works very well for me. I hope it helps someone...