So I'm working on my menu's background and I Draw()
a texture there with a rectangle. How would I have the rectangle wait, move up and then down, wait and repeat? I tried the following:
// Update()
if (Rectangle.Y = -16) // My texture is positioned to -16 initially
Rectangle.Y++;
else if (Rectangle.Y = 0)
Rectangle.Y--;
So my game resolution is 1366x768
. To have the background texture move up and down I had to make it have a height > 768
. I made it 1366x800
. Every time the above code is called it should wait 1-2seconds (not yet implemented), move 16 pixels down, wait again and go back 16 pixels up... But that code doesn't work... Could you guide me as to how this is done?
You can do it with Math.Sin
, which will give you a smooth transition from -1 to 1. You will have to keep a copy of your rectangle's center Y position.
double time = gameTime.TotalGameTime.TotalSeconds;
Rectangle.Y = centerY + (int)(Math.Sin(time * transitionSpeed) * maxOffset);
You can play with double transitionSpeed
to get the best visual effect. int maxOffset
is the max amount of offset from centerY.
If you don't want smooth movements, then just do
int speed = 1; // speed of movement
Then in update
if (Rectangle.Y <= -16 || Rectangle.Y >= 0)
speed *= -1; // reverse move direction
Rectangle.Y += speed;