你必須保持形狀對象的數組,並測試每一個鼠標的碰撞,以及跟蹤其中形狀您拖動:
#include <GL/glut.h>
#include <vector>
using namespace std;
struct Shape
{
float mX, mY;
float mSize;
bool mIsRectangle;
bool PointInside(const float x, const float y) const
{
return
mX - mSize <= x && x <= mX + mSize
&&
mY - mSize <= y && y <= mY + mSize;
}
};
vector<Shape> objects;
Shape* dragging = NULL;
void mouse(int button, int state, int x, int y)
{
if(GLUT_DOWN == state)
{
dragging = NULL;
for(Shape& obj : objects)
{
if(obj.PointInside(x, y))
{
dragging = &obj;
glutPostRedisplay();
break;
}
}
}
else
{
dragging = NULL;
}
}
void motion(int x, int y)
{
if(dragging)
{
dragging->mX = x;
dragging->mY = 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 drawTriangle(float x, float y, float size)
{
glPushMatrix();
glTranslatef(x, y, 0.0f);
glScalef(size, size, 1.0f);
glBegin(GL_TRIANGLES);
glColor3ub(255, 255, 255);
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();
for(const Shape& obj : objects)
{
if(obj.mIsRectangle)
drawRect(obj.mX, obj.mY, obj.mSize);
else
drawTriangle(obj.mX, obj.mY, obj.mSize);
}
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);
Shape temp;
temp.mSize = 50;
temp.mX = temp.mY = 100;
temp.mIsRectangle = true;
objects.push_back(temp);
temp.mX = temp.mY = 200;
temp.mIsRectangle = false;
objects.push_back(temp);
glutMainLoop();
return 0;
}
您發佈的代碼只是繪製在任何'x'和'y'座標下給出一個三角形。它與鼠標輸入或跟蹤三角形出現的位置無關。 – Wyzard 2014-10-30 02:45:38