C# 贝塞尔工作不正常
我试图在我的Unity游戏中实现一个简单的贝塞尔曲线,但它似乎不起作用。 以下是如何绘制的屏幕截图: 4个绿色球体是贝塞尔的枢轴,白色球体是正在计算的实际贝塞尔。正如你所看到的,这有点不正确 这是我的贝塞尔代码(我从Unity论坛上获得):C# 贝塞尔工作不正常,c#,unity3d,bezier,C#,Unity3d,Bezier,我试图在我的Unity游戏中实现一个简单的贝塞尔曲线,但它似乎不起作用。 以下是如何绘制的屏幕截图: 4个绿色球体是贝塞尔的枢轴,白色球体是正在计算的实际贝塞尔。正如你所看到的,这有点不正确 这是我的贝塞尔代码(我从Unity论坛上获得): 使用UnityEngine; [系统可序列化] 公共类Bezier:System.Object { 公共向量3 p0; 公共向量3 p1; 公共向量3p2; 公共向量3 p3; 公共浮点数ti=0f; 私有向量3 b0=向量3.0; 私有向量3 b1=向量
使用UnityEngine;
[系统可序列化]
公共类Bezier:System.Object
{
公共向量3 p0;
公共向量3 p1;
公共向量3p2;
公共向量3 p3;
公共浮点数ti=0f;
私有向量3 b0=向量3.0;
私有向量3 b1=向量3.0;
私有向量3 b2=向量3.0;
私有向量3 b3=向量3.0;
私人浮动斧头;
私人浮动账户;
私人浮子;
私人浮动Bx;
私人游船;
私人浮动Bz;
私人浮动Cx;
私人股本;
私人浮动Cz;
//初始函数v0=第1点,v1=第1点的句柄,v2=第2点的句柄,v3=第2点
//手柄1=v0+v1
//handle2=v3+v2
公共贝塞尔(Vector3 v0、Vector3 v1、Vector3 v2、Vector3 v3)
{
这是0.p0=v0;
这是1.p1=v1;
这是1.p2=v2;
这是p3=v3;
}
//0.0>=t看起来很像GetPointAtTime
是用来生成贝塞尔点的。如果是这种情况,您根本没有计算正确的函数:对于立方贝塞尔,函数是:
a ‧ t³ + 3 ‧ b ‧ t² ‧ (1-t) + 3 ‧ c ‧ t ‧ (1-t)² + d ‧ (1-t)³
因此,您的代码没有使用二项式,它只是使用了一个t
的直多项式,这将生成真正错误的东西=)
因此,改变你的功能:
public float ComputeBezierValue( float t, float a, float b, float c, float d )
{
float t2 = t * t,
t3 = t2 * t,
mt = 1 - t,
mt2 = mt * mt,
mt3 = mt2 * mt;
return a * t3 + 3 * b * t2 * mt + 3 * c * t * mt2 + d * mt3;
}
public Vector3 GetPointAtTime( float t )
{
this.CheckConstant();
float x = ComputeBezierValue(t, this.Ax, this.Bx, this.Cx, this.Dx);
float y = ComputeBezierValue(t, this.Ay, this.By, this.Cy, this.Dy);
float z = ComputeBezierValue(t, this.Az, this.Bz, this.Cz, this.Dz);
return new Vector3( x, y, z );
}
还要注意,我写这篇文章是为了明确使用四个坐标。三次贝塞尔曲线需要全部四个坐标,二次曲线只需要三个坐标(但通常很难表示均匀弯曲的线段,如圆形/椭圆形线段,以及类圆)
a ‧ t³ + 3 ‧ b ‧ t² ‧ (1-t) + 3 ‧ c ‧ t ‧ (1-t)² + d ‧ (1-t)³
public float ComputeBezierValue( float t, float a, float b, float c, float d )
{
float t2 = t * t,
t3 = t2 * t,
mt = 1 - t,
mt2 = mt * mt,
mt3 = mt2 * mt;
return a * t3 + 3 * b * t2 * mt + 3 * c * t * mt2 + d * mt3;
}
public Vector3 GetPointAtTime( float t )
{
this.CheckConstant();
float x = ComputeBezierValue(t, this.Ax, this.Bx, this.Cx, this.Dx);
float y = ComputeBezierValue(t, this.Ay, this.By, this.Cy, this.Dy);
float z = ComputeBezierValue(t, this.Az, this.Bz, this.Cz, this.Dz);
return new Vector3( x, y, z );
}