gpt4 book ai didi

c++ - OpenGL 鼠标跟踪(自由线)

转载 作者:行者123 更新时间:2023-11-28 06:08:53 25 4
gpt4 key购买 nike

目前我正在尝试制作一个程序来跟踪鼠标坐标,以便在您移动它时绘制一条自由形式的线。到目前为止,程序正在跟踪鼠标并绘制线条,但线条都回到几乎充当原点的坐标。我的教授提到自由线是通过变量 previous x 和 previous y 实现的,每次鼠标移动时,旧线如何存储在 previous x 和 previous y 中,然后它将连接到新的 x 和 y 坐标。

我将如何更改 previousx 和 previousy 变量以获得自由形式的线条?

// To compile in Linux: g++ -o mouse_exam mouse_exam.cpp -lGL -lGLU -lglut -lm

#ifdef __APPLE__
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GlUT/glut.h>
#else
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#endif

#include <iostream>
#include <cmath>
using namespace std;

#define WIDTH 600
#define HEIGHT 600

#define WLEFT 0
#define WRIGHT WIDTH
#define WBOTTOM 0
#define WTOP HEIGHT

#define RGBBLACK 0,0,0
#define RGBGREY .8,.8,.8

static int tracking = 0;
float previousx;
float previousy;

int inwindow(int x, int y)
{
return(x>WLEFT && x<WRIGHT && y>WBOTTOM && y<WTOP);
}

void m_motion(int x, int y)
{
y = WTOP-y;



if(tracking && inwindow(x,y))
{
glBegin(GL_LINES);
glVertex2f(previousx,previousy);
glVertex2f(x,y);
glEnd();

glFlush();
}
}

void handleButton(int button, int state, int x, int y)
{
y=WTOP-y;

if(button != GLUT_LEFT_BUTTON)
{
return;
}

if(state == GLUT_DOWN)
{
if(inwindow(x,y))
{
tracking = 1;
previousx =x;
previousy =y;

cout << previousx << " " << previousy << endl;
}
}

else
{
tracking = 0;
}
}

void drawMouse(void)
{
int i;

glClearColor(RGBGREY,1);
glClear(GL_COLOR_BUFFER_BIT);

glColor3f(RGBBLACK);

glFlush();

}

int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(WIDTH,HEIGHT);
glutCreateWindow("Mouse Exam");
glutDisplayFunc(drawMouse);
glutMouseFunc(handleButton);
glutMotionFunc(m_motion);
gluOrtho2D(0,WIDTH,0,HEIGHT);

glutMainLoop();

return 0;
}

当我编译并运行它时,它会在窗口上输出它

enter image description here

最佳答案

替换这部分:

if(tracking && inwindow(x,y))
{
glBegin(GL_LINES);
glVertex2f(previousx,previousy);
glVertex2f(x,y);
glEnd();

glFlush();
}

有了这个:

if(tracking && inwindow(x,y))
{
glBegin(GL_LINES);
glVertex2f(previousx,previousy);
glVertex2f(x,y);
glEnd();

glFlush();

previousx = x; /* ADDED */
previousy = y; /* ADDED */
}

注意我添加的两行。这个想法是始终保留您已经在 previousx 和 previous 中绘制的线的最后一个点,因此下次绘制另一段时,您将从那里开始。

关于c++ - OpenGL 鼠标跟踪(自由线),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31713844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com