⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 vector.h

📁 visual c++ 实例编程
💻 H
字号:
// From gamasutra. This file may follow different licence features.

// A floating point number
//

typedef float SCALAR;

//
// A 3D vector
//

class VECTOR
{
public:
	SCALAR x,y,z; //x,y,z coordinates
public:
	VECTOR() : x(0), y(0), z(0) {}

	VECTOR( const SCALAR& a, const SCALAR& b, const SCALAR& c ) : x(a), y(b), z(c) {}

	//index a component
	//NOTE: returning a reference allows
	//you to assign the indexed element

	SCALAR& operator [] ( const long i )
	{
		return *((&x) + i);
	}

//compare

	const bool operator == ( const VECTOR& v ) const
	{
		return (v.x==x && v.y==y && v.z==z);
	}

	const bool operator != ( const VECTOR& v ) const
	{
		return !(v == *this);
	}

//negate

	const VECTOR operator - () const
	{
		return VECTOR( -x, -y, -z );
	}

//assign

	const VECTOR& operator = ( const VECTOR& v )
	{
		x = v.x;
		y = v.y;
		z = v.z;
		return *this;
	}

//increment

	const VECTOR& operator += ( const VECTOR& v ) 
	{
		x+=v.x;
		y+=v.y;
		z+=v.z;
		return *this;
	} 

//decrement

	const VECTOR& operator -= ( const VECTOR& v ) 
	{
		x-=v.x;
		y-=v.y;
		z-=v.z;
		return *this;
	} 

//self-multiply
	const VECTOR& operator *= ( const SCALAR& s )
	{
		x*=s;
		y*=s;
		z*=s;
		return *this;
	}

//self-divide
	const VECTOR& operator /= ( const SCALAR& s )
	{
		const SCALAR r = 1 / s;
		x *= r;
		y *= r;
		z *= r;
		return *this;
	}

//add

	const VECTOR operator + ( const VECTOR& v ) const
	{
		return VECTOR(x + v.x, y + v.y, z + v.z);
	}

//subtract

	const VECTOR operator - ( const VECTOR& v ) const
	{
		return VECTOR(x - v.x, y - v.y, z - v.z);
	}

//post-multiply by a scalar

	const VECTOR operator * ( const SCALAR& s ) const
	{
		return VECTOR( x*s, y*s, z*s );
	}

//pre-multiply by a scalar

	friend inline const VECTOR operator * ( const SCALAR& s, const VECTOR& v )
	{
		return v * s;
	}

//divide

	const VECTOR operator / (SCALAR s) const
	{
		s = 1/s;
		return VECTOR( s*x, s*y, s*z );
	}

//cross product

	const VECTOR cross( const VECTOR& v ) const
	{
		//Davis, Snider, "Introduction to Vector Analysis", p. 44
		return VECTOR( y*v.z - z*v.y, z*v.x - x*v.z, x*v.y - y*v.x );
	}

//scalar dot product

	const SCALAR dot( const VECTOR& v ) const
	{
		return x*v.x + y*v.y + z*v.z;
	}

//length

	const SCALAR length() const
	{
		return (SCALAR)sqrt( (double)this->dot(*this) );
	}

//unit vector

	const VECTOR unit() const
	{
	return (*this) / length();
	}

//make this a unit vector

	void normalize()
	{
		(*this) /= length();
	}

//equal within an error 慹

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -