Model ourModel("D:/openGLResource/bin/nanosuit/nanosuit.obj");
map<string, pair<glm::vec3, Model>> _models;
_models.insert(pair<string, pair<glm::vec3, Model>>("Zhang3", pair<glm::vec3, Model>(cubePositions[0], ourModel)));
_models["Li4"] = pair<glm::vec3, Model>(cubePositions[2], ourModel);
map<string, pair<glm::vec3, Model>>::iterator _modelsIter;
- 注意Model类需要做一个声明函数不然第二个函数无法生成
Model()
{
}
for(_modelsIter=_models.begin();_modelsIter!=_models.end();_modelsIter++)
{
model=glm::translate(trans,_modelsIter->second.first);
glUniformMatrix4fv(glGetUniformLocation(cubeShader.ID,"model"),1,GL_FALSE,glm::value_ptr(model));
_modelsIter->second.second.Draw(cubeShader);
}
- 定义选择的全局变量以及点击选择,做了一个半径为7.5的包围球,注意模型中心并不是模型中间,所以要往上提一点
string modelSelected = "NULL";
glfwPollEvents();
if (pickingModelWorldPosition == true)
{
glReadPixels((int)winX, 600 - (int)winY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);
float x = (2.0f * winX) / 800.0f - 1.0f;
float y = 1.0f - (2.0f * winY) / 600.0f;
float z = winZ * 2.0 - 1.0f;
pickingModelWorldPosition = false;
if (winZ < 1.0f)
{
float w = near * far / (near * winZ - far * winZ + far);
glm::vec4 wolrdPostion = glm::inverse(view) * glm::inverse(projection) * w * glm::vec4(x, y, z, 1);
for (_modelsIter = _models.begin(); _modelsIter != _models.end(); _modelsIter++)
{
float _distance = glm::distance(_modelsIter->second.first + glm::vec3(0, 7.5, 0), glm::vec3(wolrdPostion));
if (_distance < 7.5)
cout << _modelsIter->first << "模型被选中..." << endl;
modelSelected = _modelsIter->first;
}
}
else {
modelSelected = "NULL";
cout << "没有点中模型...." << endl;
}
}
结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/570554c7f5384db7894e40a933b9adec.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dxZHF3YXNz,size_16,color_FFFFFF,t_70)