Last active
December 12, 2018 17:22
-
-
Save baobao/75e685e90e3dfef691bb89ddb6269793 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 頂点ライティング | |
*/ | |
Shader "VertexLighting" | |
{ | |
SubShader | |
{ | |
Tags { "RenderType"="Opaque"} | |
Pass | |
{ | |
CGPROGRAM | |
#pragma vertex vert | |
#pragma fragment frag | |
#include "UnityCG.cginc" | |
struct appdata | |
{ | |
float4 vertex : POSITION; | |
float3 normal : NORMAL; | |
}; | |
struct v2f | |
{ | |
float4 vertex : SV_POSITION; | |
float luminance : TEXCOORD0; | |
}; | |
float3 _UserWorldSpaceLightDir; | |
fixed4 _LightColor0; | |
v2f vert (appdata v) | |
{ | |
v2f o; | |
o.vertex = UnityObjectToClipPos(v.vertex); | |
float4 invLightDir = mul(UNITY_MATRIX_M, -_UserWorldSpaceLightDir); | |
// 各頂点の拡散反射輝度を算出 | |
float luminance = dot(v.normal, normalize(invLightDir)); | |
o.luminance = luminance; | |
return o; | |
} | |
fixed4 frag (v2f i) : SV_Target | |
{ | |
return float4(i.luminance, i.luminance, i.luminance, 1) * _LightColor0; | |
} | |
ENDCG | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
[RequireComponent(typeof(MeshRenderer))] | |
public class VertexLighting : MonoBehaviour | |
{ | |
private Transform _lightTransform; | |
private Material _material; | |
private static readonly int UserWorldSpaceLightDir0Id = Shader.PropertyToID("_UserWorldSpaceLightDir"); | |
void Awake() | |
{ | |
var directionalLight = FindObjectOfType<Light>(); | |
if (directionalLight != null) | |
_lightTransform = directionalLight.transform; | |
var meshRenderer = GetComponent<MeshRenderer>(); | |
_material = meshRenderer.material; | |
} | |
void Update() | |
{ | |
if (_lightTransform != null) | |
{ | |
// ライトのオイラー角から方向ベクトルを算出 | |
var direction = Quaternion.Euler(_lightTransform.eulerAngles) * Vector3.forward; | |
// ライトベクトルをシェーダにわたす | |
_material.SetVector(UserWorldSpaceLightDir0Id, direction); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment