由于Unity中的向量用的都是float型去存储,而float型的精度只有五位小数,导致了前段时间做项目的时候出现了精度上的问题。当时重新写了一个简单的类去解决它,过后觉得以后还有可能还会遇到类似的问题,于是系统的写了一下Unity中的几个结构体。
首先是Vector2d:
/// Vector2d.cs
///
/// The double type version of the Unity struct Vector2.
/// It can solve the problem that the float type may not be accurate enough.
///
/// Unity Vector2结构体的double版实现,以解决float型精度可能不够的问题。
///
/// Created by D子宇 on 2018.3.17
///
/// Email: darkziyu@126.com
using System;
using UnityEngine;
namespace Mathd
{
public struct Vector2d
{
#region public members
public double x;
public double y;
#endregion
#region constructor
public Vector2d(double p_x,double p_y) {
x = p_x;
y = p_y;
}
#endregion
#region public properties
public double this[int index]
{
get
{
switch (index)
{
case 0:
return x;
case 1:
return y;
default:
throw new IndexOutOfRangeException("Invalid Vector2d index!");
}
}
set
{
switch (index)
{
case 0:
x = value;
break;
case 1:
y = value;
break;
default:
throw new IndexOutOfRangeException("Invalid Vector2d index!");
}
}
}
public static Vector2d down
{
get
{
return new Vector2d(0, -1);
}
}
public static Vector2d left
{
get
{
return new Vector2d(-1, 0);
}
}
public static Vector2d one
{
get
{
return new Vector2d(1, 1);
}
}
public static Vector2d right
{
get
{
return new Vector2d(1, 0);
}
}
public static Vector2d up
{
get
{
return new Vector2d(0, 1);
}
}
public static Vector2d zero
{
get
{
return new Vector2d(0, 0);
}
}
public double magnitude
{
get
{
return Math.Sqrt(sqrMagnitude);
}
}
public Vector2d normalized
{
get
{
Vector2d result &#