- Home /
Raycast on Nonconvex MeshCollider
Hey there,
Iam am trying to use a Raycast for some color Picking.
First I Generate a Mesh with Mesh Collider and Mesh Renderer from Vertices.
public Color colorBoring;
public Color colorAngry;
public Color colorHappy;
Texture2D mainTexture;
private Vector3[] Vertices = { new Vector3(-1,0,0), new Vector3(0,0.5f,0), new Vector3(0,1,0), new Vector3(1,0,0)};
private int[] Indices = { 0, 1, 2, 0, 3, 1, 3, 2, 1 };
private Vector2[] UVs = { new Vector2(0,0), new Vector2(0.5f,0.5f), new Vector2(0.5f,1), new Vector2(1,0)};
private List<Color> colors;
// Use this for initialization
void Start () {
colors = new List<Color>();
colors.Add(colorHappy);
colors.Add(Color.grey);
colors.Add(colorAngry);
colors.Add(colorBoring);
Mesh mesh = new Mesh();
mesh.name = "Picker";
mesh.vertices = Vertices;
mesh.triangles = Indices;
mesh.uv = UVs;
mainTexture = new Texture2D (128, 128);
for (int i = 0; i < mainTexture.width; i++) {
for (int j = 0; j < mainTexture.height; j++) {
Color pixelColor = Color.Lerp (colorHappy, colorBoring, (float)i / mainTexture.width);
pixelColor = Color.Lerp (pixelColor, colorAngry, (float)j / mainTexture.height);
mainTexture.SetPixel (i, j, pixelColor);
}
}
mainTexture.Apply ();
GetComponent<MeshRenderer> ().material.mainTexture = mainTexture;
mesh.colors = colors.ToArray();
GetComponent<MeshFilter>().mesh = mesh;
GetComponent<MeshCollider> ().sharedMesh = mesh;
mesh.RecalculateBounds ();
mesh.RecalculateNormals ();
}
This is simply a Colored Triangle.
Now the other Side the Raycast. According to the Manual I need a Nonconvex Mesh Collider to use textureCoord.
if (triggerPressed) {
Ray ray = new Ray (transform.position, transform.forward);
RaycastHit hit;
var raycast = Physics.Raycast (ray, out hit);
Debug.DrawRay (transform.position, transform.forward, Color.red);
if (hit.collider.gameObject == Picker) {
Texture2D map = (Texture2D)Picker.GetComponent<MeshRenderer> ().materials[0].mainTexture;
var pixelUV = hit.textureCoord;
Debug.Log (pixelUV + " " + hit.collider.gameObject.name);
pixelUV.x *= map.width;
pixelUV.y *= map.height;
Debug.Log ("x=" + pixelUV.x + ", y=" + pixelUV.y + " " + map.GetPixel ((int)pixelUV.x, (int)pixelUV.y));
//Debug.Log (hit.triangleIndex);
} else {
Debug.Log (hit.collider.gameObject.name);
}
}
But the Raycast Ignores the MeshCollider if it is Nonconvex. If I set it Convex, it will be recognised by the Ray, but then the textureCoord is {0,0}
Answer by Dropye · Feb 21, 2017 at 11:47 AM
Okay,
I just changed the Mesh and the Texture. Both are now Assets. Not what I wanted, but it works.
Your answer
Follow this Question
Related Questions
Why do I get a triangleIndex of -1 when I SphereCast a convex MeshCollider? 1 Answer
Get texture pixel color after raycast on rigidbody object 1 Answer
Convex MeshCollider Doesn't Work on 2D Plane 0 Answers
Building a prism (adding thickness) from non-convex mesh 0 Answers
Rigidbody and convex mesh collider 1 Answer