Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Question Why is my mouse input offset when using ScreenPointToRay?

Discussion in 'Input System' started by koenfrontatie, Feb 9, 2024.

  1. koenfrontatie

    koenfrontatie

    Joined:
    Mar 7, 2020
    Posts:
    5
    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<Grid>();
    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;
    }
    }
    }
     
  2. koenfrontatie

    koenfrontatie

    Joined:
    Mar 7, 2020
    Posts:
    5
  3. koenfrontatie

    koenfrontatie

    Joined:
    Mar 7, 2020
    Posts:
    5
    I think i've figured it out. It was a FOV issue :cool: