我有一個代碼,找出在國際象棋棋盤單擊單元格鼠標,那麼二維三角形去細胞位置,現在我想2D三角變爲3D立方體,但我不知道怎麼做。變化2D物體的3D對象的OpenGl
這是我的代碼
#include <string>
#include <stdlib.h>
#ifdef __APPLE__
#include <OpenGL/OpenGL.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include <iostream>
using namespace std;
void init()
{
glClearColor (1.0, 0.0, 1.0, 0.0);
glShadeModel (GL_FLAT);
}
const int scl = 80 ;
const int STEP_SIZE = 80;
const int WIN_WIDTH = 800;
const int WIN_HEIGHT = 800;
int LeftRight = 0 ;
int UpDown = 0;
void moveRight()
{
LeftRight+=STEP_SIZE;
}
void moveLeft()
{
LeftRight-=STEP_SIZE;
}
void moveUp()
{
UpDown+=STEP_SIZE;
}
void moveDown()
{
UpDown-=STEP_SIZE;
}
void DrawBoard()
{
int x , y , color = 0;
glClear (GL_COLOR_BUFFER_BIT);
for(x=1; x<=8; x++)
{
if(color==0)
glColor3f (1.0, 0.0, 0.0), color++;
else
glColor3f (1.0, 1.0, 1.0),color=0;
for(y=1; y<=8; y++)
{
if(color==0)
glColor3f (0.0, 0.0, 0.0),color++;
else
glColor3f (1.0, 1.0, 1.0),color=0;
glBegin(GL_QUADS);
glVertex2f(scl+scl*x, scl+scl*y);
glVertex2f(scl*x, scl+scl*y);
glVertex2f(scl*x, scl*y);
glVertex2f(scl+scl*x, scl*y);
glEnd();
}
}
// This is the Triangle that will change to cube
glBegin(GL_QUADS);
glColor3f (1.0, 0.5, 0.0);
glVertex2f(90+LeftRight,100+UpDown);
glVertex2f(90+LeftRight,100+UpDown);
glVertex2f(120+LeftRight,140+UpDown);
glVertex2f(150+LeftRight,100+UpDown);
glEnd();
//--------------------------------------
glFlush();
}
int mouse_x = -1 ;
int mouse_y = -1 ;
int object_x = -1 ;
int object_y = -1 ;
void moveObjectToFrom()
{
if (mouse_x > 8 || mouse_x < 1 || mouse_y > 8 || mouse_y < 1)
return ;
if(object_x > mouse_x)
{
object_x-- ;
moveUp();
}
if(object_x < mouse_x)
{
object_x++;
moveDown();
}
if(object_y > mouse_y)
{
object_y-- ;
moveLeft();
}
if(object_y < mouse_y)
{
object_y++ ;
moveRight();
}
}
void mouseClicks(int button , int key, int x, int y)
{
// this variables related to chessboard
mouse_x = y/scl ;
mouse_y = 9 - (WIN_HEIGHT - x)/scl ;
object_x = 9 - (100 + UpDown)/ scl ;
object_y = 9 - (WIN_HEIGHT - (LeftRight+90))/scl ;
if (button !=0 || mouse_x > 8 || mouse_x < 1 || mouse_y > 8 || mouse_y < 1)
return ;
glutPostRedisplay();
}
void reshape (int w, int h)
{
glViewport (0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity();
gluOrtho2D (0.0, (GLdouble) w, 0.0, (GLdouble) h);
}
void update(int value)
{
moveObjectToFrom();
glutTimerFunc(50, update, 0);
glutPostRedisplay();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
// glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glEnable(GL_DEPTH_TEST);
glutInitWindowSize (WIN_WIDTH, WIN_HEIGHT);
glutInitWindowPosition (100,100);
glutCreateWindow (argv[0]);
glutTimerFunc(25, update, 0);
glutMouseFunc(mouseClicks);
init();
glutDisplayFunc(DrawBoard);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}
所以要映射在3D場景中點擊鼠標?如果是這樣,你可以在https://www.opengl.org/discussion_boards/showthread.php/175699-How-to-click-on-3D-objects-with-mouse看一看,看看這些答案的人幫助您。 – Aumnayan