L-system(4日目)

前回はUnityで線分を描画しましたが、今回はL-systemで作成した曲線が描画できることを確認します。LineRendererコンポーネントは一筆書きできる線分にしか対応していないため、コッホ曲線を描画します。枝分かれした線の描画は次にやることにします。

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Example : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        // Make string representation of tree
        int n = 3;
        string s = "F";
        for (int i = 0; i < n; i++)
        {
            string ss = s.Replace("F", "F+F--F+F");
            s = ss;
        }

        LineRenderer renderer = gameObject.GetComponent<LineRenderer>();

        // Number of nodes
        int nn = (int)Math.Pow(4.0, (double)n) + 1;
        renderer.positionCount = nn;

        // Interplate node positions from the string
        Vector3 p = new Vector3(-7.5f, 0f, 0f);
        float d = 5.0f / (float)Math.Pow(3f, (double)(n-1));
        double delta = 60.0 / 180.0 * Math.PI;
        double theta = 0.0 / 180.0 * Math.PI;
        
        int count = 0;
        renderer.SetPosition(0, p); // First position
        for (int i = 0; i < s.Length; i++)
        {
            if (s.Substring(i,1) == "F")
            {
                count++;
                p = p + d * new Vector3
                    ((float)Math.Cos(theta), (float)Math.Sin(theta), 0f);
                renderer.SetPosition(count, p);
            }
            else if (s.Substring(i,1) == "-")
            {
                theta -= delta; // Rotate turtle -delta
            }
            else if (s.Substring(i,1) == "+")
            {
                theta += delta; // Rotate turtle +delta
            }
        }

        // Line width
        renderer.startWidth = 0.1f;
        renderer.endWidth = 0.1f;
    }

    // Update is called once per frame
    void Update()
    {
    }

f:id:hsmtta:20201017214746p:plain
上のスクリプトで描画される曲線