How to check Collision before moving player object.

Hi,
Please help me on this.

I want to move a player from position A to position B. But before move the player object, I want to check that any object is on the path. If any object is on the path, then I should not move player, have to show error message. Position B is taken from mouse double click. Thank you .

  1. Need solution to check the object between position A and B before move.
  2. Please check my code, the way I handled the double click. If any other effective way to check, then please guide me.

Source Code:

private float doubleClickStart = 0;

bool dclick = false;

bool getclick = false;

void FixedUpdate()

{

    if (Input.GetMouseButtonDown(0))
    {
        if ((Time.time - doubleClickStart) < 0.3f)
        {
            dclick = true;
            getclick = true;

            doubleClickStart = -1;

        }
        else
        {

            doubleClickStart = Time.time;
        }
    }

    if (dclick)
        this.OnDoubleClick();
}
void OnDoubleClick()
{
    if (getclick)
    {
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit))
        {
            movement = hit.point;          
        }
        getclick = false;
    }
    

    movePosition = Vector3.Lerp(transform.position, movement, Time.deltaTime * speed);

    PlayerRightbody.MovePosition(movePosition);

}

You didn’t explain about your scenario, so here are some general tips:

  1. Use navmeshes and path-finding. Unity has a path subsystem you can use. It’ll be the way to go for 3D games, specially if you need to move long distances and around obstacles. Check here for more info: Unity Navmesh docs
  2. Use a raycast. If you don’t need to traverse around obstacles or just want to stop the player from entering world objects, or if you have a 2D game and you can’t use navmeshes, this will be the way to go. Check here for more information: Unity raycast tutorial