Search Unity

Vector Magnitude Does Not Drop to Zero as Character Reaches Destination (click to move)

Discussion in 'Scripting' started by davidhfw, Apr 30, 2017.

  1. davidhfw

    davidhfw

    Joined:
    Aug 17, 2016
    Posts:
    77
    The codes move the player with click to move. However, when the player reaches the destination, it does not stay still and attempt to move on the spot.

    playerToClickPoint is the vector from the player position to destination.
    currentDestination is the vector from origin to destination.
    transform.position is the vector from origin to the player position.

    WalkToDestination() is a method in FixedUpdate().

    Code (CSharp):
    1. private void WalkToDestination()
    2. {
    3.     var playerToClickPoint = currentDestination - transform.position;
    4.     if (playerToClickPoint.magnitude > 0)
    5.     {
    6.         thirdPersonCharacter.Move(playerToClickPoint, false, false);
    7.     }
    8.     thirdPersonCharacter.Move(Vector3.zero, false, false); // #1
    9. }
    As the player moves closer to the destination, theoretically the value of playerToClickPoint.magnitude decreases until it reaches 0 when he reaches the destination since currentDestination = transform.position. With that, the code at #1 will run and bring the player to a still.

    However, the problem is playerToClickPoint.magnitude does not reach zero. It will drop until it reaches about 0.2 and sometimes 0.4 and stays there. The code to stop the player movement at #1 was never executed. So changing the code to "if (playerToClickPoint.magnitude > 0.5f)" will resolve the issue, but is that the correct way to resolve it? It is not ideal as the player is not exactly at the destination where I click, but offset by 0.5f.

    Any advice is greatly appreciated!

    Thanks!

    PS. The thirdPersonCharacter.Move() code is from third person character Unity standard asset.
     
  2. Donay

    Donay

    Joined:
    Apr 28, 2017
    Posts:
    70
    Is the player moving over terain? The issue could by a Y offset in the magnitude which it can never reach.
    you could try if ((playerToClickPoint.x=0) && (playerToClickPoint.z=0))