Hi everyone,
I hope this is the right section for my question!
I am working on a simple tilemap where the player can select individual tiles using the mouse. I have a script that programmatically generates the mesh with 4 vertices for each tile and another one that handles the mouse movement and inputs.
When the mouse is above a tile, a cubic game object which I call the “selectionMarker” is moved to the respective position to highlight the position. Here is the code that I use:
/* get the current mouse coordinates */
void OnMouseOver () {
// find the tile that is selected by the mouse
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
// error: remove the selection marker
if (!GetComponent<Collider> ().Raycast (ray, out hitInfo, Mathf.Infinity)) {
selectionMarker.GetComponentInChildren<MeshRenderer>().enabled = false;
return;
}
// convert the world coordinates to tile coordinates
Vector3 correctedPoint = gameObject.transform.InverseTransformPoint(hitInfo.point);
int x = Mathf.FloorToInt(correctedPoint.x / tileMap.tileSize);
int z = Mathf.FloorToInt(correctedPoint.z / tileMap.tileSize);
int mapX = x;
int mapZ = tileMap.sizeZ - z - 1;
lastCoordinates = new Vector2 (mapX,mapZ);
// move the selection marker
selectionMarker.transform.position = new Vector3(x * tileMap.tileSize, 0.1f, z * tileMap.tileSize);
selectionMarker.GetComponentInChildren<MeshRenderer>().enabled = true;
}
/* no tile selected: remove the selection marker */
void OnMouseExit() {
selectionMarker.GetComponentInChildren<MeshRenderer>().enabled = false;
}
For some reason this does not work properly: When I move the cursor over the border between two tiles, the marker pops up for a few milliseconds but immediately becomes invisible again. The OnMouseExit() function seems to get called while I am still above the grid.
How is this possible when there are absolutely no gaps between the tiles? I have read that the MouseOver functions depend on the collider of the game object the script is attached to. The mesh collider is set to the generated mesh with “meshCollider.sharedMesh=mesh;” in the beginning.
Could the reason be that the selection marker game object is moved below the cursor and this triggers the OnMouseExit() function for the tilemap?