Search code examples
unity-game-engineonclickreal-time-strategy

Unity raycast returns center of object, not a point


I want to create a click-to-move game, and have got a nav-mesh agent with code which almost works, except my character always attempts to move to the same spot, regardless of where I click or the position of the camera. This is my function,

private Vector3 GetClickPosition()
{
    Vector2 screenPosition = Input.mousePosition;
    Vector3 mouseWorldPosition = cam.ScreenToWorldPoint(screenPosition);

    RaycastHit hitPosition;

    Physics.Raycast(mouseWorldPosition, cam.transform.forward, out 
    hitPosition, 100, Floor);

    return hitPosition.point;
}

Which is used in an on-click command connecting to the player. Everything is referenced and I'm sure the problem is with this piece of code... Thanks in advance.

My source for this code: https://www.youtube.com/watch?v=LoKNYlWWeSM


Solution

  • The source you reference works for me so perhaps something has gone slightly off in your version.

    Try assigning the appropriate layer, the one that is referenced as Floor in your Physics.Raycast method, onto the terrain you want to navigate. You may have missed out on this if you renamed the groundLayer mentioned in the source but didn't create and assign the corresponding layer in the editor. Be sure to also set the floor you are using to be static in the Navigation -> Object tab.