Created
January 17, 2014 20:32
-
-
Save becksebenius/8480885 to your computer and use it in GitHub Desktop.
Runtime vertex color painter
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; | |
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