我正在开始一个3D场景,我正在研究相机的运动,或者实体四处走动,但我似乎无法得到它朝着它面向的方向移动。
有没有人对我如何开始向相机方向移动有任何指导?但是我只希望实体沿着x和z轴移动,就像它在地板上一样,y轴现在将被忽略。如果有人能告诉我涉及什么数学,那就非常感激。
Camera::Camera(Vector3 * eye, Vector3 * center, Vector3 * up) {
this->eye = eye;
this->center = center;
this->up = up;
}
Camera::Vector3 * getEye() { return eye; }
Camera::Vector3 * getCenter() { return center; }
Camera::Vector3 * getUp() { return up; }
camera = new Camera(new Vector3(5.0f, 3.0f, 5.0f),
new Vector3(0.0f, 0.0f, 0.0f),
new Vector3(0.0f, 1.0f, 0.0f));
gluLookAt(camera->eye->getX(), camera->eye->getY(), camera->eye->getZ(),
camera->center->getX(), camera->center->getY(), camera->center->getZ(),
camera->up->getX(), camera->up->getY(), camera->up->getZ());//camera
答案 0 :(得分:4)
您还可以直接从视图矩阵中提取视图矢量 - 在渲染场景之前应用的视图矩阵。
OpenGL模型/视图矩阵如下所示:
|lx,ux,vx,px| -- lx,ly,lz is your left-vector
|ly,uy,vy,py| -- ux,uy,uz is your up-vector
|lz,uz,vz,pz| -- vx,vy,vz is your view-vector
|0 ,0 ,0 ,1 | -- px,py,pz is your translation
通过获取:
简单地提取视图向量vx = matrix[2];
vy = matrix[6];
vz = matrix[10];
我通常在旋转相机后执行此操作,以便应用移动。在继续使用它们进行数学运算之前,将这些向量标准化是一种很好的做法。
答案 1 :(得分:2)
背后的数学很简单。首先需要2个vec3(一个用于相机位置,一个用于外观位置)
我假设你的向上矢量是(0,1,0)。所以计算应该是这样的:
vec3 lookatPosition;
vec3 cameraPosition;
vec3 upVector(0,1,0);
float movementSpeed;
vec3 forwardVector = lookatPosition - cameraPosition;
//You can generate like that if you don't have operator overload
//forwardVector.x = lookatPosition.x - cameraPosition.x;
//forwardVector.y = lookatPosition.y - cameraPosition.y;
//forwardVector.z = lookatPosition.z - cameraPosition.z;
forwardVector.normalise() // normalise your vector
//moving forward :
cameraPosition += forwardVector * movementSpeed;
lookatPosition += forwardVector * movementSpeed;
//Again you can do the operation like that if you don't have operator overloading
//cameraPosition.x += forwardVector.x * movementSpeed;
//cameraPosition.y += forwardVector.y * movementSpeed;
//cameraPosition.z += forwardVector.z * movementSpeed;
//moving backward :
cameraPosition -= forwardVector * movementSpeed;
lookatPosition -= forwardVector * movementSpeed;
//moving left :
vec3 leftVector = Crossproduct(upVector,forwardVector);
cameraPosition += leftVector * movementSpeed;
lookatPosition += leftVector * movementSpeed;
//moving right :
vec3 rightVector = Crossproduct(forwardVector,upVector);
cameraPosition += rightVector * movementSpeed;
lookatPosition += rightVector * movementSpeed;
注意:数据类型和函数名称不是内置的,您可以实现自己的数据类型或使用glm作为向量。