Last active
June 22, 2016 06:50
-
-
Save s2kw/eb91f4aa34c63b51249d7b96415a848c to your computer and use it in GitHub Desktop.
毎日出題の7日目第一問[description]( http://jigax.jp/unityunity%E3%81%A8c%E3%82%92%E5%AD%A6%E3%81%B6%E5%95%8F%E9%A1%8C007/ )
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 enum BodyType | |
{ | |
None, // 親用 | |
Head, // 頭部用 | |
Body, // 身体用 | |
Tail, // 尻尾用 | |
} | |
public Transform bigBrother; // 連結する対象を格納する。以降兄貴分として記述 | |
public BodyType bodyType; // 自身が何のタイプなのかを指定される | |
bool alreadyMakeBros = false; // 既に弟分を作ったことがあるか否か | |
[SerializeField] | |
float distance = 0.5f; // この距離以上離れたら追いかける。 | |
// Use this for initialization | |
void Start () { | |
// 起動時い生成うるのは親だけ。 | |
if ( this.bodyType == BodyType.None ) | |
{ | |
this.CreateSnakePart(BodyType.Head); | |
} | |
} | |
// 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; | |
// 頭部ではない場合は距離を縮める | |
if (this.bodyType != BodyType.Head) | |
{ | |
// Lerp関数で目標地点と自分の地点の3割あたりの位置へワープ | |
this.transform.position = Vector3.Lerp(this.transform.position, this.bigBrother.position, 0.3f); | |
} | |
// 生成のした数が十分であれば終了 | |
if (bodyCount > maxBodyCount) return; | |
// body数とMax数が一致する場合 | |
if (bodyCount != maxBodyCount) | |
// 身体パーツを作る | |
this.CreateSnakePart(BodyType.Body); | |
else | |
// 尻尾パーツを作る | |
this.CreateSnakePart(BodyType.Tail); | |
} | |
void CreateSnakePart( BodyType bodyType ) | |
{ | |
if (this.alreadyMakeBros) return; | |
var g = GameObject.CreatePrimitive( bodyType == BodyType.Tail ? PrimitiveType.Cube : PrimitiveType.Sphere ); | |
if (bodyType == BodyType.Head) | |
{ | |
g.transform.localScale = Vector3.one * 1.5f; | |
} | |
g.name = string.Format( "{0}_{1}",bodyType.ToString().ToUpper(),bodyCount ); | |
var snake = g.AddComponent<SnakeHead>(); | |
snake.bigBrother = this.transform; | |
snake.bodyType = bodyType; | |
this.alreadyMakeBros = true; | |
// 生成数を加算 | |
bodyCount++; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment