How does this work? (C# & XNA related)

Started by
1 comment, last by Falcon988 13 years, 6 months ago
If someone would take the time to peruse this Reimer XNA tutorial (http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series2D/SpriteBatch.Draw.php). My question is pretty simple but I'm a bit stumped!

There's an array in which the colors of the players are defined as follows:



PlayerData[] players;
int numberOfPlayers = 4;



private void SetUpPlayers()
{
Color[] playerColors = new Color[10];
playerColors[0] = Color.Red;
playerColors[1] = Color.Green;
playerColors[2] = Color.Blue;
playerColors[3] = Color.Purple;
playerColors[4] = Color.Orange;
playerColors[5] = Color.Indigo;
playerColors[6] = Color.Yellow;
playerColors[7] = Color.SaddleBrown;
playerColors[8] = Color.Tomato;
playerColors[9] = Color.Turquoise;

players = new PlayerData[numberOfPlayers];
for (int i = 0; i < numberOfPlayers; i++)
{
players.IsAlive = true;
players.Color = playerColors;
players.Angle = MathHelper.ToRadians(90);
players.Power = 100;
}


And then in the draw methods we render them using the following code block:






"private void DrawPlayers()
{
foreach (PlayerData player in players)
{
if (player.IsAlive)
{
spriteBatch.Draw(carriageTexture, player.Position, null, player.Color, 0, new Vector2(0, carriageTexture.Height), playerScaling, SpriteEffects.None, 0);
}
}


}
}"




The part that's got me stumped is the 'player.Color' argument. I don't know where 'player' is defined??? I guess I could understand it more if it was 'players.Color' and not player singular. Does XNA recognize the singular version of a plural?? I just don't get it and I feel like I'm overthinking it but... I just don't see how when I say 'player.Color' it knows to obey the sequence defined in the Color[] array.

Everything in my code renders fine, but I don't understand how it pieces together.
Advertisement
It says it right here int he code you pasted:

foreach (PlayerData player in players)

Foreach is a mechanism similar to creating a for loop. Each time foreach loops back to the beginning of the loop, the variable specified (in this case, player) becomes the next entry inside the players array.

It's essentially the same as doing this:
for (int i = 0; i < players.Length; i++){   PlayerData player = players;   if (player.IsAlive)   {      spriteBatch.Draw(carriageTexture, player.Position, null, player.Color, 0, new Vector2(0, carriageTexture.Height), playerScaling, SpriteEffects.None, 0);   }}
I see! That totally makes sense, thank you!

This topic is closed to new replies.

Advertisement