0

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.

https://streamable.com/kalri6

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 ?

The tile in Blender enter image description here

Disco Fever
  • 147
  • 10
  • 1
    you assumed sqrt(3) in width, which doesnt look to be too wrong, but, its not the same height.. youve picked 2+3/4 in height.. are you sure on that? – BugFinder Jul 02 '23 at 14:49
  • At the moment I'm not sure of anything; I blender I measured the tile to be 2.31 height and 2 of width. – Disco Fever Jul 02 '23 at 15:25

0 Answers0