I have a textured polygon that rotates. I used GL_QUADS and glRotatef in openGL to draw the cube. I would like to make this into a screensacer by coding a function that makes the box float around as it rotates, and possibly bounce off of the borders of the window. Can someone please solve this?
You can just position the box randomly using rand() to generate a random number and then position the box via that. You'll have to set some upper and lower bounds for the random number, probably best to just have a play around with a few values and see which ones work best.
rand() % 100
This would give you a random number 0 to 100.
If you need more assistance post a bit of code up and Ill have a play around with it.
The easiest solution is to break the motion of the cube up into 2 componentsâ€”horizontal and vertical (x, and y).
You assign the cube an initially random direction vector, by giving it random x and y components (see Sam's comment above).
You then have a seperate thread iterate infinitely, pause for say 30 milliseconds, then repaint the display.
When the display is repainted, you use the current position, and the direction components of the cube to calculate the new position for it.
You merely need to paint the cube in it's new position.
Next, you check to see if the x or y components exceed the window limits; if it does, then you INVERT them (*-1), so that they appear to bounce off the screen's edges..
// define the x,y position of the cube on the screen (where the origin 0,0 is the center of the screen)
int x = 0 ;
int y = 0 ;
// define the random direction vectors for each axis
int dx = rand() % 30 ;
int dy = rand() % 30 ;
.
.
// in your seperate thread
for( ;; )
{
Sleep( 30 ) ; // 30 ms
// invoke a repaint() here
}
.
.
// when you repaint the display:
// -- render the cube here, with the coordinates x,y -- //
// now update the x,y position based on the dx,dy values:
x += dx ;
y += dy ;
// now check to see if there's any collision with the edges of the screen, with width and height of w and h:
// (where 'c' is the width (or height) of the cube)
if ( x-c-w/2 <= 0 || x+c >= w/2 )
{
dx = -dx ;
}
if ( y-c-h/2 <= 0 || y+c >= w/2 )
{
dy = -dy ;
}
0
spo7Author Commented:
This is helpful - although I'm having trouble getting it working properly. Since I'm very new to openGL, I was hoping for an answer more specific to openGL functions etc.
You can just position the box randomly using rand() to generate a random number and then position the box via that. You'll have to set some upper and lower bounds for the random number, probably best to just have a play around with a few values and see which ones work best.
rand() % 100
This would give you a random number 0 to 100.
If you need more assistance post a bit of code up and Ill have a play around with it.
Hope this helps
Sam