Search code examples
c#unity-game-engineraycasting

Raycasting in unity jumping to a wrong position


I am having a problem with Raycasting. All I want to do is always know the position of my cursor in world space and it works, but only if the cursor is moving. when the cursor is not moving it jumps to a random point around 4 units down on the x and z-axis.

public class CameraMovementRay : MonoBehaviour
{
    public Camera playerCam;
    Ray cursorRay;
    Vector3 playerPos;
    public RaycastHit cursorHit;
    public LayerMask clickPlain;
    public bool cursorHittingFloor;

    // Update is called once per frame
    void Update()
    {
        cursorRay = playerCam.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(cursorRay, out cursorHit, 100f, clickPlain))
        {
            print(cursorHit.point);
            Debug.DrawLine(cursorRay.origin, cursorHit.point, Color.red);
            cursorHittingFloor = true;

        }
        else
        {
            Debug.LogError("Not on the grund");
            cursorHittingFloor = false;
        }
    }


Solution

  • That wasn't working out but I did find code that does

    `` public class LookAtMouse : MonoBehaviour {

    public Camera playerCamera;
    
    Plane movementPlane = new Plane(Vector3.up, 0f);
    Vector3 lookPoint;
    
    Ray CursorRay;
    
    // Update is called once per frame
    void Update()
    {
        CursorRay = playerCamera.ScreenPointToRay(Input.mousePosition);
        float enter = 0.0f;
    
        movementPlane.Raycast(CursorRay, out enter);
        lookPoint = CursorRay.GetPoint(enter);
        print(lookPoint);
        Debug.DrawLine(CursorRay.origin, lookPoint);
    
        transform.LookAt(lookPoint);
    
    }
    

    } ``