468,504 Members | 1,956 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,504 developers. It's quick & easy.

random movement

1
I have made an object move across the screen from right to left in a straight line using a for loop. However now I need to use the random function to make it appear to move up and down randomly as it moves to the right of the screen, and where in the loop do I do this? any help starting this, thanks
Oct 20 '06 #1
1 3929
arne
315 Expert 100+
I have made an object move across the screen from right to left in a straight line using a for loop. However now I need to use the random function to make it appear to move up and down randomly as it moves to the right of the screen, and where in the loop do I do this? any help starting this, thanks
You could generate a random number and then decide from this number whether you go up,down,left or right. Like

Expand|Select|Wrap|Line Numbers
  1.         switch( rand() % 4 ) {
  2.  
  3.             case 0: 
  4.                 // go up
  5.                 cout << "up" << endl;
  6.                 break;
  7.             case 1:
  8.                 // go down
  9.                 cout << "down" << endl;
  10.                 break;
  11.             case 2:
  12.                 // go left
  13.                 cout << "left" << endl;
  14.                 break;
  15.             default:
  16.                 // go right
  17.                 cout << "right" << endl;
  18.                 break;
  19.                }    
  20.  
If you only need to decide about two directions, calculate rand()%2 and decide from that.
One loop iteration is one step of your object, so the above switch statement should be inside the loop.
Oct 20 '06 #2

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

14 posts views Thread by Paul C-T | last post: by
4 posts views Thread by Pjotr Wedersteers | last post: by
2 posts views Thread by Robin Shuff | last post: by
24 posts views Thread by Tuvas | last post: by
13 posts views Thread by porterboy76 | last post: by
1 post views Thread by sircool | last post: by
5 posts views Thread by hurricane_number_one | last post: by
3 posts views Thread by gieforce | last post: by
reply views Thread by fmendoza | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.