Sign in to follow this  
Falcon988

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

Recommended Posts

Falcon988    100
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[i].IsAlive = true;
players[i].Color = playerColors[i];
players[i].Angle = MathHelper.ToRadians(90);
players[i].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.

Share this post


Link to post
Share on other sites
Flimflam    665
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[i];
if (player.IsAlive)
{
spriteBatch.Draw(carriageTexture, player.Position, null, player.Color, 0, new Vector2(0, carriageTexture.Height), playerScaling, SpriteEffects.None, 0);
}
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this