Advertisement
EmmyDev

Rail Follow

Dec 29th, 2022 (edited)
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.44 KB | Source Code | 0 0
  1. using UnityEngine;
  2.  
  3. namespace PathCreation.Examples
  4. {
  5.     // Moves along a path at constant speed.
  6.     // Depending on the end of path instruction, will either loop, reverse, or stop at the end of the path.
  7.     public class PathFollower : MonoBehaviour
  8.     {
  9.         public PathCreator pathCreator;
  10.         public EndOfPathInstruction endOfPathInstruction;
  11.         public float speed = 5;
  12.         public float distanceTravelled;
  13.  
  14.         void Start() {
  15.             if (pathCreator != null)
  16.             {
  17.                 // Subscribed to the pathUpdated event so that we're notified if the path changes during the game
  18.                 pathCreator.pathUpdated += OnPathChanged;
  19.             }
  20.         }
  21.  
  22.         void Update()
  23.         {
  24.             if (pathCreator != null)
  25.             {
  26.                 distanceTravelled += speed * Time.deltaTime;
  27.                 transform.position = pathCreator.path.GetPointAtDistance(distanceTravelled, endOfPathInstruction);
  28.                 transform.rotation = pathCreator.path.GetRotationAtDistance(distanceTravelled, endOfPathInstruction);
  29.             }
  30.         }
  31.  
  32.         // If the path changes during the game, update the distance travelled so that the follower's position on the new path
  33.         // is as close as possible to its position on the old path
  34.         void OnPathChanged() {
  35.             distanceTravelled = pathCreator.path.GetClosestDistanceAlongPath(transform.position);
  36.         }
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement