Unit moving after empty space click with mouse

Hey codemonkey! I saw the other similar questions on this topic but never saw any example code. Right now, i have the problem of when i click on empty space, the player still moves to another position. Is this what you were saying? how would i use it properly?

public static bool TryGetPosition(out Vector3 position)
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    Physics.Raycast(ray, out RaycastHit raycastHit, float.MaxValue, instance.mousePlaneLayerMask);
    position = raycastHit.point;
    return Physics.Raycast(ray);
}

thanks!

By empty space you mean clicking outside the plane collider?
If so yes that code should work, the function will return false if it doesn’t hit the collider and you can use that to ignore the move/select code.

sweet! btw, what would be the code on the Unit script to set move position?

It’s just calling the Move function on the Unit
So you would do

if (Input.GetMouseButtonDown(0) && MouseWorld.TryGetPosition(out Vector3 mouseWorldPosition)) {
  Move(mouseWorldPosition);
}

That would only move if you clicked on a valid world position

1 Like

thank you so much!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms