Raycast and ignore transparency

So what I am trying to do is a array of 3d tiles and select them with mouse click. I am not using monobehaviour as it is breaking my other code. I am using raycast instead of OnMouseOver() and it was working fine until I applied transparency to the tiles. It is now at certain angle highlighting and selecting multiple tiles. It would be great if someone could assist, I am unsure if this has been asked as I am new to forums, if the question exists and has been solved, could someone please link and close this question?

This is the the tile: http://puu.sh/7AVFO.png
This is with one tile highlighted: http://puu.sh/7AVHE.png
This is with multiple tiles: http://puu.sh/7AVKE.png

I apologise for angles as to replicate error I need certain angles.
If you need any more information I am missing let me know.

public Tile (GameObject prefab)
	{
		potato = prefab;
		TileColours colours = potato.GetComponent<TileColours> ();
		uncontrolledColor = colours.uncontrolledColor;
		highlightColor = colours.highlightColor;
		selectionColor = colours.selectionColor;
		playerColor = colours.playerColor;
		titanColor = colours.titanColor;

		terrainType = 0;
		controlled = 0;
		selected = false;
	
		//titanCount = 10;

		tileID = -1;

	}



	public void Update ()
	{
		if (controlled == 0) {
			potato.renderer.material.color = uncontrolledColor;
		} else if (controlled == 1) {
			potato.renderer.material.color = playerColor;
		} else if (controlled == 2) {
			potato.renderer.material.color = titanColor;
		} else {
			potato.renderer.material.color = Color.black;
			Debug.Log ("tile Controlled variable is not within correct parameters");
		}

		Ray raycast = Camera.main.ScreenPointToRay (Input.mousePosition);
		RaycastHit hitInfo;

		if (potato.collider.Raycast (raycast, out hitInfo, Mathf.Infinity)) {
			potato.renderer.material.color = highlightColor;
			if (Input.GetMouseButtonDown (0)) {
				/*mousdown*/
				Selected = true;
			}

		}

		if (selected) { //putting on material if selected, done externally and at the end so the refresh doesn't override
			potato.renderer.material.color = selectionColor;
		}

		if (Input.GetKey (KeyCode.Escape)) { //deselecting tile
			selected = false;
		}

	}

1 Answer

1

Transparency has nothing to do with Raycasting(). Raycasting uses the collider of the object.

The issue is that you are using Collider.Raycast(). Collider.Raycast() casts against a specific collider. It doesn’t take into account that the ray might hit another collider first. Any situation/angle where a Raycast() can hit multiple objects, it will.

You can solve the problem by moving to Physics.Raycast(), but having the individual tiles each do their own Raycast() is a potential performance issue. It would be far better to have just one object do the Physics.Raycast() and then have that object communicate the hit to the appropriate tile.

Thank you for your quick response

–