Question by
unoo_ · Oct 25, 2018 at 12:45 PM ·
shadershadersshader programmingshader writing
my 2D light shader works wrong
I'm making 2d light which limits the sight like the second stage of Nuclear Throne. I made my shader work, but it doesn't do well with multiple lights. The circles surrounding the ones in the middle must have the same alpha but as you can see, the first one in the list is darker, and the last one is brighter.
Here's a script for a camera.
using UnityEngine;
[System.Serializable]
public struct LightSource
{
public Vector2 pos;
public float range;
}
[ExecuteInEditMode]
public class LightCamera : MonoBehaviour {
public Material lightMapper;
public Material lightApplier;
public LightSource[] lightSources;
Camera cam;
private void OnEnable()
{
cam = GetComponent<Camera>();
}
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
RenderTexture lightMap = new RenderTexture(source.width, source.height, 16);
foreach (LightSource light in lightSources)
{
RenderTexture tempMap = new RenderTexture(source.width, source.height, 16);
Vector2 screenPoint = cam.WorldToScreenPoint(light.pos);
lightMapper.SetVector("_LightCoord", new Vector2(screenPoint.x, screenPoint.y));
lightMapper.SetFloat("_SquaredLightRange", light.range * light.range);
Graphics.Blit(lightMap, tempMap, lightMapper);
lightMap = tempMap;
}
lightApplier.SetTexture("_LightMap", lightMap);
Graphics.Blit(source, destination, lightApplier);
}
}
And shader. It's assigned to the lightMapper above.
Shader "Custom/LightMapper"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
Pass
{
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float4 vertex : SV_POSITION;
float2 uv : TEXCOORD0;
};
v2f vert(appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
sampler2D _MainTex;
float4 _MainTex_TexelSize;
float2 _LightCoord;
float _SquaredLightRange;
float Square(float x) {
return x * x;
}
fixed4 frag(v2f i) : SV_Target
{
float squaredDst = Square(_LightCoord.x - i.uv.x * _MainTex_TexelSize.z) + Square(_LightCoord.y - i.uv.y * _MainTex_TexelSize.w);
if (squaredDst <= _SquaredLightRange)
{
if (squaredDst <= _SquaredLightRange / 8 * 3)
return float4(1, 1, 1, 1);
float4 col = tex2D(_MainTex, i.uv);
if (col.a >= 1)
return col;
return float4(1, 1, 1, .5);
}
return tex2D(_MainTex, i.uv);
}
ENDCG
}
}
}
The lightApplier doesn't matter. I tried drawing without that, but the result was the same.
캡처.png
(128.1 kB)
Comment
Your answer
Follow this Question
Related Questions
Add fog to vertex shader 0 Answers
Converted ShaderToy shader showing up black 1 Answer
Metallic material decomposing light in rainbow spectre? 0 Answers
_Time in Image Effects 0 Answers