在Opengl中通过鼠标移动形状 [英] Moving Shape via Mouse in Opengl
本文介绍了在Opengl中通过鼠标移动形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
void Rectangle(void) {
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_QUADS);
glColor3f(1.0,0.0,0.0);
glVertex2f(m_x-0.25,m_y-0.25);
glColor3f(1.0,0.0,0.0);
glVertex2f(m_x-0.25,m_y-0.75);
glColor3f(1.0,0.0,0.0);
glVertex2f(m_x-0.75,m_y-0.75);
glColor3f(1.0,0.0,0.0);
glVertex2f(m_x-0.75,m_y-0.25);
glEnd();
glutSwapBuffers();
我想将矩形移动到按下鼠标的位置. m_x和m_y是全局变量.此函数已在主glutDisplayFunc(Rectangle)中调用,鼠标函数如下:
I want to move the rectangle to where pressed mouse. m_x and m_y are global variable.This function has called in main glutDisplayFunc(Rectangle), mouse function like this:
void mouse(int button,int state,int x,int y)
switch(button)
{
case GLUT_LEFT_BUTTON:
if(state==GLUT_DOWN)
{
m_x=x;
m_y=y;
Rectangle();
glutSwapBuffers();
}
break;
default:
break;
}
应用程序运行时,在我按下鼠标后,它会绘制一个矩形.矩形丢失了吗?
When the application runs ,it draws a rectangle after i pressed mouse the rectangle lost.What is my wrong?
推荐答案
不要在鼠标处理程序中这样渲染内容,只需更新对象位置并使用glutPostRedisplay()
将重绘排队:
Don't render stuff in your mouse handler like that, just update the object position and queue a redraw with glutPostRedisplay()
:
#include <GL/glut.h>
float objX = 100;
float objY = 100;
float objSize = 50;
bool dragging = false;
void mouse( int button, int state, int x, int y )
{
if( GLUT_DOWN == state )
{
bool colliding =
objX - objSize <= x && x <= objX + objSize
&&
objY - objSize <= y && y <= objY + objSize;
if( colliding )
{
dragging = true;
objX = x;
objY = y;
glutPostRedisplay();
}
}
else
{
dragging = false;
}
}
void motion( int x, int y )
{
if( dragging )
{
objX = x;
objY = y;
glutPostRedisplay();
}
}
void drawRect( float x, float y, float size )
{
glPushMatrix();
glTranslatef( x, y, 0.0f );
glScalef( size, size, 1.0f );
glBegin( GL_QUADS );
glColor3ub( 255, 255, 255 );
glVertex2f( -1, -1 );
glVertex2f( 1, -1 );
glVertex2f( 1, 1 );
glVertex2f( -1, 1 );
glEnd();
glPopMatrix();
}
void display()
{
glClearColor( 0, 0, 0, 1 );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
const double w = glutGet( GLUT_WINDOW_WIDTH );
const double h = glutGet( GLUT_WINDOW_HEIGHT );
glOrtho( 0, w, h, 0, -1, 1 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
drawRect( objX, objY, objSize );
glutSwapBuffers();
}
int main(int argc, char **argv)
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE );
glutInitWindowSize( 600, 600 );
glutCreateWindow( "GLUT" );
glutDisplayFunc( display );
glutMouseFunc( mouse );
glutMotionFunc( motion );
glutMainLoop();
return 0;
}
这篇关于在Opengl中通过鼠标移动形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文