I just started taking a class on unity, I apologize if I’m really noob at this. I’ve done some programming here and there, but my major doesn’t really require us to take that many classes on programming like computer science majors.
So here’s my problem.
We need to create a javascript that will generate boxes in some specific way, like so: * will represent a cube
----**
—****
–******
-********
However after many hours of trying to figure this out, I’m stuck with this:
**
We’re suppose to modify our professors code in order to produce the pyramid.
Here’s my code:
var myBox: Transform;
function Start () {
for (var i = 1; i<=10-i; i++) {
for (var j = 10; j>=(i*2)-1; j--) {
var xpos = i * 10;
var zpos = j * 10;
var instanceObj = Instantiate (myBox, Vector3(xpos, 50, zpos), Quaternion.identity);
}
}
}
What am I doing wrong and how can I make it right?
You’re always starting j at 10, so the zpos will always be 100, resulting in the right-triangle shape you’ve seen. To get a pyramid, you need to change the start for j as well as the end.
Also, why are you using “i <= 10-i” instead of just “i <= 5”?
You need to offset zpos by an amount related to I (row index).
The bottom row is offset by zero, the next up is offset by one (cube), the next by two, etc.
If you know the maximum row is “maxRow”, then:
zpos = j * 10 + (maxRow - i) * 10
Then if (i==maxRow) there’s no offset; if (i==maxRow-1) there’s a single offset, etc.
Based on your example with five rows, on row one you have (5-1=4) cubes offset, on row two you have (5-2=3) cubes offset.
It’s helpful (to me) to associativize or whatever that:
zpos = ( j + (maxRow - i) ) * 10;
Then you can see you’re putting a block at the “logical position” of (j+maxrow-i), then to get the block to the right “real position” you’re scaling by ten.