Advertisement
Guest User

Untitled

a guest
Jan 18th, 2020
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.92 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class Rail : MonoBehaviour {
  6.     public Vector3[] nodes;
  7.     public LineRenderer visualisation;
  8.     public float demo;
  9.     public GameObject go;
  10.  
  11.     void OnValidate() {
  12.         visualisation.positionCount = nodes.Length;
  13.         visualisation.SetPositions(nodes);
  14.         string msg = "";
  15.         go.transform.position = distanceToCoordinate(demo);
  16.         Debug.Log(msg);
  17.  
  18.     }
  19.  
  20.     float NodeToDistance(int node) {
  21.         if (node > nodes.Length - 1) {
  22.             node = nodes.Length - 1;
  23.         }
  24.        
  25.         float sum = 0f;
  26.         for (int i = 0; i < node; i++) {
  27.             sum += Vector3.Distance(nodes[i], nodes[i + 1]);
  28.         }
  29.  
  30.         return sum;
  31.     }
  32.  
  33.     int DistanceToNode(float dist) {
  34.         float sum = 0f;
  35.         float lastSum = 0f;
  36.         for (int i = 0; i < nodes.Length; i++) {
  37.             if (i != nodes.Length) {
  38.                 sum += Vector3.Distance(nodes[i], nodes[i + 1]);
  39.             }
  40.             if (lastSum > dist && dist < sum) {
  41.                 return i;
  42.             }
  43.             lastSum = sum;
  44.         }
  45.  
  46.         return -1;
  47.     }
  48.  
  49.     Vector3 distanceToCoordinate(float dist) {
  50.         float sum = 0f;
  51.         int indexFirst = -1;
  52.         int indexSecond = -1;
  53.         for (int i = 0; i < nodes.Length - 1; i++) {
  54.             sum += Vector3.Distance(nodes[i], nodes[i + 1]);
  55.             if (sum >= dist) {
  56.                 indexFirst = i;
  57.                 indexSecond = i + 1;
  58.                 break;
  59.             }
  60.         }
  61.         float distanceFirst = NodeToDistance(indexFirst);
  62.         float distanceSecond = NodeToDistance(indexSecond);
  63.         float distanceDifference = distanceSecond - distanceFirst;
  64.         // The following line was the only one that was wrong.
  65.         float percent = (dist-distanceFirst) / distanceDifference;
  66.  
  67.         // There is a Vector3.Lerp function, no need to use Mathf.Lerp three times.
  68.         Vector3 ret = Vector3.Lerp(nodes[indexFirst], nodes[indexSecond], percent);
  69.  
  70.         // I suggest you add a toggle option for using worldspace/local space,
  71.         // and apply it to the visualization in OnValidate, as well as here.
  72.         // ret += transform.position;
  73.         return ret;
  74.     }
  75.    
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement