I'm writing up a camera class today and I'm having troubles. The mouse handles perfectly fine, but motion is not so good looking. I believe it may have to do with my vector math functions. Is there anything wrong here?
SimStructs.h
typedef struct SimVector
{
float x, y, z;
void operator= (SimVector v)
{
x = v.x;
y = v.y;
z = v.z;
}
void operator+= (SimVector v)
{
x += v.x;
y += v.y;
z += v.z;
}
void operator-= (SimVector v)
{
x -= v.x;
y -= v.y;
z -= v.z;
}
void operator*= (float a)
{
x *= a;
y *= a;
z *= a;
}
void operator/= (float a)
{
x /= a;
y /= a;
z /= a;
}
SimVector operator+ (SimVector v)
{
SimVector ret;
ret.x = x + v.x;
ret.y = y + v.y;
ret.z = z + v.z;
return ret;
}
SimVector operator- (SimVector v)
{
SimVector ret;
ret.x = x - v.x;
ret.y = y - v.y;
ret.z = z - v.z;
return ret;
}
SimVector operator* (float a)
{
SimVector ret;
ret.x = x * a;
ret.y = y * a;
ret.z = z * a;
}
SimVector operator/ (float a)
{
SimVector ret;
ret.x = x / a;
ret.y = y / a;
ret.z = z / a;
return ret;
}
float operator[] (int a)
{
if(a == 0)
return x;
if(a == 1)
return y;
if(a == 2)
return z;
}
};
namespace SimStructs
{
float GetMagnitude(SimVector v);
void Normalize(SimVector &v);
float DotProduct(SimVector v1, SimVector v2);
SimVector CrossProduct(SimVector v1, SimVector v2);
}
SimStructs.cpp
float SimStructs::GetMagnitude(SimVector v)
{
return sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
}
void SimStructs::Normalize(SimVector &v)
{
float mag = 1.0f / SimStructs::GetMagnitude(v);
v *= mag;
}
float SimStructs::DotProduct(SimVector v1, SimVector v2)
{
return (v1.x * v2.x + v1.y * v2.y + v1.z * v2.z);
}
SimVector SimStructs::CrossProduct(SimVector v1, SimVector v2)
{
SimVector ret;
ret.x = (v1.y * v2.z - v1.z * v2.y);
ret.y = (v1.z * v2.x - v1.x * v2.z);
ret.z = (v1.x * v2.y - v1.y * v2.x);
return ret;
}
Camera code:
void SimCamera::Move(float speed, float timestep)
{
direction = target - position;
SimStructs::Normalize(direction);
position += (direction * speed * timestep);
target += (direction * speed * timestep);
}
void SimCamera::Strafe(float speed, float timestep)
{
direction = target - position;
SimStructs::Normalize(direction);
strafe = SimStructs::CrossProduct(direction, up);
SimStructs::Normalize(strafe);
position += (strafe * speed * timestep);
target += (strafe * speed * timestep);
}
Usage:
camera.MouseInput();
if(globalInput.IsKeyDown(SDLK_w))
camera.Move(1, frameInterval);
if(globalInput.IsKeyDown(SDLK_s))
camera.Move(-1, frameInterval);
if(globalInput.IsKeyDown(SDLK_a))
camera.Strafe(-1, frameInterval);
if(globalInput.IsKeyDown(SDLK_d))
camera.Strafe(1, frameInterval);