SebastianLague

Path mover with reverse

Jul 16th, 2018
366
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.72 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class Move : MonoBehaviour {
  6.  
  7.     public float speed = 4;
  8.     public float pathResolution = .05f;
  9.     public float turnSpeed = 6;
  10.     Path v;
  11.     Vector2[] points;
  12.     int iOld;
  13.     int i;
  14.     bool reverseDirection;
  15.  
  16.     void Start () {
  17.         v = FindObjectOfType<PathCreator>().path;
  18.         points = v.CalculateEvenlySpacedPoints(pathResolution);
  19.         transform.position = points[i];
  20.         i = 1;
  21.     }
  22.  
  23.     void Update () {
  24.         MoveStep(Time.deltaTime * speed);
  25.  
  26.         if (Input.GetKeyDown(KeyCode.Space))
  27.         {
  28.             ReverseDirection();
  29.         }
  30.     }
  31.  
  32.     void ReverseDirection()
  33.     {
  34.         reverseDirection = !reverseDirection;
  35.         int t = i;
  36.         i = iOld;
  37.         iOld = t;
  38.     }
  39.  
  40.     void MoveStep(float dst)
  41.     {
  42.         Vector2 targetPos = points[i];
  43.         Vector2 offset =points[i] - (Vector2)transform.position;
  44.         float dstToTarget = offset.magnitude;
  45.         Vector2 dirToTarget = offset.normalized;
  46.  
  47.         Quaternion currentRot = transform.rotation;
  48.         transform.right = dirToTarget;
  49.         Quaternion targetRot = transform.rotation;
  50.         transform.rotation = Quaternion.Slerp(currentRot, targetRot, Time.deltaTime * turnSpeed);
  51.  
  52.         float dstToMove = Mathf.Min(dst, dstToTarget);
  53.         transform.Translate(dirToTarget * dstToMove, Space.World);
  54.  
  55.         if (dstToMove == dstToTarget)
  56.         {
  57.             iOld = i;
  58.             i = (points.Length + i + ((reverseDirection) ? -1 : 1)) % points.Length;
  59.         }
  60.  
  61.         float dstRemaining = dst - dstToMove;
  62.  
  63.         if (dstRemaining > .001)
  64.         {
  65.             MoveStep(dstRemaining);
  66.         }
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment