unityで数式をグラフ化したり視覚化する
unityで数式をグラフ化したり視覚化する
<注目点>
- デリゲートの使い方(デリゲート関数の配列とenumのメンバーを同期するようにしている)
- パーティクルを使ったグラフ化
- 各数式を視覚化
- パーティクルにはソート順の指定がある(既定は生成順表示)
<注釈を日本語化したコード>
using UnityEngine;
using System.Collections;
public class Grapher1Test : MonoBehaviour
{
public enum Function { Linear, Exponential, Parabola, Sine } public Function function;
delegate float FunctionDelegate (float x);
static FunctionDelegate[] functionDelegates = { Linear, Exponential, Parabola, Sine };
[Range(10,100)] public int resolution = 10; int currentResolution; ParticleSystem.Particle[] point;
void Start () { CreatePoint (); }
void CreatePoint () { if (resolution < 10 | | resolution > 100) { Debug.LogWarning ("解像度が大きすぎるか小さすぎます", this); resolution = 10; } currentResolution = resolution; point = new ParticleSystem.Particle[resolution]; float increment = 1f / (resolution - 1); for (int i = 0; i < resolution; i++) { float x = i * increment; point [i].position = new Vector3 (x, 0, 0); point [i].color = new Color (x, 0, 0); point [i].size = 0.1f; } } void Update () { if (currentResolution != resolution | | point == null) { CreatePoint (); } //実行中にリアルタイムにレゾリューションを変更した場合、即座に反映させる //配列が空でも生成する
//デリゲートセレクタ FunctionDelegate f = functionDelegates [(int)function];
for (int i = 0; i < resolution; i++) { Vector3 p = point [i].position; p.y = f (p.x); point [i].position = p;
Color c = point [i].color; c.g = c.r; point [i].color = c;
} particleSystem.SetParticles (point, point.Length); }
//リニア static float Linear (float x) { return x; }
//f(x) = x^2 //右上がりのグラフ static float Exponential (float x) { return x * x; }
//f(x) = (2x-1)^2 //放物線 static float Parabola (float x) { x = 2f * x - 1f; return x * x; }
//f(x) = (sin(2πx)+1)/2 //サインカーブ static float Sine (float x) { return 0.5f + 0.5f * Mathf.Sin (2 * Mathf.PI * x + Time.timeSinceLevelLoad); }
}
- 最終更新:2013-11-27 17:40:26