Skip to content

Instantly share code, notes, and snippets.

@becksebenius
Created January 17, 2014 20:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save becksebenius/8480885 to your computer and use it in GitHub Desktop.
Save becksebenius/8480885 to your computer and use it in GitHub Desktop.
Runtime vertex color painter
using UnityEngine;
using System.Collections;
public class VPainter : MonoBehaviour
{
public MeshCollider[] paintTargets = new MeshCollider[0];
public Color targetColor;
public float paintRadius = 1f;
public float paintSpeed = 1f;
public void Update ()
{
if(Input.GetKey(KeyCode.Mouse0))
{
Ray r = Camera.main.ScreenPointToRay(Input.mousePosition);
foreach(MeshCollider target in paintTargets)
{
RaycastHit hit;
if(target.Raycast(r, out hit, Mathf.Infinity))
{
var mesh = target.sharedMesh;
var colors = mesh.colors;
var vertices = mesh.vertices;
if(colors.Length != vertices.Length)
{
colors = new Color[vertices.Length];
}
//Loop through the vertices of the mesh to see which ones we hit
for(int i = 0; i < vertices.Length; i++)
{
//Convert the vertex into world space
var point = target.transform.TransformPoint(vertices[i]);
float distance = Vector3.Distance(point, hit.point);
//If the vertex is too far away, don't perform any calculations
if(paintRadius < distance) continue;
float factor = 1-distance/paintRadius;
colors[i] = Color.Lerp(colors[i], targetColor, paintSpeed * factor * Time.deltaTime);
}
mesh.colors = colors;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment