Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class RailTest : MonoBehaviour {
- public Vector3[] nodes;
- public LineRenderer visualisation;
- public float demo;
- public GameObject go;
- void OnValidate() {
- visualisation.positionCount = nodes.Length;
- visualisation.SetPositions(nodes);
- string msg = "";
- go.transform.position = DistanceToPoint(demo);
- Debug.Log(msg);
- }
- float NodeToDistance(int node) {
- if (node > nodes.Length - 1) {
- node = nodes.Length - 1;
- }
- float sum = 0f;
- for (int i = 0; i < node; i++) {
- sum += Vector3.Distance(nodes[i], nodes[i + 1]);
- }
- return sum;
- }
- int DistanceToNode(float dist) {
- float sum = 0f;
- float lastSum = 0f;
- for (int i = 0; i < nodes.Length; i++) {
- if (i != nodes.Length) {
- sum += Vector3.Distance(nodes[i], nodes[i + 1]);
- }
- if (lastSum > dist && dist < sum) {
- return i;
- }
- lastSum = sum;
- }
- return -1;
- }
- Vector3 DistanceToPoint(float dist) {
- float sum = 0f;
- int indexFirst = -1;
- int indexSecond = -1;
- for (int i = 0; i < nodes.Length - 1; i++) {
- sum += Vector3.Distance(nodes[i], nodes[i + 1]);
- if (sum >= dist) {
- indexFirst = i;
- indexSecond = i + 1;
- break;
- }
- }
- float distanceFirst = NodeToDistance(indexFirst);
- float distanceSecond = NodeToDistance(indexSecond);
- float distanceDifference = distanceSecond - distanceFirst;
- // The following line was the only one that was wrong.
- float percent = (dist-distanceFirst) / distanceDifference;
- // There is a Vector3.Lerp function, no need to use Mathf.Lerp three times.
- Vector3 ret = Vector3.Lerp(nodes[indexFirst], nodes[indexSecond], percent);
- // I suggest you add a toggle option for using worldspace/local space,
- // and apply it to the visualization in OnValidate, as well as here.
- // ret += transform.position;
- return ret;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement