Last active
June 22, 2016 06:49
-
-
Save s2kw/5a08da843843c9e3bf1adae7191b3839 to your computer and use it in GitHub Desktop.
[description]( http://jigax.jp/unityunity%E3%81%A8c%E3%82%92%E5%AD%A6%E3%81%B6%E5%95%8F%E9%A1%8C007/ ) [code]( https://gist.github.com/s2kw/5a08da843843c9e3bf1adae7191b3839 )
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SnakeHead : MonoBehaviour { | |
static int bodyCount = 0; // 現在の身体の数をカウントするためstaticに。 | |
static readonly int maxBodyCount = 10; // この数字以上のパーツは造らない。 | |
public Transform bigBrother; // 連結する対象を格納する。以降兄貴分として記述 | |
bool alreadyMakeBros = false; // 既に弟分を作ったことがあるか否か | |
int num = -1; // 何番目の身体かを記録する。 | |
[SerializeField] | |
float distance = 0.5f; // この距離以上離れたら追いかける。 | |
// Use this for initialization | |
void Start () { | |
// 起動時い生成うるのは親だけ。 | |
if ( bodyCount == 0 ) | |
{ | |
this.CreateSnakePart(); | |
} | |
} | |
// Update is called once per frame | |
void Update () { | |
// 兄貴分が指定されてないのであれば抜ける | |
if (this.bigBrother == null) return; | |
// 兄貴分との距離を測定し、distance値以上離れたら移行の振る舞いを行う | |
if (Vector3.Distance(this.transform.position, this.bigBrother.position) <= this.distance) return; | |
// Lerp関数で目標地点と自分の地点の3割あたりの位置へワープ | |
if( this.num > 0 ) | |
this.transform.position = Vector3.Lerp(this.transform.position, this.bigBrother.position, 0.3f); | |
// 生成のした数が十分であれば終了 | |
if (bodyCount > maxBodyCount) return; | |
this.CreateSnakePart(); | |
} | |
void CreateSnakePart() | |
{ | |
if (this.alreadyMakeBros) return; | |
// 形状の指定 | |
var g = GameObject.CreatePrimitive( ( bodyCount == 0||bodyCount % 2 == 0) ? PrimitiveType.Cube : PrimitiveType.Sphere ); | |
g.name = string.Format("snake_{0}", bodyCount); | |
var snake = g.AddComponent<SnakeHead>(); | |
if (bodyCount == 0) | |
{ | |
g.transform.localScale = Vector3.one * 1.5f; | |
} | |
snake.bigBrother = this.transform; | |
this.alreadyMakeBros = true; | |
snake.num = bodyCount; | |
// 色を指定 | |
var renderer = g.GetComponent<Renderer>(); | |
if (renderer == null ) return; | |
var mat = new Material(Shader.Find("Standard")); | |
switch ( bodyCount % 3 ) | |
{ | |
case 0: | |
mat.color = Color.red; | |
break; | |
case 1: | |
mat.color = Color.blue; | |
break; | |
case 2: | |
mat.color = Color.green; | |
break; | |
} | |
renderer.material = mat; | |
// 生成数を加算 | |
bodyCount++; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment