Search Unity

Making the player move along a path at a specific trigger?

Discussion in 'Scripting' started by skoteskote, Jan 28, 2018.

  1. skoteskote

    skoteskote

    Joined:
    Feb 15, 2017
    Posts:
    87
    Hi all, I have followed a tutorial for making an object move along a path and altered it so it moves the player when triggered. Instead of moving along the path the player is thrown into the horizon at great speed. I tried destroying the rigidbody when triggered as well, but to no avail.

    Any ideas?

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PathFollower : MonoBehaviour
    6. {
    7.  
    8.     public Transform[] path;
    9.     public float speed = 5.0f;
    10.     public float reachDist = 1.0f;
    11.     public int currentPoint = 0;
    12.  
    13.     private GameObject playerToMove;
    14.     private Rigidbody rbody;
    15.  
    16.     private bool movePlayer = false;
    17.  
    18.     void Start ()
    19.     {
    20.      
    21.     }
    22.  
    23.     void Update ()
    24.     {
    25.         if (movePlayer) {
    26.             MovePlayer ();
    27.         }
    28.     }
    29.  
    30.     void MovePlayer ()
    31.     {
    32.  
    33.         Vector3 dir = path [currentPoint].position - transform.position;
    34.  
    35.         playerToMove.transform.position += dir * Time.deltaTime * speed;
    36.  
    37.         if (dir.magnitude <= reachDist) {
    38.             currentPoint++;
    39.         }
    40.  
    41.         if (currentPoint >= path.Length) {
    42.             movePlayer = false;
    43.         }
    44.     }
    45.  
    46.     void OnTriggerEnter (Collider other)
    47.     {
    48.         if (other.gameObject.tag == "camera") {
    49.             playerToMove = other.gameObject;
    50.             //Destroy(playerToMove.GetComponent<Rigidbody>());
    51.             movePlayer = true;
    52.         }
    53.     }
    54.  
    55.     void OnDrawGizmos ()
    56.     {
    57.         for (int i = 0; i < path.Length; i++) {
    58.             if (path [i] != null) {
    59.                 Gizmos.DrawSphere (path [i].position, reachDist);
    60.             }
    61.         }
    62.     }
    63. }
    64.  
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    How do you normally move the player? It might still be wrestling for control if you haven't explicitly disabled it / zeroed out the velocity of the rigidbody beforehand.

    If you're going to manually move a rigidbody, mark isKinematic to true or alternatively use rigidbody.MovePosition() to move your object manually rather than moving the transform directly and then all of your other collisions will still work.
     
    skoteskote likes this.
  3. skoteskote

    skoteskote

    Joined:
    Feb 15, 2017
    Posts:
    87