Vector2,3,4类在DirectX中都有现成的可以调用,不过要实现其中的功能其实也不难,也都是一些简单的数学知识罢了。
本文用C++实现一个简单的Vector3类的功能,暂时有的功能是:
1 + - * /算术运算
2 向量的数量积,又叫:点乘
3 向量的向量积,又叫:叉乘
4 向量单位化(normalization)
//Vecotr3.h
#pragma once
extern const double uZero;
class Vector3
{
float x, y, z;
public:
Vector3():x(0), y(0), z(0){}
Vector3(float x1, float y1, float z1):x(x1), y(y1), z(z1){}
Vector3(const Vector3 &v);
~Vector3();
void operator=(const Vector3 &v);
Vector3 operator+(const Vector3 &v);
Vector3 operator-(const Vector3 &v);
Vector3 operator/(const Vector3 &v);
Vector3 operator*(const Vector3 &v);
Vector3 operator+(float f);
Vector3 operator-(float f);
Vector3 operator/(float f);
Vector3 operator*(float f);
float dot(const Vector3 &v);
float length();
void normalize();
Vector3 crossProduct(const Vector3 &v);
void printVec3();
};
//Vector3.cpp
#include"Plane.h"
#include
const double uZero = 1e-6;
//复制构造函数,必须为常量引用参数,否则编译不通过
Vector3::Vector3(const Vector3 &v):x(v.x), y(v.y), z(v.z)
{
}
Vector3::~Vector3()
{
}
void Vector3::operator=(const Vector3 &v)
{
x = v.x;
y = v.y;
z = v.z;
}
Vector3 Vector3::operator+(const Vector3 &v)
{
return Vector3(x+v.x, y+v.y, z+v.z);
}
Vector3 Vector3::operator-(const Vector3 &v)
{
return Vector3(x-v.x, y-v.y, z-v.z);
}
Vector3 Vector3::operator/(const Vector3 &v)
{
if (fabsf(v.x) <= uZero || fabsf(v.y) <= uZero || fabsf(v.z) <= uZero)
{
std::cerr<<"Over flow!
";
return *this;
}
return Vector3(x/v.x, y/v.y, z/v.z);
}
Vector3 Vector3::operator*(const Vector3 &v)
{
return Vector3(x*v.x, y*v.y, z*v.z);
}
Vector3 Vector3::operator+(float f)
{
return Vector3(x+f, y+f, z+f);
}
Vector3 Vector3::operator-(float f)
{
return Vector3(x-f, y-f, z-f);
}
Vector3 Vector3::operator/(float f)
{
if (fabsf(f) < uZero)
{
std::cerr<<"Over flow!
";
return *this;
}
return Vector3(x/f, y/f, z/f);
}
Vector3 Vector3::operator*(float f)
{
return Vector3(x*f, y*f, z*f);
}
float Vector3::dot(const Vector3 &v)
{
return x*v.x + y*v.y + z*v.z;
}
float Vector3::length()
{
return sqrtf(dot(*this));
}
void Vector3::normalize()
{
float len = length();
if (len < uZero) len = 1;
len = 1/len;
x *= len;
y *= len;
z *= len;
}
/*
Cross Product叉乘公式
aXb = | i, j, k |
| a.x a.y a.z|
| b.x b.y b.z| = (a.y*b.z -a.z*b.y)i + (a.z*b.x - a.x*b.z)j + (a.x*b.y - a.y*b.x)k
*/
Vector3 Vector3::crossProduct(const Vector3 &v)
{
return Vector3(y * v.z - z * v.y,
z * v.x - x * v.z,
x * v.y - y * v.x);
}
void Vector3::printVec3()
{
std::cout<<"("<
测试主程序:
#include
#include
#include"Vector3.h"
using namespace std;
int main()
{
Vector3 v31;
Vector3 v32(2.0f,3.0f,4.0f);
Vector3 v33(v32 - 1.0f);
cout<<"We have original Vector3s:
";
v31.printVec3();
v32.printVec3();
v33.printVec3();
cout<<"v32 crossproduct v33 is:
";
Vector3 v3233 = v32.crossProduct(v33);
v3233.printVec3();
cout<<"Now we normalize them:
";
v31.normalize();
v32.normalize();
v33.normalize();
v3233.normalize();
v31.printVec3();
v32.printVec3();
v33.printVec3();
v3233.printVec3();
system("pause");
return 0;
}
运算结果: