Search Unity

Limit path to distance

Discussion in 'Navigation' started by Corva-Nocta, Jun 6, 2019.

  1. Corva-Nocta

    Corva-Nocta

    Joined:
    Feb 7, 2013
    Posts:
    801
    I've been googling and trying to find the answer to this but I think I'm just looking in the wrong places, so any help at all would be great!

    I have a simple move system for my turn based game. You click where you want your character to move and he navigates to that spot. Simple. Now I want to limit how far the player will move with each move command, so if his speed is 9 lets say, he will stop moving once he has moved 9 units.

    Now I could get the Vector3.Distance between the start position and the end position and just abruptly stop the player once the distance is 9 (using the example above) which is ok, but I don't like the sudden stop. My plan is to speed up and slow down the player nesr stsrting and stopping point, basically lerping/slerping the movement.

    So if I click way out in the map, how can I set the target that I move to to be exactly 9 (again just using an example number) units away from the player but in the direction that was clicked. For example if I clicked 20 units away, I want to draw a line between that point and the player, then set the new move to point at 9 units.

    Any suggestions?
     
  2. Yandalf

    Yandalf

    Joined:
    Feb 11, 2014
    Posts:
    491
    Well this might get a little tricky. First of all do not simply check your agent's position based on starting position, because when your agent makes corners to walk around objects that distance can decrease again, allowing your agent to travel less far or further than they should be able to.
    I'd suggest first calculating the path to your clicked destination without setting it on the agent.
    To do this, use NavMesh.CalculatePath(origin, destination, mask, path), then take the resulting path's corners with path.corners. Then you simply loop over that array and add up the distances between the corners until you have a bigger distance than your agent can travel. Find the point between the last two corners you iterated over, and set your agent's destination to that point.
     
  3. Corva-Nocta

    Corva-Nocta

    Joined:
    Feb 7, 2013
    Posts:
    801
    Interesting, I never knew about the CalculatePath. I'll definitely give that a look at! It there's lots of terrain that will be handy for accurate distances