Search Unity

How to move along a few path follow?

Discussion in 'Scripting' started by polan31, Sep 21, 2018.

  1. polan31

    polan31

    Joined:
    Nov 20, 2017
    Posts:
    149
    How to make the object after pressing the left mouse button move along the first path follow, stopped at the end and after repeated pressing the button moved the second path follow and etc.

    I guess I should do it using the list.

    I always have a big problem with the lists, I do not understand them completely, that's why I am asking for help.

    I thought to create a path follow list, which object must pass.

    Then give each of the path an index number.

    And in the code for the object, write that it must pass them all in the correct order.

    After passing the first path, it stops and waits until I press the left mouse button to go through the next one.

    I do not know how to write it.

    My moving script:

    Code (CSharp):
    1.  using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PathFollower1 : MonoBehaviour {
    6.  
    7.      public float speed = 3f;
    8.      public Transform pathParent;
    9.  
    10.      Transform targetPoint;
    11.      int index;
    12.  
    13.      bool rightClicked = false;
    14.      public float speedRotate = 7f;
    15.  
    16.      Vector3 distance;
    17.      Quaternion newRotate;
    18.  
    19.      void Start () {
    20.          index = 0;
    21.          targetPoint = pathParent.GetChild (index);
    22.      }
    23.      void Update () {
    24.          if (Input.GetMouseButtonDown (0)) {
    25.              rightClicked = true;
    26.          }
    27.          if(rightClicked)
    28.              Move ();
    29.      }
    30.    
    31.      
    32.      void Move() {
    33.          transform.position = Vector3.MoveTowards (transform.position, targetPoint.position, speed * Time.deltaTime);
    34.          rotate ();
    35.          if (Vector3.Distance (transform.position, targetPoint.position) < 0.1f)
    36.          {
    37.              index++;
    38.              index %= pathParent.childCount;
    39.              targetPoint = pathParent.GetChild (index);
    40.      }
    41. }
    42.      void rotate ()
    43.      {
    44.          distance = transform.position - targetPoint.position;
    45.          newRotate = Quaternion.LookRotation (distance, transform.forward);
    46.          newRotate.x = 0;
    47.          newRotate.y = 0;
    48.          transform.rotation = Quaternion.Lerp (transform.rotation, newRotate, speedRotate * Time.deltaTime);
    49. }
    50. }