Reputation: 593
It appears that my if statement is not working; it is, from what I gather with debug messageboxes that I placed earlier throughout the code to report variables etc., simply not modifying the variable "pos" in the if block, but the if block is definitely being executed. It's hard to explain.
I'm building a little game with cars on a street, and here, I try to spawn new cars and assign them a starting position (or modify their position) based on the lane of the street they're in. This is not production code, it's just me roughing out the basic idea.
for (int i = 0; i < carlane.Count; i++)
{
float lane = carlane.ElementAt(i);
if (lane == 1)
{
if (carpos.Count <= i)
{
pos = new Vector2(screenWidth - 20, (screenHeight / 2) - (8 * screenHeight / 200));
}
else
{
pos = new Vector2(carpos[i].X - 2, carpos[i].Y);
}
rotation = 1.5f * (float)Math.PI;
}
else if (lane == 2)
{
if (carpos.Count <= i)
{
pos = new Vector2(screenWidth - 20, (screenHeight / 2) - (8 * screenHeight / 200));
}
else
{
pos = new Vector2(carpos[i].X - 2, carpos[i].Y);
}
rotation = 1.5f * (float)Math.PI;
}
}
spriteBatch.Draw(car, pos, null, Color.White, rotation, origin, (lane - 1) * (float)Math.PI * 0.5f, SpriteEffects.None, 0f);
if (carpos.Count > i)
{
carpos[i] = (pos);
}
else
{
carpos.Add(pos);
}
And so, when lane is set to 1, nothing happens. Cars spawn, but don't appear. When lane is set to 2, I purposefully used the same code within the if-block as when lane is equal to 1, and the cars spawn and drive along the lane correctly. Something is wrong with the code, when lane = 1, and I don't know what it is.
My computer runs Windows 7 Home Premium 64 bit, and I'm using C# 2010 express edition with XNA game studio 4.0.
Please help?
Upvotes: 0
Views: 118
Reputation: 27247
When lane
is zero, (lane - 1) * (float)Math.PI * 0.5f
is zero. You're Draw
ing with scale
argument zero, which draws nothing.
The documentation:
public void Draw (
Texture2D texture,
Vector2 position,
Nullable<Rectangle> sourceRectangle,
Color color,
float rotation,
Vector2 origin,
float scale,
SpriteEffects effects,
float layerDepth
)
Your code:
spriteBatch.Draw(
car,
pos,
null,
Color.White,
rotation,
origin,
(lane - 1) * (float)Math.PI * 0.5f,
SpriteEffects.None,
0f
);
Looks like the scale to me.
Upvotes: 1
Reputation: 1200
You should only change the pos
variable depending on the lane, not the size of the sprite (you were changing the scale of the sprite, just set that to 1.0f).
spriteBatch.Draw(car, pos, null, Color.White, rotation,
origin, 1.0f, SpriteEffects.None, 0f);
Upvotes: 0
Reputation: 56716
When lane equals 1, the scale (lane - 1) * (float)Math.PI * 0.5f
equals 0, which means that car is scaled to nothing - thus nothing appears on the screen.
Upvotes: 1