OpenGL實(shí)現(xiàn)鼠標(biāo)移動(dòng)方塊
本文實(shí)例為大家分享了OpenGL實(shí)現(xiàn)鼠標(biāo)移動(dòng)方塊的具體代碼,供大家參考,具體內(nèi)容如下
思路:用變量設(shè)定方塊的坐標(biāo),然后根據(jù)鼠標(biāo)的位移更改方塊的變量坐標(biāo)。
注意:方塊的繪圖坐標(biāo)系和世界坐標(biāo)系是重合的,鼠標(biāo)所在的坐標(biāo)是以窗口的左上角為原點(diǎn)(0,0)的坐標(biāo)系,窗口的左下角的世界坐標(biāo)系為gluOrho2D(left, right, bottom, top)中的(left, bottom)。所以鼠標(biāo)的坐標(biāo)(xMouse, yMouse)轉(zhuǎn)化為世界坐標(biāo)(x, y)為: x = xMouse; y = top - yMouse.且鼠標(biāo)位移的Y增量在世界坐標(biāo)系中式減量。
#include <GL/glut.h>
#include "Graphics.h"
int x1 = 0, y1 = 0, x2 = 100, y2 = 100; //方塊的左下角坐標(biāo)和右上角坐標(biāo)
int x = 0, y = 0; //鼠標(biāo)位置
int dx = 0, dy = 0; //鼠標(biāo)位移
int b = 0; //判斷鼠標(biāo)是否在方塊內(nèi)
void init()
{
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0.0, 800.0, 0.0, 800.0); //窗口左下角的世界坐標(biāo)系為 (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是以窗口的左上角為原點(diǎn)(0,0)的窗口坐標(biāo)系中的點(diǎn)
y = yMouse;
if (inRect(x, y)) b = 1;
}
if (button == GLUT_LEFT_BUTTON && state == GLUT_UP) b = 0; //當(dāng)移動(dòng)較快時(shí)鼠標(biāo)會(huì)在刷新間隔移出方塊,所以用DOWN和UP來判斷鼠標(biāo)在方塊內(nèi)
}
void moveMouse(int xMouse, int yMouse)
{
if (b) {
dx = xMouse - x;
dy = yMouse - y;
x1 = x1 + dx;
x2 = x2 + dx;
y1 = y1 - dy; //鼠標(biāo)的窗口坐標(biāo)系和世界坐標(biāo)系的Y軸相反,所以鼠標(biāo)向Y軸的正方向移動(dòng)的時(shí)候,在世界坐標(biāo)系是向Y軸的負(fù)方向移動(dòng)
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); //移動(dòng)是動(dòng)畫,為了流暢,必須開這個(gè)
glutMouseFunc(myMouse);
glutMotionFunc(moveMouse);
glutMainLoop();
return 0;
}
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
VScode搭建C/C++開發(fā)環(huán)境的詳細(xì)過程
最近迷上了vscode,小巧美觀,最主要的是全平臺(tái),但是vscode并不是ide,必須得自己配置環(huán)境,下面這篇文章主要給大家介紹了關(guān)于VScode搭建C/C++開發(fā)環(huán)境的詳細(xì)過程,需要的朋友可以參考下2023-06-06
C++?opencv圖像處理實(shí)現(xiàn)圖像腐蝕和膨脹示例
這篇文章主要為大家介紹了C++?opencv圖像處理實(shí)現(xiàn)圖像腐蝕和圖像膨脹示例代碼,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
c++之std::get_time和std::put_time
std::get_time和std::put_time是C++中用于日期和時(shí)間的格式化和解析的函數(shù),它們都包含在<iomanip>頭文件中,std::get_time用于從輸入流中解析日期時(shí)間字符串,而std::put_time則用于將std::tm結(jié)構(gòu)格式化為字符串2024-10-10
C語言中函數(shù)與指針的應(yīng)用總結(jié)
本篇文章是對(duì)C語言中函數(shù)與指針的應(yīng)用進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05

