Im trying to detect intersecting gameobjects. I have a simple scene with 4 blocks and a shape. The blocks have box colliders and the shape a mesh collider.
If the shape is intersecting a block it should turn the block red otherwise it should remain blue. For some reason I can’t get this to work, it’s as if the mesh collider is not accurate enough.
With the image on the left, I would expect the bottom left block to be blue as it’s not intersecting the green shape; but it’s not.
If I drag the shape to the right (right image) the left side blocks turn blue which makes me think the code is working in some form.
Any help would be much appreciated!
Code:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class gameController : MonoBehaviour {
public GameObject shape;
public GameObject blockA;
public GameObject blockB;
public GameObject blockC;
public GameObject blockD;
public Material red;
public Material blue;
List<GameObject> blockList;
// Use this for initialization
void Start () {
blockList = new List<GameObject>();
blockList.Add (blockA);
blockList.Add (blockB);
blockList.Add (blockC);
blockList.Add (blockD);
}
// Update is called once per frame
void Update () {
MeshCollider shape_collider = shape.GetComponent<MeshCollider> ();
foreach (GameObject block in blockList) {
BoxCollider block_collider = block.GetComponent<BoxCollider> ();
if (shape_collider.bounds.Intersects (block_collider.bounds)) {
block.GetComponent<Renderer> ().material = red;
} else {
block.GetComponent<Renderer> ().material = blue;
}
}
}
}