0

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?

Johny P.
  • 648
  • 1
  • 9
  • 31

1 Answers1

0

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;
libertylocked
  • 892
  • 5
  • 15
  • I do want smooth movements so I assume `centerY` is a `Rectangle.Height / 2;`? `maxOffset` should be `16`. – Johny P. Mar 18 '16 at 15:24
  • I would also use a multiple of `gameTime.ElapsedGameTime` in both cases. – vgru Mar 18 '16 at 15:25
  • @JohnyP. `centerY` should be the original Y position of your rectangle, without any offset applied. `maxOffset` is how far you want the rectangle to move from the center position – libertylocked Mar 18 '16 at 15:27
  • Oh, now I see. I got it all working. I will just have to play around with `transitionSpeed` to find the best effect. – Johny P. Mar 18 '16 at 15:29