bate's blog

調べたこと実装したことなどを取りとめもなく書きます。

unityでコッホアイランド

DrawCallが10なのが気になる。

初期
F→F-F-F-F

変換規則
F→F+FF-FF-F-F+F+FF-F-F+F+FF+FF-F

  1. →+
  • →-

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_InitialString = "F-F-F-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");
		//m_RuleTable.Add("F", "F+F-F-F+F");
		m_RuleTable.Add("F", "F+FF-FF-F-F+F+FF-F-F+F+FF+FF-F");
		m_RuleTable.Add("-", "-");
		m_RuleTable.Add("+", "+");
		string cmd = m_InitialString;
		for(int i = 0; i < 2; ++i) {
			m_CurrentString = "";
			foreach(char s in cmd) {
				m_CurrentString += m_RuleTable[s.ToString()];
			}
			cmd = m_CurrentString;
		}
		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 () {
	
	}
}
広告を非表示にする