Search Unity

Move player to target point / destination

Discussion in 'Editor & General Support' started by guru20, Jul 31, 2015.

  1. guru20

    guru20

    Joined:
    Jul 30, 2013
    Posts:
    239
    I know this question has been asked many times before, but I never seem to find a complete answer in the searches I've done (just "hints" or "clues" about general functions to call)

    I am trying to move the main player/character to a target selected on the ground/floor plane. I'd like to have the player character do an animated walk over there at constant speed (ie. continue walking at that speed until destination reached.) I don't want the rules of physics/collisions to disappear in the process, so this is why I am not simply lerping or moving transform to location... seems like I need to use CharacterController?

    So, I have a few questions:
    1) Do I need to go through the CharacterMotor to do this? Or can I bypass that script and access the CharacterController directly?
    2) How? Obviously I'd really only be moving along two axes (not all 3; otherwise, the character would be going down into the floor at the selected point)

    Is there anybody who has a completed script that does this? I haven't found one, but it seems like a pretty common game task/feature....
     
  2. guru20

    guru20

    Joined:
    Jul 30, 2013
    Posts:
    239
    Never mind, I found correct solution... I just didn't realize that my Update scripting was preventing it from sort of running as a while loop. I just had to set a boolean flag to ignore the rest of the Update script until destination reached, and it worked fine:

    Code (CSharp):
    1. void MoveTowardsTarget(Vector3 target) {
    2.         var offset = target - playerController.transform.position;
    3.         //Get the difference.
    4.         if (offset.magnitude > 0.1f) {
    5.             //If we're further away than .1 unit, move towards the target.
    6.             //The minimum allowable tolerance varies with the speed of the object and the framerate.
    7.             // 2 * tolerance must be >= moveSpeed / framerate or the object will jump right over the stop.
    8.             offset = offset.normalized * 5.0f;
    9.             //normalize it and account for movement speed.
    10.             playerController.Move (offset * Time.deltaTime);
    11.             //actually move the character.
    12.         } else {
    13.             moving = false;
    14.             timer = 2.5f; // reset timer
    15.         }
    16.     } // end MoveTowardsTarget
     
  3. Fantastic Worlds Studio

    Fantastic Worlds Studio

    Joined:
    Apr 26, 2015
    Posts:
    48
    One of those moments we all have when we smack ourselves in the head.
     
  4. AndrewJamesBowen

    AndrewJamesBowen

    Joined:
    Oct 10, 2013
    Posts:
    13
    7 years on, and you saved me :)