unityでL-Systemをやるためのあれこれ
前々から気になっていたので、色々試すためのテストをした。
OpenRLは手詰まり感があるので保留。
Unity4ゲームコーディング 本当にゲームが作れるスクリプトの書き方
- 作者: 浅野祐一,荒川巧也
- 出版社/メーカー: SBクリエイティブ
- 発売日: 2014/03/28
- メディア: 大型本
- この商品を含むブログ (3件) を見る
シリンダーを使ったプレファブ「Branch」を用意しておく。
using UnityEngine; using System.Collections; using System.Collections.Generic; public class LSystem : MonoBehaviour { GameObject m_Root = null; const float FORWARD_DISTANCE = 2.0f; class Pointer { public Vector3 pos = Vector3.zero; public Quaternion rot = Quaternion.identity; } string m_InitialString = "F"; string m_CurrentString = ""; Dictionary<string, string> m_RuleTable = null; Pointer m_Pointer = null; int m_Index = 0; void Awake () { m_Pointer = new Pointer(); m_Pointer.pos = Vector3.zero; m_Pointer.rot = Quaternion.identity; m_Root = new GameObject("Tree"); m_Root.transform.position = Vector3.zero; m_Root.transform.rotation = Quaternion.identity; m_RuleTable = new Dictionary<string, string>(); m_RuleTable.Add("F", "FFF-FF-F-F+F+FF-F-FFF"); foreach(char s in m_InitialString) { Debug.Log(s); m_CurrentString += m_RuleTable[s.ToString()]; } Debug.Log(m_CurrentString); } void Build (string command) { foreach(char s in command) { ParseCommand(s); } } void ParseCommand(char s) { switch(s) { case 'F': Debug.Log("pos="+m_Pointer.pos+",rot="+m_Pointer.rot); GameObject go = GameObject.Instantiate(Resources.Load("Branch")) as GameObject; go.name = "Branch"+m_Index; go.transform.position = m_Pointer.pos; go.transform.rotation = m_Pointer.rot; go.transform.parent = m_Root.transform; Vector3 n = m_Pointer.rot*(FORWARD_DISTANCE*Vector3.up) + m_Pointer.pos; m_Pointer.pos = n; break; case '-': m_Pointer.rot = m_Pointer.rot * Quaternion.AngleAxis(90.0f, Vector3.left); break; case '+': m_Pointer.rot = m_Pointer.rot * Quaternion.AngleAxis(-90.0f, Vector3.left); break; } m_Index++; } // Use this for initialization void Start () { Build(m_CurrentString); } // Update is called once per frame void Update () { } }