思路:用变量设定方块的坐标,然后根据鼠标的位移更改方块的变量坐标。
注意:方块的绘图坐标系和世界坐标系是重合的,鼠标所在的坐标是以窗口的左上角为原点(0,0)的坐标系,窗口的左下角的世界坐标系为gluOrho2D(left, right, bottom, top)中的(left, bottom)。所以鼠标的坐标(xMouse, yMouse)转化为世界坐标(x, y)为: x = xMouse; y = top - yMouse.且鼠标位移的Y增量在世界坐标系中式减量。
#include <GL/glut.h>
#include "Graphics.h"
int x1 = 0, y1 = 0, x2 = 100, y2 = 100; //方块的左下角坐标和右上角坐标
int x = 0, y = 0; //鼠标位置
int dx = 0, dy = 0; //鼠标位移
int b = 0; //判断鼠标是否在方块内
void init()
{
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0.0, 800.0, 0.0, 800.0); //窗口左下角的世界坐标系为 (0,0)
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
}
void test()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0f, 0.0f, 0.0f);
glRecti(x1, y1, x2, y2);
glutSwapBuffers();
}
int inRect(int xMouse, int yMouse)
{
yMouse = 800 - yMouse;
if (xMouse < x2 && xMouse > x1 && yMouse < y2 && yMouse > y1)
return 1;
else
return 0;
}
void myMouse(int button, int state, int xMouse, int yMouse)
{
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
x = xMouse; //xMouse, yMouse是以窗口的左上角为原点(0,0)的窗口坐标系中的点
y = yMouse;
if (inRect(x, y)) b = 1;
}
if (button == GLUT_LEFT_BUTTON && state == GLUT_UP) b = 0; //当移动较快时鼠标会在刷新间隔移出方块,所以用DOWN和UP来判断鼠标在方块内
}
void moveMouse(int xMouse, int yMouse)
{
if (b) {
dx = xMouse - x;
dy = yMouse - y;
x1 = x1 + dx;
x2 = x2 + dx;
y1 = y1 - dy; //鼠标的窗口坐标系和世界坐标系的Y轴相反,所以鼠标向Y轴的正方向移动的时候,在世界坐标系是向Y轴的负方向移动
y2 = y2 - dy;
x = xMouse;
y = yMouse;
}
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowPosition(0, 0);
glutInitWindowSize(800, 800);
glutCreateWindow("Move Square");
init();
glutDisplayFunc(test);
glutIdleFunc(test); //移动是动画,为了流畅,必须开这个
glutMouseFunc(myMouse);
glutMotionFunc(moveMouse);
glutMainLoop();
return 0;
}