Reputation: 5
I am using Microsoft visual C++ express 2010 i have a variables: int x, that represents the position of a video game character. (their is a Y of course) The program loops and each time it changes X by a couple of places. but it must be within 0-800. and when it reaches the 0 (which is supposed to be the edge of the screen) its rewinds.
I have figured out how to change their value every time the program runs, but how do i make sure that it keeps its value in the 0-800 range, and rewind it when it reaches position 0? and it has its very own function outside of Main entirely. thank you.
Upvotes: 0
Views: 180
Reputation: 490408
First, it's not quite clear exactly what you want. When you say "rewind", do you mean start over at the opposite side again, or turn around and move back in the direction it came from.
Assuming the first, the easy (but somewhat clumsy) way is to just do a comparison and when/if the value goes out of range, adjust as necessary:
x -= increment;
if (x < 0)
x = 800;
or:
x += increment;
if (x > 800)
x = 0;
You can also use the remainder operator, but it can be a little bit clumsy to get it entirely correct. When you're going in the positive direction, it's fairly direct and simple, but in the negative direction, it's not -- in this case a negative number is entirely possible, so simple tests like above are needed. If the value only ever goes in the positive direction, so you only care about it becoming greater than the limit, it works fine though.
Upvotes: 0
Reputation: 63481
Make a direction variable...
int dir = -2;
for(;;) {
x += dir;
if( x < 0 || x >= 800 ) {
dir *= -1;
x += dir;
}
}
Upvotes: 1
Reputation: 198436
x = (x + 800) % 800;
This will keep x
within (0..799)
. If you really need (0..800)
, replace 800
with 801
.
Upvotes: 2