(Unity・LEGOワールドで遊ぶ)回転棒の作成(回転速度を3段階で切り替える)

(オブジェクトの作成)

  • 2つのCylinderを使って下記のようなオブジェクトを作成
  • 名前は「Base」と「Rod」
  • 大きさ、デザイン等は自由

  • RodをBaseの子供に設定する(親子関係)


(回転のスクリプト)

  • 新規にC#スクリプトを作成
  • 名前を「Rod」に変更
  • 下記のコードを書いてチェック
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Rod : MonoBehaviour
{
    private int speed;

    void Start()
    {
        StartCoroutine(RotateManager());
    }

    void Update()
    {
        transform.Rotate(new Vector3(0, 90, 0) * Time.deltaTime * speed);
    }

    private IEnumerator RotateManager()
    {
        while (true)
        {
            speed = 1;
            yield return new WaitForSeconds(5f);
            // 速度2倍
            speed = 2;
            yield return new WaitForSeconds(5f);
            // 逆回転
            speed = -2;
            yield return new WaitForSeconds(5f);
        }
    }
}

(設定)

  • このスクリプトは親である「Base」オブジェクトに追加


(実行結果)

  • 設定が完了したらゲーム再生
  • 3段階で回転速度が変化すれば成功です。


(ゲームオーバー)

  • ここではロッド部分に触れた場合に「ゲームオーバー」になるようにします。
  • 新規にC#スクリプトを作成
  • 名前を「TouchRod」に変更
  • 下記のコードを書いてチェック
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// 追加
using UnityEngine.SceneManagement;

public class TouchRod : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        if(other.CompareTag("Rod"))
        {
            SceneManager.LoadScene("Menu Lose");
        }
    }
}

(設定)

  • このスクリプトはプレーヤーに追加しましょう。

  • Rodオブジェクトに「Rod」のTagを追加しましょう。


(実行結果)

  • 設定が完了したらゲーム再生
  • プレーヤがRod部分に触れた瞬間にゲームオーバーになれば成功です。