Reputation: 22837
I am working on a project in Unity 4.6. I am wondering if there is an easy way to programmatically set the vertex locations. Currently my code looks like this (C#):
public void createPoints(float x, float y, float z) {
point [0] = new Vector3 (x, y, z);
point [1] = new Vector3 (x, y, -z);
point [2] = new Vector3 (x, -y, z);
point [3] = new Vector3 (x, -y, -z);
point [4] = new Vector3 (-x, y, z);
point [5] = new Vector3 (-x, y, -z);
point [6] = new Vector3 (-x, -y, z);
point [7] = new Vector3 (-x, -y, -z);
}
Where x, y, and z are predetermined values and point is a Vector3[]
(array). The prism's centre is to be point 0,0,0
(Vector3(0,0,0)
in Unity).
As an example, using the following values:
The points generated should be the following (order does not matter):
My question: Is there a way to generate these points without practically hardcoding the values in?
My current code for the desired solution is:
public void createPoints(float originalX, float originalY, float originalZ) {
for (int i = 0; i < 8; i++) { //8 vertices exist of a rectangular prism
point [i] = new Vector3 (x, y, z);
}
}
How do I change this code to generate these positive and negative points? My guess is some sort of alternation between positive and negative values for x, y, and z, using modulus of i
or rounding of the division of i
by some other integer, however I cannot wrap my brain around it. C# or UnityScript are OK.
In other words, in each iteration of the for loop, x = -x
, for each something y = -y
, for each something z = -z
.
Any help with this is greatly appreciated.
Upvotes: 1
Views: 286
Reputation: 1019
I don't know how if my Unity syntax is correct, but this code should be modifiable to work there. Basically, it gives you 8 vectors. The x values are x, -x, x, -x, ... The y values are y, y, -y, -y, y, y, ... and the z values are z, z, z, z, -z, -z, -z, -z. This is done by multiplying by -1 to even and odd powers.
function createPoints(x, y, z) {
var resp = [];
for (var i = 0; i < 8; ++i) {
var vect = new Vector3d(x * Math.pow(-1, i), y * Math.pow(-1, Math.floor(i / 2)), z * Math.pow(-1, Math.floor(i / 4)));
resp.push(vect);
}
return resp;
}
createPoints(1,2,3);
Upvotes: 1
Reputation: 15364
I would use linq for this
var alt = new[] { 1, -1 };
var result = ( from i in alt
from j in alt
from k in alt
select new Vector3(i * 1, j * 2, k * 3)
).ToList();
Upvotes: 3
Reputation: 7679
You can do this with nested for
loops like so:
List<Vector3> points = new List<Vector3>();
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
for (int k = 0; k < 2; k++)
points.Add(new Vector3(i == 0 ? originalX : -originalX,
j == 0 ? originalY : -originalY,
k == 0 ? originalZ : -originalZ));
Vector3[] point = points.ToArray();
There probably is an easier, cleaner way to do this, but it does work.
Upvotes: 3