Unity2Dゲームでエレベーターのようなものを作成してみます。
はじめに
Unityのバージョンは「2021.3.14f1」で作成しています。
2Dゲームで「エレベーター」のような動きを実装していきます。特定の台の上でキー操作すると台が上昇・下降します。
実装開始
横に移動するプレイヤーを作成した後、エレベーター機能を追加していきます。
プレイヤーと地面の作成
「2DObject」→「Sprites」→「Square」を2つ追加します。

一つはGroundに名前を変更して、AddComponentから「BoxCollider2D」を追加します。Scaleも変更しておきます。

もう一つはPlayerに名前を変更して、AddComponentから「BoxCollider2D」と「Rigidbody2D」を追加します。Rigidbody2DはGravityScale(重力)を変更、FreezeRotationにチェックを入れます。

プレイヤーを横移動させるスクリプト
下記スクリプトを作成して、Playerオブジェクトに追加します。
using UnityEngine; public class PlayerMove : MonoBehaviour { private float speed = 5.0f; private Rigidbody2D rb; private float inputX; void Start() { rb = GetComponent<Rigidbody2D>(); } void Update() { inputX = Input.GetAxisRaw("Horizontal"); } void FixedUpdate() { rb.velocity = new Vector2(inputX * speed, rb.velocity.y); } }

キーボードの「←」、「→」を押すと左右に動きます。

エレベーターの作成
次に簡単なエレベーターを作成していきます。
「CreateEmpty」で空オブジェクトを追加して、名前を「elevator」に変更。Positionを変更しておきます。

配下に「2DObject」→「Sprites」→「Square」を2つ追加します。一つは名前を「yoko」にして、BoxCollider2Dを追加、Scaleと色を変更しておきます。エレベーターの床部分になります。

もう一つは「tate」にして、同じようにBoxCollider2Dを追加して、色とスケールを変更しておきます。

さらに配下に「CreateEmpty」で空オブジェクトを追加します。名前を「1F」としておきます。

「1F」をコピーして、「2F」、「3F」とします。それぞれPositionのYを変更しておきます。(エレベータの移動先の位置になります)

ゲーム画面は下記のような形になります。緑色の床部分に乗ってキーボードを入力をしたときに上昇、下降するようにしていきます。

エレベーターのスクリプト
下記スクリプトを作成して、elevatorオブジェクトに追加します。
using UnityEngine; public class elevator : MonoBehaviour { [SerializeField] private Transform player; [SerializeField] private Transform elevatorFloor; [SerializeField] private Transform[] elevatorPos; private int nowfloor; private float speed = 5.0f; private bool iselevator; private void Start() { nowfloor = 0; iselevator = false; } private void Update() { if (Vector2.Distance(player.position, elevatorFloor.position) < 1.0f) { if (Input.GetKeyDown(KeyCode.UpArrow) && nowfloor < elevatorPos.Length - 1) { nowfloor++; iselevator = true; } if (Input.GetKeyDown(KeyCode.DownArrow) && nowfloor > 0) { nowfloor--; iselevator = true; } } if (iselevator) { elevatorFloor.position = Vector2.MoveTowards(elevatorFloor.position, elevatorPos[nowfloor].position, speed * Time.deltaTime); if (elevatorFloor.position.y == elevatorPos[nowfloor].position.y) { iselevator = false; } } } }
キーボードの↑を押した時に上昇、↓を押した時に下降します。また、プレイヤーがエレベーターに乗っているか、上の階があるか、下の階があるかもチェックしています。
elevatorオブジェクトにスクリプトを追加して、各パラメータをセットします。今回は3Fまであるので3Fまでセットします。

実行して、「↑」、「↓」を押すと上昇・下降します。

弾む動きを修正する
エレベーターが動いている時、プレイヤーが弾むような動きをするので修正していきます。
下記スクリプトを作成します。プレイヤーがエレベーターの床に触れた時、プレイヤーオブジェクトをエレベーターの配下に移動しています。
using UnityEngine; public class elevatorFloor : MonoBehaviour { private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.tag == "Player") collision.gameObject.transform.parent = this.transform; } private void OnCollisionExit2D(Collision2D collision) { if (collision.gameObject.tag == "Player") collision.gameObject.transform.parent = null; } }
スクリプトをエレベーターの床に追加します。

Playerにタグを設定します。

実行すると下記のような動きになります。床とプレイヤーがくっついて移動するので弾まなくなります。
