Skip to content

Instantly share code, notes, and snippets.

@s2kw
Last active June 17, 2016 10:00
Show Gist options
  • Save s2kw/e523350c5a5a19479486fd000b5c7c31 to your computer and use it in GitHub Desktop.
Save s2kw/e523350c5a5a19479486fd000b5c7c31 to your computer and use it in GitHub Desktop.
毎日出題の5日目第一問 description: http://jigax.jp/unityunityとcを学ぶ問題005/ movie: https://vimeo.com/170936882
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.CreateHead();
}
}
// 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 )
{
// 頭部ではない場合は距離を縮める
if (this.bodyType != BodyType.Head)
{
// Lerp関数で目標地点と自分の地点の3割あたりの位置へワープ
this.transform.position = Vector3.Lerp(this.transform.position, this.bigBrother.position, 0.3f);
}
// 生成のした数あ十分であれば終了
if (bodyCount > maxBodyCount) return;
// まだ弟分を生成いたことないならば次へ
if (!this.alreadyMakeBros)
{
// body数とMax数が一致する場合
if (bodyCount != maxBodyCount)
// 身体パーツを作る
this.CreateBody();
else
// 尻尾パーツを作る
this.CreateTail();
// 生成数を加算
bodyCount++;
}
}
}
/// <summary>
/// 頭づくり
/// </summary>
/// <returns>The head.</returns>
void CreateHead()
{
// 球体を創る
var b = GameObject.CreatePrimitive(PrimitiveType.Sphere);
// GameObjectの名前変更
b.name = "HEAD";
// 頭は1.5倍のサイズい。
b.transform.localScale = Vector3.one * 1.5f;
// このコンポーネントを追加
var snake = b.AddComponent<SnakeHead>();
// 頭タイプとして作成されたという情報を渡しておく
snake.bodyType = BodyType.Head;
// 兄貴分として自身を入れる
snake.bigBrother = this.transform;
// 生成済みフラグを立てる
this.alreadyMakeBros = true;
}
/// <summary>
/// 体づくり
/// </summary>
/// <returns>The body.</returns>
void CreateBody()
{
var b = GameObject.CreatePrimitive(PrimitiveType.Sphere);
b.name = "BODY_"+bodyCount;
var snake = b.AddComponent<SnakeHead>();
snake.bodyType = BodyType.Body;
snake.bigBrother = this.transform;
this.alreadyMakeBros = true;
}
/// <summary>
/// 尻尾づくり
/// </summary>
/// <returns>The tail.</returns>
void CreateTail()
{
var b = GameObject.CreatePrimitive(PrimitiveType.Cube);
b.name = "TAIL_" + bodyCount;
var snake = b.AddComponent<SnakeHead>();
snake.bodyType = BodyType.Tail;
snake.bigBrother = this.transform;
this.alreadyMakeBros = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment