The following code shows the mouse hit position with a gray sphere; the yellow sphere shows the snapped hex position; as you can see it works well when close to center but the moment I get a bit far it stops working.
using UnityEngine;
public class HexDebug : MonoBehaviour
{
[SerializeField] private LayerMask hexLayerMask;
private const float tileSize = 1.1547f;
private Camera mainCamera;
private void Awake()
{
mainCamera = Camera.main;
}
private Vector3 GetMouseHitPoint()
{
var mousePosition = Input.mousePosition;
var ray = mainCamera.ScreenPointToRay(mousePosition);
return !Physics.Raycast(ray, out var hit, Mathf.Infinity, hexLayerMask) ? Vector3.zero : hit.point;
}
private Vector3 GetGridPosition()
{
return SnapHexToGrid(GetMouseHitPoint());
}
private static Vector3 SnapHexToGrid(Vector3 worldPosition)
{
var col = (int)Mathf.Floor(worldPosition.x / (Mathf.Sqrt(3) * tileSize));
var row = (int)Mathf.Floor(worldPosition.z / (2f * tileSize * (3f / 4f)));
var shouldOffset = row % 2 == 0;
var width = Mathf.Sqrt(3) * tileSize;
var offset = shouldOffset ? width / 2f : 0f;
var xPosition = col * width + offset;
var yPosition = row * 2f * tileSize * (3f / 4f);
return new Vector3(xPosition, 0f, yPosition);
}
private void OnDrawGizmos()
{
if (!Application.isPlaying) return;
Gizmos.DrawSphere(GetMouseHitPoint() + new Vector3(0f, 0.5f, 0f), 0.5f);
Gizmos.color = Color.yellow;
Gizmos.DrawSphere(GetGridPosition() + new Vector3(0f, 0.5f, 0f), 0.5f);
}
}
I cannot make this work properly; I have tried everything and loosing hairs here. What obvious mistake am I making ?