Unity C# 常用几何计算代码
1.2D绕点旋转,不用Transform。2D的话不使用Unity的Quaternion跟Vector类,直接用数学公式计算绕原点旋转的话照下面。不知道现在Unity有没有类似方便的公式了,反正挺常用的。
Vector3 Rotate(Vector3 relativePosition, float degree)
{
float angle = degree / 180f * Mathf.PI;
float x = Mathf.Cos(angle) * relativePosition.x - relativePosition.y * Mathf.Sin(angle);
float y = relativePosition.x * Mathf.Sin(angle) + relativePosition.y * Mathf.Cos(angle);
return new Vector3(x, y,0 );
}
2.3D绕点旋转,不用Transform。
3D的话有几种做法,先把一个简单的Qualification方式,假如绕pivot点旋转就是下面。
public Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Vector3 angles) {
return Quaternion.Euler(angles) * (point - pivot) + pivot;
}
3.屏幕坐标到Orthographic正交相机坐标。
public Vector3 ScreenPositionToOrthograhicCameraPosition()
{
float sizePerPixel = mCamera.orthographicSize * 2 / Screen.height;
float x = (Input.mousePosition.x - Screen.width / 2) * sizePerPixel;
float y = (Input.mousePosition.y - Screen.height / 2) * sizePerPixel;
return mCamera.transform.position + mCamera.transform.up * y + mCamera.transform.right * x;
}
4.判断点是否在三角形内。(3D)
当然先要检测点是否在三角形的平面上,把点投射到三角形的面用Unity的Plane类可以做到。
然后可以用三角形的AABB,如果不在AABB里面那么就不用进行下面的计算了。
方法一 使用叉乘,点乘
bool Isinside(Vector3 point,Vector3 a,Vector3 b,Vector3 c)
{
Vector3 pa = a - point;
Vector3 pb = b - point;
Vector3 pc = c - point;
Vector3 pab = Vector3.Cross(pa,pb);
Vector3 pbc = Vector3.Cross(pb, pc);
Vector3 pca = Vector3.Cross(pc, pa);
float d1 = Vector3.Dot(pab, pbc);
float d2 = Vector3.Dot(pab, pca);
float d3 = Vector3.Dot(pbc, pca);
if (d1 > 0 && d2 > 0 && d3 > 0) return true;
return false;
}
方法二 面积
bool Isinside2(Vector3 point, Vector3 a, Vector3 b, Vector3 c)
{
float s1 = Area(a,b,c);
float s2 = Area(point, a, b);
float s3 = Area(point, a, c);
float s4 = Area(point, b, c);
if (s2 == 0 || s3 == 0 || s4 == 0) return false;
if (s1 - (s2+s3+s4)<= 0.00001f) return true;
return false;
}
float Area(Vector3 a, Vector3 b, Vector3 c)
{
float dab = Vector3.Distance(a, b);
float dac = Vector3.Distance(a, c);
float dbc = Vector3.Distance(b, c);
float half = (dab + dac + dbc) / 2;
return Mathf.Sqrt(half * (half - dab) * (half - dac) * (half - dbc));
}
页:
[1]