Make an object follow the camera in OpenGL

2019-03-22 07:57发布

I'm making a racecar game in OpenGL (just a small project) and I'm having problems trying to make my car follow the camera view.

It wasn't hard to make it follow the camera as the camera moves forward and/or backward, but as I rotate the camera (look right or left) the car remais still. I mean, it still moves forward and backward but it's not in front of the camera (it's on the side).

Here is my code (the part where I try to implement it):

void updateCam() {
    gluLookAt(posX,posY + 0.025 * std::abs(sin(headPosAux*PI/180)),posZ,
        posX + sin(roty*PI/180),posY + 0.025 * std::abs(sin(headPosAux*PI/180)) + cos(rotx*PI/180),posZ -cos(roty*PI/180),
        0.0,1.0,0.0);

    listenerPos[0] = posX;
    listenerPos[1] = posY;
    listenerPos[2] = posZ;

    source0Pos[0] = posX;
    source0Pos[1] = posY;
    source0Pos[2] = posZ;

    GLfloat distD;

    distD = posZ - 3.3;


    //makes the car "follow" the camera
    modelPOR.Translate(posX,posY,distD);

}

标签: opengl 3d camera
1条回答
淡お忘
2楼-- · 2019-03-22 08:39

I think the problem is that you change the center location in gluLookAt and not in the modelPOR.Translate

the 3 middle parameters of gluLookAt set the center of the view, so the car should be at the exact same position but you modify the center without modifying the car's position.

gluLookAt(posX,posY + 0.025 * std::abs(sin(headPosAux*PI/180)),posZ,

    // center x
    posX + sin(roty*PI/180),
    // center y
    posY + 0.025 * std::abs(sin(headPosAux*PI/180)) + cos(rotx*PI/180),
    // center z
    posZ -cos(roty*PI/180),

    0.0,1.0,0.0);

you should probably translate the car by those same values. then it will be centered.

another problem that seems to be in that code is that you rotate the camera and not the car, so the car probably will not stay pointing in the same direction as the camera. (is that desired or do you do it elswhere?)

but are you really sure you want to make the car follow the camera? it would probably be better the other way around.

查看更多
登录 后发表回答