- Home /
Change vertex color of a mesh.
I am trying to color the vertices of a mesh based on each vertex's distance from some nodes. Ultimately I want to use this to color the ground to visually message the player about the fertility of the ground.
I made a test with a cube in the middle and 2 nodes that had different colors associated with them.
Mesh _mesh;
Vector3[] _vertexs;
public Color _color1;
public Color _color2;
public Transform pos1;
public Transform pos2;
// Use this for initialization
void ChangeColors(){
Color[] _color = new Color[_vertexs.Length];
for (int i = 0; i < _vertexs.Length; i++){
float _distance1 = Distance (_vertexs[i], pos1.position);
float _distance2 = Distance (_vertexs[i], pos2.position);
float _ratio1 = _distance1 / (_distance1+_distance2);
float _ratio2= _distance2 / (_distance1+_distance2);
_color[i] = _color1 * _ratio1 + _color2*_ratio2;
}
_mesh.colors = _color;
}
void Start () {
_mesh = GetComponent<MeshFilter> ().mesh;
_vertexs = _mesh.vertices;
ChangeColors ();
}
float Distance(Vector3 _start, Vector3 _end){
return Vector3.Distance (_start, _end);
}
void ChangeToRed(){
for (int i = 0; i < _mesh.colors.Length; i++) {
_mesh.colors[i] = Color.red;
}
}
The interpolation bit works (I used to have it spit out the numbers to the log.) But the colors don't take. If I go through and print out the colors array it's all just white.
I have tried finding shaders that use vertex color but this doesn't seem to be working. (I have no experience with shaders, but I think I may have to learn a bit to solve this problem.)
To reiterate, I'm trying to find a way to assign a color to each vertex of a mesh. Thanks.
Answer by drudiverse · Oct 18, 2014 at 10:01 PM
i think there is a code by c petersen to rewrite the UVS to all the same for each vertex, and make them a function of the distance from point. otherwise, is just sent point informations to the shader and say color values +/- distance from worldspace, say a loop of 10 points that are in view in the map, hopefully less of them.
Answer by seth_slax · Sep 23, 2015 at 02:43 AM
I'm not sure if this is necessary in C# (I work in JS), but getting the vertex world position, from your code would be:
float _distance1 = Distance (transform.TransformPoint(_vertexs[i]), pos1.position);
Also for the vertex shader, can't recall where I got this from but this is the simplest one I've found:
Shader "Vertex Color Lit" {
Properties {
_MainTex ("Base (RGB)", 2D) = "white" {}
}
SubShader {
Pass {
Lighting On
ColorMaterial AmbientAndDiffuse
SetTexture [_MainTex] {
combine texture * primary DOUBLE
}
}
}
}
Your answer
Follow this Question
Related Questions
Material doesn't have a color property '_Color' 4 Answers
vertex color questions! 1 Answer
GameObject coloring 1 Answer
Simple vertex color + light shader 1 Answer
iOS shader with no texture, just vertex colouring and main colour 1 Answer