OpenGL鼠标移动方块

思路:用变量设定方块的坐标,然后根据鼠标的位移更改方块的变量坐标。

注意:方块的绘图坐标系和世界坐标系是重合的,鼠标所在的坐标是以窗口的左上角为原点(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;
}

 

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值