捕鱼游戏思路(三):贝塞尔曲线的实现

毫无状态的度过一段时间,今天把贝塞尔曲线实现吧。之前自己推导了一阶,二阶,三阶的贝塞尔方程式,接下来只需要将其实现就好。
在网上找了文章截了两张图(一阶和二阶):

捕鱼游戏思路(三):贝塞尔曲线的实现_第1张图片
贝塞尔一阶.png
捕鱼游戏思路(三):贝塞尔曲线的实现_第2张图片
贝塞尔二阶.png

三阶(没找到,明天上传自己推导的吧)
还有可以参考雨松大神的文章(PS:但是好像有点错误)
链接:http://www.xuanyusong.com/archives/1548
接下来就是三阶的代码:

using UnityEngine;

[System.Serializable]
public class Bezier : System.Object

{
//定义四个点,起点终点,两个控制点
public Vector3 p0;
public Vector3 p1;
public Vector3 p2;
public Vector3 p3;

public float ti = 0f;

//定义几个私有的向量来存储那些点
private Vector3 b0 = Vector3.zero;
private Vector3 b1 = Vector3.zero;
private Vector3 b2 = Vector3.zero;
private Vector3 b3 = Vector3.zero;

//四个点之间的三个比例点的坐标
private float Ax;
private float Ay;
private float Az;

private float Bx;
private float By;
private float Bz;

private float Cx;
private float Cy;
private float Cz;

//初始化这四个点
public Bezier(Vector3 v0, Vector3 v1, Vector3 v2, Vector3 v3)
{
    this.p0 = v0;
    this.p1 = v1;
    this.p2 = v2;
    this.p3 = v3;
}


// 0.0 >= t <= 1.0
//获取t时刻的点
public Vector3 GetPointAtTime(float t)
{
    
    this.CheckConstant();

    float t2 = t * t;
    float t3 = t * t * t;
    float x = this.Ax * t3 + this.Bx * t2 + this.Cx * t + p0.x;
    float y = this.Ay * t3 + this.By * t2 + this.Cy * t + p0.y;
    float z = this.Az * t3 + this.Bz * t2 + this.Cz * t + p0.z;
    return new Vector3(x, y, z);

}

private void SetConstant()
{

    this.Cx = 3f * (this.p1.x - this.p0.x);
    this.Bx = 3f * (this.p2.x - this.p1.x) - this.Cx;
    this.Ax = this.p3.x - this.p0.x - this.Cx - this.Bx;

    this.Cy = 3f * (this.p1.y - this.p0.y);
    this.By = 3f * (this.p2.y - this.p1.y) - this.Cy;
    this.Ay = this.p3.y - this.p0.y - this.Cy - this.By;

    this.Cz = 3f * (this.p1.z- this.p0.z);
    this.Bz = 3f * (this.p2.z - this.p1.z) - this.Cz;
    this.Az = this.p3.z - this.p0.z - this.Cz - this.Bz;

}

// Check if p0, p1, p2 or p3 have changed
private void CheckConstant()
{
    if (this.p0 != this.b0 || this.p1 != this.b1 || this.p2 != this.b2 || this.p3 != this.b3)
    {
        this.SetConstant();
        this.b0 = this.p0;
        this.b1 = this.p1;
        this.b2 = this.p2;
        this.b3 = this.p3;
    }
}
}

这个实际上是在雨松大神的基础上修正的(PS:微笑脸),但是重要的贝塞尔的理解(PS:微笑脸)

你可能感兴趣的:(捕鱼游戏思路(三):贝塞尔曲线的实现)