Answers for "Find the average of 10 Vectors"
http://answers.unity.com/questions/164257/find-the-average-of-10-vectors.html
The latest answers for the question "Find the average of 10 Vectors"Answer by grofie
http://answers.unity.com/answers/588788/view.html
All previous posts forget to divide through the number of entries.
Try this piece of code:
private Vector3 GetMeanVector(Vector3[] positions)
{
if (positions.Length == 0)
return Vector3.zero;
float x = 0f;
float y = 0f;
float z = 0f;
foreach (Vector3 pos in positions)
{
x += pos.x;
y += pos.y;
z += pos.z;
}
return new Vector3(x / positions.Length, y / positions.Length, z / positions.Length);
}Tue, 03 Dec 2013 15:31:21 GMTgrofieAnswer by CHPedersen
http://answers.unity.com/answers/164294/view.html
Much of that loop is wrong, I'm afraid. :P
Thor is correct that you're getting the exception because you've incremented i to a number greater than the length of the Array-1, but he's wrong to say that the loop must run while i is less than numberOfPoints-1. Because arrays are zero-indexed, accessing an element at the index i is valid as long as i is less than the length (and greater than or equal to 0), not length-1.
In general, it's bad form to use constant numbers as the limit of array iteration, unless you can be perfectly sure your array's runtime length never deviates from that number. It's always better to use Array.length as the limit in the loop instead of some integer you've set.
In addition to these facts, be mindful of changing your iterator (i) inside the loop: You've got code that says positions[i++] inside the loop body. This can be dangerous business and generally shouldn't be done unless you're absolutely sure about what you're doing. As you know, i++ is short-hand for i = i + 1;, so if you increment i there, then i will get incremented again by the for-loop on the next iteration, causing you to effectively skip an element in the array.
Finally, if the 'average' you want is a single vector that points in the direction you'd be headed if you followed each of the component vectors one by one, the result is just the sum of all the component vectors. Here's a snippet that does that:
Vector3[] vectors = new Vector3[10];
Vector3 average = Vector3.zero;
for (int i = 0; i < vectors.Length; i++)
{
average += vectors[i];
}
Translation to JS is a pretty straight forward. :)Wed, 07 Sep 2011 08:53:12 GMTCHPedersenAnswer by thor_tillas
http://answers.unity.com/answers/164266/view.html
As far as I understand, you have to do your loop as long as i is under numberOfPoints - 1 instead of numberofPoints.
Otherwise, the line
positions[i++] = o;
while raise a "Out of bounds" exception.
But this works only when your "Position" array is initialized with "numberOfPoints" position...
Hope it's helped !
Cheers,
ThorWed, 07 Sep 2011 07:45:46 GMTthor_tillas