统一在点之间创建带有间隙的线



我正在尝试创建一个类似的游戏,例如Curve Fever,其中某种"蛇"随着尾巴的增加而四处走动。我试图实现的是每x秒在行之间有一次间隙。

目前,我正在使用线渲染器并设置如下点:

void Update() {
    if(Vector3.Distance(points.Last(), snake.position) > pointSpacing)
        SetPoint();
}
public void SetPoint(){
    if (noGap)
    {
        if (points.Count > 1)
            coll.points = points.ToArray<Vector2>();
        points.Add(snake.position);
        line.numPositions = points.Count;
        line.SetPosition(points.Count - 1, snake.position);
    }
}
public IEnumerator LineGap(){
    while (enabled)
    {  
        yield return new WaitForSeconds(2f);
        noGap = false;
        yield return new WaitForSeconds(.5f);
        noGap = true;
    }
}

使用上面的协程,我尝试在 .5 秒内每 2 秒不创建一次点,但制作了一个 LineRenderer 来在每 2 个点之间创建一条线。

有什么方法可以实现我想要做的事情吗?也许通过使用另一种渲染器?

一种选择是为每个线段创建一个新的线渲染器。然后,您的蛇会跟踪线渲染器列表。如果将 LineRenderer 游戏对象设置为预制件,则很容易即时生成它。您的Snake类如下所示:

public class Snake
{
    public GameObject LinePrefab;           //Prefab gameobject with LineRenderer
    private List<LineRenderer> pathList;    //List of line segments
    private LineRenderer line;              //Current line

    private void Start(){
        this.pathList = new List<LineRenderer>();
        SpawnNewLineSegment();
        //Other initialization code
    }
    public void Update(){
        if (!noGap && Vector3.Distance(points.Last(), snake.position) > pointSpacing)
            SetPoint()
    }
    public void SetPoint(){
        if (points.Count > 1)
            coll.points = points.ToArray<Vector2>();
        points.Add(snake.position);
        //Increment the number of points in the line
        line.numPositions = line.numPositions + 1;
        line.SetPosition(line.numPositions - 1, snake.position);
    }
    public IEnumerator LineGap(){
        while (enabled)
        {  
            yield return new WaitForSeconds(2f);
            noGap = false;
            yield return new WaitForSeconds(.5f);
            noGap = true;
            //We are starting a new line, create a new line segment
            SpawnNewLineSegment();
        }
    private LineRenderer SpawnNewLineSegment(){
        //Spawn the gameobject as a parent of this object
        GameObject go = Instantiate(this.LinePrefab, this.transform);
        this.line = go.GetComponent<LineRenderer>();
        this.pathList.Add(this.line)
        //Set the first point on the line
        SetPoint()
    } 
}

唯一的问题是你想如何处理你的碰撞(我想这就是coll的意思)。碰撞是跨越间隙还是在那里留下一个洞?正如所写,看起来对撞机将是连续的(没有间隙)。

如果您担心在运行时生成新游戏对象的性能,您可以在初始化时创建一个游戏对象的池,然后在需要它们之前禁用它们。

最新更新