- Home /
Distance between a waypoint and the object
I have calculate the distance between an object and waypoints. I have taken waypoints as transform[], which is an array. The problem is:- I am not able to calculate the distance between the object and respective waypoints in the code.
Despite giving var k,l,m,.... = Vector3.Distance(waypoint[0,1,2,...].position,object.transform.position);
I am not able to find the distance. If I haven't given the waypoints in an array, the code will work. But I have to give it in an array. But how!
Please help. Thanks in advance.
$$anonymous$$hm? You have to use a FOR, arrays simply can't be passed to Distance. Why you're saying you can't?
Answer by ptdnet · Dec 01, 2011 at 05:47 PM
The distance between any two points in 3d space is a simple formula:
dist = sqrt((x2-x1)^2 + (y2-y1)^2 + (z2-z1)^2)
Answer by suruz@kento · Dec 01, 2011 at 07:26 PM
Say you have N waypoints and should be stored in a array wayPoints.First create wayPoints with N elements and initialise.
var wayPoints: Transform[];
var distances: float[];
var myObject: GameObject;
var N: int = 5; //initialise yours
function Start() {
initWayPoints();
}
function initWayPoints() {
wayPoints = new Transform[N];
distances = new float[N];
//asume your waypoint objects are stored in wayPoints ,such that
//wayPoints[0] = ObjA.transform;
//wayPoints[1] = ObjB.transform;
//wayPoints[2] = ObjC.transform;
//..............................
//..............................
//wayPoints[N-1] = ObjN.transform;
}
function calcObjectToWayPoints() {
for( var i = 0 ; i < N ; i++)
{
if(wayPoints[i])
{
distances[i] = (wayPoints[i].position - myObject.transform.position).magnitude;
}
else
{
print("way point not set to wayPoints");
}
}
}
function Update() {
calcObjectToWayPoints();
for( var i = 0 ; i < N ; i++) { print("distances[" + i + "]:"+ distances[i] ); }
}
Your answer
Follow this Question
Related Questions
Getting vectors on an object every so many units 0 Answers
Load Object(3d model) by name with script at scene 2 Answers
How to make a drag and drop menu in 2d for a 3d game (sims 4 furniture like) 0 Answers
I try to move my 3D object in the game but it only on the X & Z axis, can someone help me with that 1 Answer