I was recently trying to make a boucing ball off the environment walls. I apparently had everything correct, except for one thing, that I corrected stupidly, which made my code work, but I don't understand why.
So I had set the value of a 2d vector's X and Y inside protected override void Update(GameTime gameTime)
; this vector was what I would add to the object's X and Y so it could move according to whatever logic.
But it didn't work, the fix to this problem was to apparently declare the vector's values inside protected override void LoadContent()
.
So can anyone explain to me, what is the difference between declaring your variables/constants inside these two methods? And why?
EDIT : Wrong Sourcecode :
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// Loaded content
}
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Escape))
this.Exit();
//Code logic
movement.X = 5;
movement.Y = 5;
birdbox3.X += (int)movement.X; //this variable was declared outside of any local field as a rectangle
if (birdbox3.X <= 0)
{
movement.X = -movement.X;
}
else if (birdbox3.Y <=0)
{ movement.Y = - movement.X;
}
base.Update(gameTime);
}
So when I would run this code, the birdbox3 would just stop when the if statement is fulfilled. The correct version would be to cut the
movement.X = 5;
movement.Y = 5;
and paste it into LoadContent()
instead. The problem is I do not know why.