Stella
Stella

Reputation: 548

Method to 'rock' a value back and forth

I'm working on a small game, I have objects which I want to elevate up and down. Object moves to max value of Y -> Object moves to min value of Y -> Repeat. I have a rough idea of how to do this, I would put this in a timer/my update method.

if(Y >= max)
{
    direction = "down";
}
if(y =< min)
{
    direction = "up";
}

if(direction == "up") Y -= speed;
if(direction == "down") Y += speed;

(Could also use a bool ofcourse but, for the sake of implicity)

But it feels like I'm just re-inventing the wheel, is there by any chance a built in method/math function to do this automatically? eg. SomeFunction(min, max, increment). I'm using the XNA framework, so functions built into that are ofcourse welcome as well.

Upvotes: 2

Views: 173

Answers (1)

Matthew Watson
Matthew Watson

Reputation: 109792

Forget having a separate direction flag.

Just use a negative speed for "up" to simplify the code:

if ((Y >= max) || (Y <= min)) // Hit an edge?
   speed = -speed;            // Reverse direction.

Y += speed;

Upvotes: 7

Related Questions