In my game, you can move forward and backwards but I don’t know how to side step to the left or right
GLfloat v[] = {[self centerAtIndex:0] - [self eyeAtIndex:0],[self centerAtIndex:1] - [self eyeAtIndex:1], [self centerAtIndex:2] - [self eyeAtIndex:2]};
//forward
[self setEye:[self eyeAtIndex:0] + v[0] * SPEED_MOVE atIndex:0];
[self setEye:[self eyeAtIndex:2] + v[2] * SPEED_MOVE atIndex:2];
[self setCenter: [self centerAtIndex:0] + v[0] * SPEED_MOVE atIndex:0];
[self setCenter: [self centerAtIndex:2] + v[2] * SPEED_MOVE atIndex:2];
gluLookAt(eye[0], eye[1], eye[2],center[0], center[1], center[2], 0.0, 1, 0.0);
Can anyone give me the actual code to make the camera go sideways. I have tried switching the v[2] and v[0] and that does make me move sideways for a couple of angles only, it seems to go the opposite way most the time or even forward.
Solution
float up[3] = {0, 1, 0};
float forward[3] = { center[0] - eye[0],center[1] - eye[1],center[2] - eye[2] };
float left[3];
left[0] = forward[1] * up[2] - forward[2] * up[1];
left[1] = forward[2] * up[0] - forward[0] * up[2];
left[2] = forward[0] * up[1] - forward[1] * up[0];
// now translate your eye position
[self setEye:[self eyeAtIndex:0] - left[0] * SPEED_MOVE atIndex:0];
[self setEye:[self eyeAtIndex:2] - left[2] * SPEED_MOVE atIndex:2];
[self setCenter: [self centerAtIndex:0] - left[0] * SPEED_MOVE atIndex:0];
[self setCenter: [self centerAtIndex:2] - left[2] * SPEED_MOVE atIndex:2];
if (([self eyeAtIndex:2] >= MapSizeZ || [self eyeAtIndex:0] >= MapSizeX || [self eyeAtIndex:2] <= 1 || [self eyeAtIndex:0] <= 1) || [self checkCollisionWithPoint:CGPointMake([self eyeAtIndex:0] ,[self eyeAtIndex:2])] ){
[self setEye:[self eyeAtIndex:0] + left[0] * SPEED_MOVE atIndex:0];
[self setEye:[self eyeAtIndex:2] + left[2] * SPEED_MOVE atIndex:2];
[self setCenter: [self centerAtIndex:0] + left[0] * SPEED_MOVE atIndex:0];
[self setCenter: [self centerAtIndex:2] + left[2] * SPEED_MOVE atIndex:2];
}
You can get a vector pointing sideways by calculating the cross product of the up vector (here [0 1 0]) and the “look” vector (here
center - eye). From that you get a vector pointing to the right or left side depending on the order. Then just add/subtract that vector to the current camera position (eye, center) in order to strafe.Coding it yourself should be fairly easy, the cross product is a simple formula. And there are many fully implemented camera classes available on the Internet.