PDA

View Full Version : how do i randomly position the object on left click??



newbiee
04-27-2014, 05:33 AM
could any1 please help me on randomly positioning a rectangle on window on mouse event (left click)??
this is my code,...

#include <stdlib.h>
#include <stdio.h>
#include <GL/glut.h>
#include <math.h>

int score=0;

void init()
{
glClearColor (0.0, 0.0, 0.0, 0.0);
}

float random1 (int m)
{
return rand()%m;
}

void drawObjects(GLenum mode)
{
float x;
if(mode == GL_SELECT)
glLoadName(1);
glColor3f(1.0, 1.0, 1.0);
x=random1(1000.0);
glRectf(-x, -x, x,x);


}

void display()
{
glClear(GL_COLOR_BUFFER_BIT);
drawObjects(GL_RENDER);
glFlush();
}

void processHits (GLint hits, GLuint buffer[])
{
unsigned int i, j;
GLuint names, *ptr;
if(hits==1)
{
drawObjects(GL_SELECT);
score++;
}
if(hits>=1)
{
printf("Your Score is %d Clicks Per Second!\n",score);
}

}


#define SIZE 512

void mouse(int button, int state, int x, int y)
{
GLuint selectBuf[SIZE];
GLint hits;
GLint viewport[4];

if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
glGetIntegerv (GL_VIEWPORT, viewport);

glSelectBuffer (SIZE, selectBuf);
glRenderMode(GL_SELECT);

glInitNames();
glPushName(0);

glMatrixMode (GL_PROJECTION);
glPushMatrix ();
glLoadIdentity ();
/* create 5x5 pixel picking region near cursor location */
gluPickMatrix ((GLdouble) x, (GLdouble) (viewport[3] - y),
5.0, 5.0, viewport);
gluOrtho2D (-2.0, 2.0, -2.0, 2.0);
drawObjects(GL_SELECT);


glMatrixMode (GL_PROJECTION);
glPopMatrix ();
glFlush ();

hits = glRenderMode (GL_RENDER);
processHits (hits, selectBuf);

glutPostRedisplay();
}
}


void reshape(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D (-2.0, 2.0, -2.0, 2.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

void keyboard(unsigned char key, int x, int y)
{
switch (key) {
case 27: // ?!?
exit(0);
break;
}
}


void Timer1()
{
exit(0);
}

void Timer(int iUnused)
{

glutTimerFunc(60000, Timer1, 0);

}

/* Main Loop */
void main(int argc, char** argv)
{

glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (500, 500);
glutInitWindowPosition (80, 100);
glutCreateWindow ("click on the object, fast!");
init ();
glutReshapeFunc (reshape);
glutDisplayFunc(display);
glutMouseFunc (mouse);
glutKeyboardFunc (keyboard);
Timer(0);
glutMainLoop();

}