- Home /
Raycast Mouse Click On Specific Objects Only
I'm trying to place cube primitives on a surface I've tagged as "Floor" When one clicks on the floor, a cube is placed at the mouse coordinates.
My trouble is that I'm trying to limit the cube placement to occur only when the "Floor" is clicked.
I want the function to ignore the cubes... That is don't place a cube on top of another cube.
Any suggestions on how exclude the cube's collider?
Here is my most recent attempt, which doesn't work.
public class GetMouseCoordinates : MonoBehaviour
{
public Material theBlockMaterial;
void Update()
{
CastBlock();
}
private void CastBlock()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (collider.Raycast(ray, out hit, 1000.000f))
{
if (hit.collider.tag == "Floor")
{
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = new Vector3(Mathf.Floor(hit.point.x), Mathf.Floor(hit.point.y) + 0.5f, Mathf.Floor(hit.point.z));
cube.renderer.material = theBlockMaterial;
cube.transform.parent = this.transform;
}
}
}
}
}
Answer by VesuvianPrime · Aug 01, 2014 at 01:16 AM
A couple suggestions:
1) have you considered adding a script to the floor object and implementing OnMouseDown?
2) you could filter your raycast by using LayerMasks
Hey Thanks for the suggestions.
I'm trying to stay away from On$$anonymous$$ouseDown, as I plan on refactoring for touch and I don't believe that there is an equivalent OnTouch event. $$anonymous$$y understanding is that Raycast is required for touch events and On$$anonymous$$ouseDown, while it will work, has performance issues on mobile.
Going to look into Layer$$anonymous$$asks now.
Thanks
After much experimentation... $$anonymous$$y Code works as expected when I manually -through Unity editor - place cubes or other primitives with colliders attached into the scene.
It is only the primitives created in script that don't behave, even though they are created with box colliders which should block my raycast from hitting the "Floor".
Oh... And Layer$$anonymous$$asks did not work.