Reputation: 113
I'm working on a personal project in which I want to visualize airplanes above airports. I created a .csv file containing the coordinates of one airplane over a certain period of time. I tried to write a code in Unity in which the coordinates are linked to a cube and moves over time. Unfortunately my code does not work.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO
public class AirplanePlayer : MonoBehaviour
{
public GameObject airplane;
public TextAsset csvFile;
// Update is called once per frame
void Update() {
}
void readCSV()
{
string[] records = csvFile.text.Split('\n');
for(int i = 0; i < records; i++)
{airplane.transform.position(float.Parse(fields[2]),float.Parse(fields[3]), float.Parse(fields[4]));
}
}
}
Expected results would be a cube which moves in different directions over time. Would love some tips, thank you in advance!
Upvotes: 0
Views: 1268
Reputation: 188
To move the plane between points you could use the Vector3.MoveTowards method. Here is a very basic implementation of what I understand you are trying to accomplish:
public class PlaneController : MonoBehaviour
{
public TextAsset coordinates;
public int moveSpeed;
string[] coordinatesArray;
int currentPointIndex = 0;
Vector3 destinationVector;
void Start()
{
coordinatesArray = coordinates.text.Split(new char[] { '\n' });
}
void Update()
{
if (destinationVector == null || transform.position == destinationVector)
{
currentPointIndex = currentPointIndex < coordinatesArray.Length - 1 ? currentPointIndex + 1 : 1;
if(!string.IsNullOrWhiteSpace(coordinatesArray[currentPointIndex]))
{
string[] xyz = coordinatesArray[currentPointIndex].Split(new char[] { ',' });
destinationVector = new Vector3(float.Parse(xyz[0]), float.Parse(xyz[1]), float.Parse(xyz[1]));
}
}
else
{
transform.position = Vector3.MoveTowards(transform.localPosition, destinationVector, Time.deltaTime * moveSpeed);
}
}
}
I also made it do a little loop with the coordinates and added a speed property.
I'm not really sure if adding the csv file as public TextAsset for the game object is the right approach, maybe it makes more sense to use the file path for the csv file instead and get the file data from code.
Hope this helps, let me know if you have any more questions.
Upvotes: 2