I have a simple script with a first person character controller, that does a raycast from the player’s position and look direction, and checks for collisions with a couple of meshes that I’ve placed in the scene. The meshes have MeshColliders attached to them, and it works almost correctly. For the most part, the collision is detected as it should be, but for no reason I can tell, it sometimes doesn’t detect the collision, depending on where I move to. I have a GUITexture that I’m using to indicate whether there is a collision detected. Here’s the script for the raycasting, which is attached to my character controller
using UnityEngine;
using System.Collections;
public class FPSPointer : MonoBehaviour {
private GUITexture crosshair;
void Start () {
crosshair = GameObject.Find("Crosshair GUI").GetComponent<GUITexture>();
}
void Update () {
// do ray cast to detect what is pointed at.
RaycastHit hitInfo;
if (Physics.Raycast(transform.position, transform.forward, out hitInfo, 100f)) {
if (hitInfo.collider.gameObject.tag == "Container") {
crosshair.color = Color.green;
}
else {
crosshair.color = Color.black;
}
}
}
}
The mesh is the rock mesh that comes with the free terrain assets on the site. I added a MeshCollider to it, and have tried every combination of IsTrigger, Smooth Sphere Collisions, and Convex, but I still get this odd behavior. What’s the trick to making this work?