Hello everyone, I am pretty new to game/graphics programming. I am trying to do a bit of learning with WebGl. I am trying to get a camera to rotate around a cube.
I thought I could do this with a bit of spherical math. I am targeting the camera at (0,0,0), which is where my cube is. I would like to rotate around in a circle. I am going for the type of camera you might see in a platformer. Where the camera fixes on one point and then can rotate about that point, move up and down, and follow the point.
Here is where I set the camera position (the view matrix):
var a = 10 * Math.cos(0);
cameraPosition[2] = a * Math.cos(rad);
cameraPosition[1] = 10 * Math.sin(0);
cameraPosition[0] = a * Math.sin(rad);
Now with phi = 0, everything works as expected. I am facing the cube dead on.
However if I set phi to PI / 4 or 45 degrees, then everything seems to tilt, and I rotate through the floor while still targeting 0, 0, 0.
I am pretty sure the code that is incorrect is where I set my View Matrix. I've tried the spherical math a few different ways, with the same result, and conceptually I think that I understand that a lot better than I do the View Matrix math.
Here is my code for setting the View Matrix:
var z = vec3.create();
var x = vec3.create();
var y = vec3.create();
vec3.subtract(z, cameraPosition, cameraTarget);
vec3.normalize(z, z);
vec3.cross(x, cameraUp, z)
vec3.normalize(x, x);
vec3.cross(y, z, x);
vMatrix[0] = x[0];
vMatrix[1] = x[1];
vMatrix[2] = x[2];
vMatrix[3] = 0;
vMatrix[4] = y[0];
vMatrix[5] = y[1];
vMatrix[6] = y[2];
vMatrix[7] = 0;
vMatrix[8] = z[0];
vMatrix[9] = z[1];
vMatrix[10] = z[2];
vMatrix[11] = 0;
vMatrix[12] = -vec3.dot(x, cameraPosition);
vMatrix[13] = -vec3.dot(y, cameraPosition);
vMatrix[14] = -vec3.dot(z, cameraPosition);
vMatrix[15] = 1;
Here is the code to set my cameraPosition, target, and up vectors, of course I am changing camera position to be the values I think I need, in the code at the beginning of this post.
var cameraTarget = vec3.fromValues(0, 0, 0);
var cameraPosition = vec3.fromValues(0, 0, 0);
var cameraUp = vec3.fromValues(0, 1, 0);
If anyone can spot what I am doing wrong, or help me out conceptually, that would be much appreciated. I've been trying different things for the better part of 4 hours.
Thank you.
Chris