Public Group

# Simple for loop issue

This topic is 2120 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I have three for loops that are used to loop through an array of cubes and set the World matrix to a position. The problem is that all the cubes are being drawn on top of each other. Am i missing something? I was able to do this before somehow. Would the order of the loops matter? My goal here is to create a 10x10 grid of cubes.

http://pastebin.com/LcvSCLV8

Im on my phone so i cant post any code so sorry for the inconvenience :S

##### Share on other sites

The particular problem you're having has nothing to do with the for loops.

You're trying to use the world matrix as a vector... or something.  It's hard to describe.

Your WVP matrix is the multiplication of "World", "View", and "Projection"; currently you're just multiplying VP together.

Likewise you probably shouldn't be setting your vertex declaration to your world matrix.  I think this is XNA, and if it is, that doesn't seem right.

EDIT:  Does this help?

http://blogs.msdn.com/b/shawnhar/archive/2010/06/17/drawinstancedprimitives-in-xna-game-studio-4-0.aspx

Edited by SeraphLance

L. Spiro

##### Share on other sites

Looking at the code there, these cubes are 2x2x2, so you want to space by that much.  However, seeing as how you're spacing them on 1x1 intervals, they shouldn't be completely on top of each other.

##### Share on other sites
Each cube would have a vector position of (x + 1, 0, z + 1). So i think they're being spread far enough apart

##### Share on other sites
Oh i got it. Removed the first loop and used x * z for the index. But now they're drawn sporadically almost. Strange. I did shrink the sizes down too

##### Share on other sites

It should be x * 2 and z * 2.

L. Spiro

##### Share on other sites
I shrunk the cubes so theyre 1x1x1. They're not overlapping but drawing strangley

##### Share on other sites

Oh i got it. Removed the first loop and used x * z for the index

This is wrong. If you want a linear index for a "2D array", it's x * stride + z (or z*stride + x). Your stride is probably count here, but note that you also allocate too small an array. It should be rather Cube[] cubes = new Cube[count*count].

Your original problem was that you set count*count cubes to the same index i. I advise to not use an array to collect cubes, but List<Cube> and Add them as you generate them. Then finally use ToArray(). No hassling with manual indexing needed.

@SeraphLance: The code is a bit confusing (View*Projection used for the WVP uniform) but I think it's ok: You use View*Projection since the world transformation comes from the instances.

As an aside: If you're not going to rotate and scale your cubes, a simple offset can be used instead of a full world transformation. Much less memory footprint Edited by unbird

• 18
• 29
• 11
• 21
• 16