[Unity]UnityとC#を学ぶ問題:005

5日続きました。二桁目指します。

第一問

この動画を再現してください

Snake from s2kw on Vimeo.

Ad

次のコードのコメントアウト部分を埋めて、動画を再現してください。

public class SnakeHead : MonoBehaviour {
    static int bodyCount = 0;
    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;

        if ( Vector3.Distance( this.transform.position, this.bigBrother.position ) > this.distance )
        {
            if (this.bodyType != BodyType.Head)
            {
                this.transform.position = Vector3.Lerp(this.transform.position, this.bigBrother.position, 0.3f);
            }
            if (bodyCount > maxBodyCount) return;
            if (!this.alreadyMakeBros)
            {
                if (bodyCount != maxBodyCount)
                    this.CreateBody();
                else
                    this.CreateTail();

                bodyCount++;
            }
        }
    }
    void CreateHead()
    {
        var b = GameObject.CreatePrimitive(PrimitiveType.Sphere);
        b.name = "HEAD_";
        b.transform.localScale = Vector3.one * 1.5f;
        var snake = b.AddComponent<SnakeHead>();
        snake.bodyType = BodyType.Head;
        snake.bigBrother = this.transform;
        this.alreadyMakeBros = true;
    }

    void CreateBody()
    {
        /*

        ここを考えてください

        */
    }
    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;
    }

}

答え

問題部分であるCreateBody()は上下のコードのコピペで作成可能です。
コードを読んで、どこで呼ばれるかを把握することを目的としています。

今日はこれ1つでした。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です