OpenGL按键事件移动初解

首先。我们将图形的空间坐标定义为全局。

GLfloat block = 0.1f;
GLfloat vVerts[] = { -block, -block, 0.0f,
	                  block, -block, 0.0f,
					  block,  block, 0.0f,
					 -block,  block, 0.0f};

在main中加入监听

//特殊按键事件监听
	glutSpecialFunc(SpecialKeys);

监听回调函数

//按钮监听时间回调函数
void SpecialKeys(int key,int x,int y)
{
	GLfloat stepSize = 0.025f;
	GLfloat blockX = vVerts[0];//左上角x
	GLfloat blockY = vVerts[7];//左上角y

	if(key == GLUT_KEY_UP)
	{
		blockY += stepSize;
	}
	if(key == GLUT_KEY_DOWN)
	{
		blockY -= stepSize;
	}
	if(key == GLUT_KEY_LEFT)
	{
		blockX -= stepSize;
	}
	if(key == GLUT_KEY_RIGHT)
	{
		blockX += stepSize;
	}

	if(blockX < -1.0f)
	{
		blockX = -1.0f;
	}
	if(blockX > (1.0f - block * 2))
	{
		blockX = 1.0f - block * 2;
	}
	if(blockY > 1.0f)
	{
		blockY = 1.0f;
	}
	if(blockY < - 1.0f +block * 2)
	{
		blockY = -1.0f+block * 2;
	}

	// 重新计算顶点位置
	vVerts[0] = blockX;
	vVerts[1] = blockY - block*2;

	vVerts[3] = blockX + block*2;
	vVerts[4] = blockY - block*2;

	vVerts[6] = blockX + block*2;
	vVerts[7] = blockY;

	vVerts[9] = blockX;
	vVerts[10] = blockY;

	triangleBatch.CopyVertexData3f(vVerts);
     //更新窗口显示内容
	glutPostRedisplay();
}

 

本文链接:

https://www.bobsong.net/151.html
1 + 8 =
快来做第一个评论的人吧~