SebastianLague

Path mover

Jul 14th, 2018
608
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.38 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.  
  15.     void Start () {
  16.         v = FindObjectOfType<PathCreator>().path;
  17.         points = v.CalculateEvenlySpacedPoints(pathResolution);
  18.         transform.position = points[i];
  19.         i = 1;
  20.     }
  21.    
  22.     void Update () {
  23.         MoveStep(Time.deltaTime * speed);
  24.     }
  25.  
  26.     void MoveStep(float dst)
  27.     {
  28.         Vector2 targetPos = points[i];
  29.         Vector2 offset =points[i] - (Vector2)transform.position;
  30.         float dstToTarget = offset.magnitude;
  31.         Vector2 dirToTarget = offset.normalized;
  32.  
  33.         Quaternion currentRot = transform.rotation;
  34.         transform.right = dirToTarget;
  35.         Quaternion targetRot = transform.rotation;
  36.         transform.rotation = Quaternion.Slerp(currentRot, targetRot, Time.deltaTime * turnSpeed);
  37.  
  38.         float dstToMove = Mathf.Min(dst, dstToTarget);
  39.         transform.Translate(dirToTarget * dstToMove, Space.World);
  40.  
  41.         if (dstToMove == dstToTarget)
  42.         {
  43.             i = (i + 1) % points.Length;
  44.         }
  45.  
  46.         float dstRemaining = dst - dstToMove;
  47.  
  48.         if (dstRemaining > .001)
  49.         {
  50.             MoveStep(dstRemaining);
  51.         }
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment