Implementing strafe - Opengl - Camera
I created a camera class. It is possible to rotate 360 degrees with my mouse and move up and down. Just as I intended, just like in all games. It is also possible to move forward a开发者_运维问答nd backward just like in all games. But I don't know how to implement moving to the left and right.
I do the following:
This gets called every frame:
gluLookAt(_posX , _posY , _posZ,
_viewX, _viewY, _viewZ,
_upX, _upY, _upZ );
My move function
Doesnt Work:void Camera::moveLeft()
{
float rot= (_viewY / 180 * PI);
_moveX -= float(cos(rot)) * 0.5;
_moveZ -= float(sin(rot)) * 0.5;
}
Does Work
move forwards in the scene:void Camera::moveForward()
{
float viewX = _viewX - _posX;
float viewY = _viewY - _posY;
float viewZ = _viewZ - _posZ;
_posX += viewX * speed
_posY += viewY * speed;
_posZ += viewZ * speed;
_viewX += viewX * speed;
_viewY += viewY * speed;
_viewZ += viewZ * speed;
}
When I move with my mouse only, there is no problem. But if I use this function and rotate with my mouse, I get some strange camera movements
Any ideas of how to solve this?
Thank you
@edit
So I removed the glTranslated statement and I changed my moveLeft function to the following:
void Camera::moveLeft(){
float x = ((_viewY * _upZ) - (_viewZ * _upY));
float y = ((_viewZ * _upX) - (_viewX * _upZ));
float z = ((_viewX * _upY) - (_viewY * _upX));
float magnitude = sqrt( (x * x) + (y * y) + (z * z) );
x /= magnitude;
y /= magnitude;
z /= magnitude;
_posX -= x;
_posY -= y;
_posZ -= z;
}
I am clearly doing something wrong because the movements to left and right are "better", but still not what you would expect.
To get a vector which points at 90 degrees to the plane that contains your up and view vectors, you need to do a cross product: http://en.wikipedia.org/wiki/Cross_product. Any decent vector maths library will have a function for this.
The resulting vector will either be a left vector or a right vector (try it out and find out which) and then add it to your position as appropriate.
Note that this won't work if your view vector is in exactly the same direction as your up vector.
Edit: Based on your edited question I think you need to do this:
You need to get the view direction vector and use that instead of your view vector in the cross product, and then add to both the position and view vector:
void Camera::moveLeft()
{
float viewX = _viewX - _posX;
float viewY = _viewY - _posY;
float viewZ = _viewZ - _posZ;
float x = ((viewY * _upZ) - (viewZ * _upY));
float y = ((viewZ * _upX) - (viewX * _upZ));
float z = ((viewX * _upY) - (viewY * _upX));
float magnitude = sqrt( (x * x) + (y * y) + (z * z) );
x /= magnitude;
y /= magnitude;
z /= magnitude;
_posX -= x;
_posY -= y;
_posZ -= z;
_viewX -= x;
_viewY -= y;
_viewZ -= z;
}
精彩评论