Why is my mouse input offset when using ScreenPointToRay?

Hi,

I am trying to build a grid based placing system using the Grid component and raycasting. For some reason I can’t get the mouse position to properly convert to worldspace. Could you help me?

This is the code:

using UnityEngine;

public class GridController : MonoBehaviour
{
[SerializeField] LayerMask layerMask;
[SerializeField] Transform indicator;

private Grid grid;
private Vector3 mouseWorldPosition, cellPosition;
private Vector3 lastMousePosition, lastCellPosition;

Ray mouseRay;
RaycastHit mouseHit;

private float cellSize;

void Start()
{
grid = GetComponent();
cellSize = grid.cellSize.x;
}

void Update()
{
if (MouseMoving())
{
mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(mouseRay, out mouseHit, Mathf.Infinity, layerMask))
{
mouseWorldPosition = mouseHit.point;
cellPosition = worldPositionToCell(mouseWorldPosition);
if (cellPosition != lastCellPosition)
{
indicator.position = new Vector3(cellPosition.x + cellSize * .5f, mouseHit.point.y, cellPosition.y + cellSize * .5f);

lastCellPosition = cellPosition;
}
}
}
}

Vector3 worldPositionToCell(Vector3 worldPosition)
{
return grid.WorldToCell(worldPosition);
}

bool MouseMoving()
{
if(lastMousePosition != Input.mousePosition)
{
return true;
} else
{
return false;
}
}
}

Something went wrong with the gif, here’s an imgur link

I think i’ve figured it out. It was a FOV issue :sunglasses: