PDA

View Full Version : dragging a 2d object



rohit_static
04-20-2010, 04:06 AM
Hi,
This is my first post in this community .I am trying to develop a mini opengl project for my college.I now encounter a problem of dragging a square when the left button of my mouse is pressed.Can anyone please help me with this .The following snippet of code has been written by me but doesn't work as expected
void mousemotion(int x,int y)
{
if(flag==1)
{

glColor3f(1.0,0.0,0.0);
glBegin(GL_POLYGON);
glVertex2f(x,y);
glVertex2f(x-0.5,y);
glVertex2f(x-0.5,y-0.5);
glVertex2f(x,y-0.5);
glEnd();
glFlush();
glutPostRedisplay();
}
}
void mymousehandler(int btn,int state,int x,int y)
{
if(btn==GLUT_LEFT_BUTTON && state==GLUT_DOWN)
flag=1;
else
flag=0;
}
void display()
{

glClear(GL_COLOR_BUFFER_BIT);
glClearColor(0.0,0.0,0.0,0.0);
glColor3f(1.0,0.0,0.0);
glBegin(GL_POLYGON);
glVertex2f(0.0,0.0);
glVertex2f(0.5,0.0);
glVertex2f(0.5,0.5);
glVertex2f(0.0,0.5);
glEnd();
glFlush();
}
Expecting a favorable reply
Regards

strattonbrazil
04-20-2010, 08:07 AM
First of all, it's customary to say what's not working. Are you getting strange results or no results?

Looking at you're code I see you have drawing the same thing in your display function over and over. That's a problem in the sense that you'll always get the same square. I also see you're calling OpenGL code in your mouse handling code. That's also a problem. Most of your rendering code should go into the display function. That's what it's for.

You probably want to keep track of the (x,y) of the sphere in the motion handling function and in your display function use that (x,y) to determine where to draw your square.