using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MathTest
{
/// <summary>
/// 3D向量类
/// </summary>
public class Vector3
{
public float x;
public float y;
public float z;
public Vector3() { }
public Vector3(Vector3 a)
{
x = a.x;
y = a.y;
z = a.z;
}
public Vector3(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
}
//置为零向量
public void Zero()
{
x = y = z = 0.0f;
}
//向量标准化
public void Normalize()
{
float magSq = x * x + y * y + z * z;
if (magSq > 0.0f) //检查除零
{
float oneOverMag = 1.0f / (float)Math.Sqrt(magSq);
x *= oneOverMag;
y *= oneOverMag;
z *= oneOverMag;
}
}
//重载"=="操作符
public static bool operator ==(Vector3 a, Vector3 b)
{
return a.x == b.x && a.y == b.y && a.z == b.z;
}
//重载"!="操作符
public static bool operator !=(Vector3 a, Vector3 b)
{
return a.x != b.x || a.y != b.y || a.z != b.z;
}
//重载二元"+"运算符
public static Vector3 operator +(Vector3 a, Vector3 b)
{
return new Vector3(a.x + b.x, a.y + b.y, a.z + b.z);
}
//重载二元"-"运算符
public static Vector3 operator -(Vector3 a, Vector3 b)
{
return new Vector3(a.x - b.x, a.y - b.y, a.z - b.z);
}
//重载一元"-"运算符
public static Vector3 operator -(Vector3 a)
{
return new Vector3(-a.x, -a.y, -a.z);
}
//与标量的乘法
public static Vector3 operator *(Vector3 a, float n)
{
return new Vector3(a.x * n, a.y * n, a.z * n);
}
//向量点乘
public static Vector3 operator *(Vector3 a, Vector3 b)
{
return new Vector3(a.x * b.x, a.y * b.y, a.z * b.z);
}
//与标量的除法
public static Vector3 operator /(Vector3 a, float n)
{
float oneOverN = 1.0f / n; //注意:这里不对“除零”进行检查
return new Vector3(a.x * oneOverN, a.y * oneOverN, a.z * oneOverN);
}
//求向量模
public float VectorMag()
{
return (float)Math.Sqrt(x * x + y * y + z * z);
}
//计算两向量的叉乘
public static Vector3 CrossProduct(Vector3 a, Vector3 b)
{
return new Vector3(
a.y * b.z - a.z * b.y,
a.z * b.x - a.x * b.z,
a.x * b.y - a.y * b.x
);
}
//计算两点间的距离
public static float Distance(Vector3 a, Vector3 b)
{
float dx = a.x - b.x;
float dy = a.y - b.y;
float dz = a.z - b.z;
return (float)Math.Sqrt(dx * dx + dy * dy + dz * dz);
}
}
}