NeoGriever

Untitled

Oct 9th, 2020
633
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class JustMove : MonoBehaviour {
  6.   public List<Vector2> points = new List<Vector2>();
  7.  
  8.   [Range(0.0001f, 4.0000f)]
  9.   public float speedPerSecond = 0.3f;
  10.  
  11.   public bool startAtPoint0 = true;
  12.   public bool autostart = false;
  13.   public bool loop = true;
  14.   private bool running = false;
  15.  
  16.   private Rigidbody2D rb;
  17.  
  18.   public void Begin() {
  19.     running = true;
  20.   }
  21.   void Start() {
  22.     rb = GetComponent<Rigidbody2D>();
  23.     if(startAtPoint0) {
  24.       transform.position = new Vector3(points[0].x, points[0].y, transform.position.z);
  25.     }
  26.     if(autostart) {
  27.       Begin();
  28.     }
  29.   }
  30.   void FixedUpdate() {
  31.     if(running && points.Count > 0) {
  32.       Vector2 p = points[0];
  33.       if(Vector2.Distance(p,new Vector2(transform.position.x, transform.position.y)) < speedPerSecond * Time.fixedDeltaTime) {
  34.         points.RemoveAt(0);
  35.         if(loop) {
  36.           points.Add(p);
  37.         }
  38.         p = points[0];
  39.       }
  40.       Vector2 targetDirection = (p - new Vector2(transform.position.x, transform.position.y)).normalized;
  41.       rb.velocity = targetDirection * speedPerSecond;
  42.     }
  43.   }
  44.   void OnDrawGizmos() {
  45.     Gizmos.color = Color.yellow;
  46.     Gizmos.DrawLine(transform.position, points[0]);
  47.     for(int i = 1;i < points.Count;i++) {
  48.       Gizmos.DrawLine(points[i-1], points[i]);
  49.     }
  50.     Gizmos.DrawLine(points[points.Count - 1], points[0]);
  51.   }
  52. }
  53.  
RAW Paste Data