Hi everybody,
I would like to remember the basics of lighting. Since I used the surface shaders, I lost many concepts and when I try to develop the basics, I can’t understand the following results I get…
Here is my shader to compute a directional Light per vertex:
Shader "Custom/VertexLightingDiffuse"
{
Properties
{
_MatColor ("Material Color", Color) = (0.5, 0.5, 0.5, 1.0)
}
SubShader
{
Tags
{
"RenderType"="Opaque"
}
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
// Comes from a C# script ( LightDir = -normalize(GameObject.Find("Directional Light").transform.forward) )
uniform float4 LightDir;
uniform float4 _MatColor;
struct v2f
{
float4 pos : SV_POSITION;
float4 finalColor : COLOR0;
};
v2f vert (appdata_full v)
{
v2f o;
float3 worldSpaceNormal = mul((float3x3)_Object2World, v.normal);
float NdotL = saturate(dot(normalize(worldSpaceNormal), LightDir));
o.finalColor = _MatColor * NdotL;
o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
return o;
}
float4 frag (v2f i) : COLOR
{
return i.finalColor;
}
ENDCG
}
}
Fallback "Diffuse"
}
Note: I want to use my own variables to understand as much as possible. Because when I use built-in variables, I’m more confused with the results !
I also made a short C# script, attached to the Dir Light in my scene.
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
[RequireComponent(typeof(Light))]
public class LightData : MonoBehaviour
{
private Transform lightTransform;
private new Light light;
void Start ()
{
this.lightTransform = this.transform;
this.light = this.GetComponent<Light>();
}
void Update ()
{
if (this.lightTransform != null)
{
Vector4 normalizedForward = new Vector4(
this.lightTransform.forward.x,
this.lightTransform.forward.y,
this.lightTransform.forward.z,
0.0f).normalized;
Shader.SetGlobalVector("LightDir", -normalizedForward);
Shader.SetGlobalColor("LightColor", this.light.color);
Shader.SetGlobalFloat("LightIntensity", this.light.intensity);
Shader.SetGlobalVector("LightPosition", new Vector4(
this.transform.position.x,
this.transform.position.y,
this.transform.position.z,
0.0f));
//print(normalizedForward);
}
}
}
I use the Unity Sphere and a low-poly sphere made with Maya.
- I expected to see on my Unity Sphere a result like this one:

Even if I multiply my final Color with the LightColor and LightIntensity, it still looks like a per-pixel lighting.
- To get a correct lighting, I need to negate the vector3.forward of the directional light. Why ?
Thanks in advance for your precious answers/tips.