Update ScreenToWorldPosition for Moving Camera

Hello all.

I’m trying to draw an arrow (it’ll eventually be an arrow, right now, it’s just a Debug.DrawLine) on the screen with a mouse using ScreenToWorldPosition. That system is fine and currently works, but the problem is, my player is constantly moving, so the initial mouse click sticks in the one place, and slowly crawls off the screen. What I want to do is have that initial click move along with the player, or camera itself, but when I try to add the position to the initial mouse click position, it winds up being offset way off the screen by a large amount.

My code is currently as follows:

// Get if the mouse is clicked and held
if (Input.GetMouseButtonDown(0))
{
    _mouseClickPosition = Camera.main.ScreenToWorldPoint( new Vector3(Input.mousePosition.x, Input.mousePosition.y, 20));
 
    _isDragging = true;
}
 
// if you want to input an aiming arrow, do it here
if (_isDragging)
{
    Debug.DrawLine(
        _mouseClickPosition,
        Camera.main.ScreenToWorldPoint( new Vector3( Input.mousePosition.x, Input.mousePosition.y, 20 ) ),
        Color.white );
 
}
 
 
// mouse released
if (Input.GetMouseButtonUp(0) && _isDragging)
{
    _mouseReleasePosition = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 20));
 
    _isDragging = false;
}

That achieves the original problem, but if I add the players position (or the camera’s position) to the _mouseClickPosition variable, it offsets the original click to a large degree. What I want is for that original mouse click to stay where it is on the screen while the player moves.

The camera setup is above the player, looking down at a slight angle, while the player is moving along the XZ axis.

Thanks for reading, and I hope you can help me, this has me stumped.

The easiest solution is to save the original mouse position and do the ScreenToWorldPoint() each time the value is used. So _mouseClickPosition and _mouseReleasePosition become screen cooridnates, and you call ScreenToWorldPoint() each time you call Debug.DrawLine() ( or draw the arrow as you will eventually do).