LoginSignup
2
2

More than 3 years have passed since last update.

rotationでオブジェクトがランダムに傾く方法

Last updated at Posted at 2020-03-26

勝手に倒れるオブジェクト

rotationを利用して、オブジェクトがランダムに傾くのをキーで操作する方法を紹介します。

dqz4d-ebqdc.gif

z軸を使って回転します。

UnityではQuaternionで回転数を決めているので、先に宣言。
new Vector3のzの値にRandom.Rangeを使って1-4までの乱数を返します。
これにより、ランダムで傾きます。

    void Update()
    {

        Quaternion quaternion = this.transform.rotation;
        float rot_z = quaternion.eulerAngles.z;


        transform.Rotate(new Vector3(0, 0, Random.Range(1,4)));
   }

キーで傾きを制限

この傾きをキーを使って戻したり、するためには下記のコードを追加。
zの値は乱数の最大値よりも大きな値を設定します。

     void Update()
    {


        Quaternion quaternion = this.transform.rotation;
        float rot_z = quaternion.eulerAngles.z;


        transform.Rotate(new Vector3(0, 0, Random.Range(1,4)));


        if (Input.GetKey(KeyCode.RightArrow))
        {

            transform.Rotate(new Vector3(0, 0, -6));

        }

        if (Input.GetKey(KeyCode.LeftArrow))
        {

            transform.Rotate(new Vector3(0, 0, 6));

        }

    }

下重心にする

しかし、上記のスクリプトをただオブジェクトにアタッチした場合、こうなります。
movie1.gif

なので、今回は重心を下にしてplaneにCapsulの面が触れながら傾きたかったので、
空のGameObjectを作成します。
そしてpositionを重心を置きたい位置に合わせます。
今回はここ。
スクリーンショット 2020-03-26 19.01.26.png
そして、

空のGameObjectを親にして、Capsuleを子にします。

スクリプトをアタッチするのは空のGameObjectの方です。
スクリーンショット 2020-03-26 18.56.12.png

すると、このように傾きます。
人間を傾ける時なんかは足がついていないといけないので、この方法が利用できるかなと思います。
dqz4d-ebqdc.gif

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2