- Home /
hit.textureCoord problem
I'm doing a little tunnel game where game levels are simply different transparent textures wrapped inside the surfaces of cylinders. I'm using raycasting and hit.textureCoord to find out whether player's ship is on the "solid" surface or not.
Mostly it works fine, but there are some small parts in the tunnel where tex.GetPixel returns 0,0,0,0 even though ship clearly is hovering over the solid color surface. Textures are black and white ARGB32.
Debugging shows that tunnel walls are only thing the raycast is hitting and I've also tried with larger textures (if it would have been problem of inaccuracy when rounding uv coordinates). I've also checked more pixels around the hit coordinates but they all return 0 color.
Here's my code:
RaycastHit hit;
Vector3 theRay = ship.transform.TransformDirection(-ship.transform.up);
Debug.DrawRay(ship.transform.position,-ship.transform.up,Color.red);
if (Physics.Raycast(ship.transform.position, theRay, out hit))
{
Renderer renderer = hit.collider.renderer;
MeshCollider meshCollider = hit.collider as MeshCollider;
if (renderer == null || renderer.sharedMaterial == null || renderer.sharedMaterial.mainTexture == null || meshCollider == null)
{
return;
}
float groundDis = hit.distance;
Texture2D tex = renderer.material.mainTexture as Texture2D;
Vector2 pixelUV = hit.textureCoord;
pixelUV.x *= tex.width;
pixelUV.y *= tex.height;
Color col = tex.GetPixel((int)pixelUV.x, (int)pixelUV.y);
if (col.a <= 0.1f) {
shadow.renderer.enabled = false;
}
else {
shadow.renderer.enabled = true;
}
}
And here's image of what I'm trying to achieve: