Heatmaps in Unity 5.4+
Step1:The shader
Shader "Example/Heatmap" {
Properties {
_HeatTex ("Texture", 2D) = "white" {}
}
SubShader {
Tags {"Queue"="Transparent"}
Blend SrcAlpha OneMinusSrcAlpha // Alpha blend
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
struct vertInput {
float4 pos : POSITION;
};
struct vertOutput {
float4 pos : POSITION;
fixed3 worldPos : TEXCOORD1;
};
vertOutput vert(vertInput input) {
vertOutput o;
o.pos = mul(UNITY_MATRIX_MVP, input.pos);
o.worldPos = mul(_Object2World, input.pos).xyz;
return o;
}
uniform int _Points_Length = 0; //Array Length
uniform float3 _Points [20]; // (x, y, z) = position
uniform float2 _Properties [20]; // x = radius, y = intensity
sampler2D _HeatTex;
half4 frag(vertOutput output) : COLOR {
// Loops over all the points
half h = 0;
for (int i = 0; i < _Points_Length; i ++)
{
// Calculates the contribution of each point
half di = distance(output.worldPos, _Points.xyz);
half ri = _Properties.x;
half hi = 1 - saturate(di / ri);
h += hi * _Properties.y;
}
// Converts (0-1) according to the heat texture
h = saturate(h);
half4 color = tex2D(_HeatTex, fixed2(h, 0.5));
return color;
}
ENDCG
}
}
Fallback "Diffuse"
}
Setp2: The C# code
using UnityEngine;
using System.Collections;
public class Heatmap1 : MonoBehaviour
{
public Vector4[] positions;
public Vector4[] properties;
public Material material;
public int count = 50;
void Start ()
{
positions = new Vector4[count];
properties = new Vector4[count];
for (int i = 0; i < positions.Length; i++)
{
positions = new Vector4(Random.Range(-0.4f, +0.4f), Random.Range(-0.4f, +0.4f), 0, 0);
properties = new Vector4(Random.Range(0f, 0.25f), Random.Range(-0.25f, 1f), 0, 0);
}
}
void Update()
{
//
for (int i = 0; i < positions.Length; i++)
positions += new Vector4(Random.Range(-0.1f,+0.1f), Random.Range(-0.1f, +0.1f), 0, 0) * Time.deltaTime;
//[Propagates value to the shader]
material.SetInt("_Points_Length", count);
material.SetVectorArray("_Points", positions);
material.SetVectorArray("_Properties", properties);
}
}
Setp3: The Assets
The “_HeatTex” you can use like the following texture:
[/sell]