パパコーダー

子どもと一緒にプログラミングを始めよう!2019年3月からCoderDojo溝口という子ども向けのプログラミングサークルを始めました。神奈川県川崎市の近くにお住まいの方はどうぞ遊びに来てください。

【Unity】C# Survival Guide - Rotations のプログラミングを楽しんでみました

3ヶ月間無料で提供されている Unity Learn Premium でプログラミングを楽しみましょう。

ゲームオブジェクトを回転させるクオータニオンを使ってみます。

C# Survival Guide - Rotations

Unity Learn Premium コース

こちらのコースからクオータニオンを学んでみましょう。

learn.unity.com

Unity プロジェクトを作って遊んでみよう

f:id:oco777:20200409182255j:plain
クオータニオンで遊びましょう

MyRotate.cs

"Player"タグをつけたゲームオブジェクトに、MyRotateコンポーネントを付けましょう。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MyRotate : MonoBehaviour
{
    [SerializeField]
    private Transform _startPos;
    [SerializeField]
    private Transform _endPos;
    private float _slerpT;

    private void Start()
    {
        _slerpT = 0;
    }

    // Update is called once per frame
    void Update()
    {
        if (_slerpT < 1)
        {
            _slerpT += Time.deltaTime;
            if (_slerpT > 1)
            {
                _slerpT = 1;
            }
            // 最初に向く方向.
            Vector3 startDirection = _startPos.position - transform.position;
            Quaternion startRotation = Quaternion.LookRotation(startDirection);
            // 最後に向く方向.
            Vector3 endDirection = _endPos.position - transform.position;
            Quaternion endRotation = Quaternion.LookRotation(endDirection);
            // 現在の向きの更新.
            transform.rotation = Quaternion.Slerp(startRotation, endRotation, _slerpT);
        }
    }

    public void SwitchDirection()
    {
        Transform tmp = _startPos;
        _startPos = _endPos;
        _endPos = tmp;
        _slerpT = 0;
    }
}
GameController.cs

スペースキーを押したら、"Player"コンポーネントの SwitchDirectionメソッドを呼びます。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameController : MonoBehaviour
{
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
            for (int i=0; i < players.Length; i++)
            {
                players[i].GetComponent<MyRotate>().SwitchDirection();
            }
        }
    }
}

まとめ

スペースキーを押すと、キャラクターの向きを変えるプログラミングを作ってみました。 オブジェクトを回転させるときに使うクオータニオンは難しそうに感じますが、使いやすいメソッドが用意されているので、どんどん使って慣れていきましょう。