(2)-2 -1 自作の関数、作ってみる


(2)-2 同じ文章をまとめてすっきりさせたい

先生に相談したら関数を作るとよい。引数ありでと助言を頂いたのでやってみた結果のまとめ

お題


    void Update()
    {
        if (Input.GetKey(KeyCode.A))
        {
            Quaternion myQuaternion = this.transform.rotation;
            Quaternion rot = Quaternion.AngleAxis(2, Vector3.down);
            this.transform.rotation = myQuaternion * rot;
        }

        if (Input.GetKey(KeyCode.D))
        {
            Quaternion myQuaternion = this.transform.rotation;
            Quaternion rot = Quaternion.AngleAxis(2, Vector3.up);
            this.transform.rotation = myQuaternion * rot;
        }

        if (Input.GetKey(KeyCode.W))
        {
            Quaternion myQuaternion = this.transform.rotation;
            Quaternion rot = Quaternion.AngleAxis(2, Vector3.right);
            this.transform.rotation = myQuaternion * rot;
        }

        if (Input.GetKey(KeyCode.S))
        {
            Quaternion myQuaternion = this.transform.rotation;
            Quaternion rot = Quaternion.AngleAxis(2, Vector3.left);
            this.transform.rotation = myQuaternion * rot;
        }
    }

引数になんて書けばプログラムが通るのかをもんもんとやっていきます。


    void Update()
    {
        //回転2
        Kaiten(A, down);
        Kaiten(D, up);
        Kaiten(W, right);
        Kaiten(S, left);
    }

    void Kaiten(string moji, string angle)
    {
        if (Input.GetKey(moji))
        {
            Quaternion myQuaternion = this.transform.rotation;
            Quaternion rot = Quaternion.AngleAxis(2, Vector3.angle);
            this.transform.rotation = myQuaternion * rot;
        }
    }

👆NG

名前は存在しない、定義がないと。
文字列をダブルクオーテーションで囲ってないから!?


    void Update()
    {
        //回転2
        Kaiten(A, down);
        Kaiten(D, up);
        Kaiten(W, right);
        Kaiten(S, left);
    }

    void Kaiten(string moji, string angle)
    {
        if (Input.GetKey(moji))
        {
            Quaternion myQuaternion = this.transform.rotation;
            Quaternion rot = Quaternion.AngleAxis(2, Vector3.angle);
            this.transform.rotation = myQuaternion * rot;
        }
    }

👆NG

予期しない文字、構文エラー、定義がありませんと。
もう、そのまま入れたらどう?心折れそうやし。


    void Update()
    {
        //回転2
        Kaiten(KeyCode.A, Vector3.down);
        Kaiten(KeyCode.D, Vector3.up);
        Kaiten(KeyCode.W, Vector3.right);
        Kaiten(KeyCode.S, Vector3.left);
    }

    void Kaiten(KeyCode moji, Vector3 angle)
    {
        if (Input.GetKey(moji))
        {
            Quaternion myQuaternion = this.transform.rotation;
            Quaternion rot = Quaternion.AngleAxis(2, angle);
            this.transform.rotation = myQuaternion * rot;
        }
    }

👆まぐれだけど、正解な気がする。

何を覚えたか?

・Vector3は型かもって気がするけど、KeyCode型を発見
・関数の実行部分には、型.変数 て書かないとだめ
・諦めなければいつかは、通してくれる

参考にさせて頂いたサイト

Unityプログラミング基礎 (変数からclassまで)