Skip to content

Instantly share code, notes, and snippets.

@litefeel
Last active September 13, 2018 07:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save litefeel/eaf2f925650b3b48450e425209de7b2d to your computer and use it in GitHub Desktop.
Save litefeel/eaf2f925650b3b48450e425209de7b2d to your computer and use it in GitHub Desktop.
BarycentricCoordinates.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// https://rhetty.github.io/2018/03/20/三角形线性插值——重心坐标/
// https://zh.wikipedia.org/wiki/笛卡尔坐标系
// https://en.wikipedia.org/wiki/Barycentric_coordinate_system
public struct BarycentricCoordinates
{
private Vector2 _a, _b, _c; // 三角形
private float _s; // 三角形面积
public bool IsTriangle { get; private set; }
public void SetTriangle(Vector2 a, Vector2 b, Vector2 c)
{
_a = a;
_b = b;
_c = c;
IsTriangle = a != b && a != c && b != c;
if (IsTriangle)
_s = CalcS(a, b, c);
}
// 计算P点的重心坐标
public Vector3 CalcBarycentricPos(Vector2 p)
{
var sa = CalcS(p, _b, _c);
var sb = CalcS(p, _c, _a);
var sc = CalcS(p, _a, _b);
return new Vector3(sa / _s, sb / _s, sc / _s);
}
// 计算P点的笛卡尔坐标
public Vector2 CalcCartesianPos(Vector3 v)
{
return v.x * _a + v.y * _b + v.z * _c;
}
public static bool InTriangle(Vector3 v)
{
return v.x >= 0 && v.x <= 1
&& v.y >= 0 && v.y <= 1
&& v.z >= 0 && v.z <= 1;
}
private static float CalcS(Vector2 a, Vector2 b, Vector3 c)
{
// 1 ax ay
// 1 bx by
// 1 cx cy
var s = b.x * c.y + a.x * b.y + c.x * a.y - c.x * b.y - b.x * a.y - a.x * c.y;
return s * 0.5f;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment