Click to Move and NavMesh Problems

So I’m having a problem with my Click-to-Move and NavMesh.

When I click on a game object with a collider my character will move their with no issue. The issue comes from when I click on an area not covered by my NavMesh and my character walks on the edge of the NavMesh trying to reach that point until I select a new location he can actually reach.

Is there a way to get my character to stop on the edge of the NavMesh or to make my NavMesh the target for my raycast so I can remove all the colliders from my level map?

Feel free to answer in C#.


var targetPosition : Vector3;

private var agent : NavMeshAgent;

function Start()
{
     agent = GetComponent(NavMashAgent);
     targetPosition = transform.position;
}

function Update()
{
     if (Input.GetMouseButton(0))
     {
          setPosition();
          agent.SetDesination(targetPosition);
     }
}

function setPosition()
{
     var mousePosition : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
     var hit : RaycastHit;

     if (Physics.Raycast(mousePosition, hit, 1000))
     {
          targetPosition = hit.point;
     }
}

33094-infinitewalk.png

2 Answers

2

Here is my solution, and it works like a charm thanks to Slavo and Spolglase.


// Nav Mesh Variables
var agent : NavMeshAgent;
var navHitPosition : NavMeshHit;
var cursorPosition : Vector3;

function Start()
{
    agent = GetComponent(NavMeshAgent);
}

function Update()
{
    // Locate Cursor
    var mouseClick = Camera.main.ScreenPointToRay(Input.mousePosition)
    var hit : RaycastHit;

    if (Physics.Raycast(mouseClick, hit, 1000))
    {
        cursorPosition = hit.point;
    }

    // Set and move to target position
    NavMesh.SamplePosition(cursorPosition, navHitPosition, 0.1, 
                           1 << NavMesh.GetNavMeshLayerFromName("Default"));

    if (Input.GetMouseButton(0))
    {
        agent.SetDestination(navHitPosition.position);
    }
}

YOu can try to use this to find nearst point on navmesh

NavMesh.SamplePosition

Solved. Thanks for the tip Slavo.

No problem at all. Feel free to like my answer if it lets you to higher understanding.