I’m attempting to create a force field shader that displays bullet impacts. My problem is that the points on the shader are not showing correctly. I have a simple shader graph set up with a custom function to loop over the points in world space and color the nearby world space fragments. I read these points from a texture. I wrote a c# script that updates this texture with the world positions of the “hits”. I also added an empty game object to test where the impacts should display and I get strange results.
void LoopPoints_float(float3 worldPosition, float sphereRadius, UnityTexture2D tex, out float alpha)
{
alpha = 0;
float count = 10;
for (int i = 0; i < count; i++)
{
float2 uv = float2(float(i) / count, 0);
float4 sphere = SAMPLE_TEXTURE2D(tex, tex.samplerstate, uv);
float distance = length(worldPosition - sphere.xyz);
distance = clamp(distance, 0, sphereRadius);
alpha += (sphereRadius - distance) / sphereRadius * sphere.w;
}
alpha = clamp(alpha, 0, 1);
}
using System.Linq;
using UnityEngine;
public class Shield : MonoBehaviour, IShootable
{
private Material mat;
[SerializeField]
private ItemSettings settings;
private Texture2D tex;
private Color[] hits;
private int index;
public Transform target;
public void Awake()
{
hits = new Color[10];
mat = GetComponent<MeshRenderer>().material;
tex = new Texture2D(hits.Length, 1, TextureFormat.RGBAFloat, false);
mat.SetTexture("_Texture2D", tex);
}
private void Update()
{
hits[0] = new Color(target.position.x, target.position.y, target.position.z, 1); // DEBUG
tex.SetPixels(hits);
tex.Apply();
for (var i = 0; i < hits.Length; i++)
{
hits[i].a -= Time.deltaTime / settings.shieldHitDuration;
hits[i].a = Mathf.Clamp(hits[i].a, 0, Mathf.Infinity);
}
}
// rgb is world position, a is alpha
public void Hit(Vector3 worldPosition, float damage)
{
index = (index + 1) % hits.Length;
hits[index] = new Color(worldPosition.x, worldPosition.y, worldPosition.z, 1);
}
}