Unity2Dゲームで斜面を歩いて登るのを簡単に実装していきます。
はじめに
「Unity 2022.3.14f1」バージョン、テンプレートは「2D」を選択しています。
キャラクターを左右に動かし、斜面を登るのを実装していきます。
実装開始
簡単にUIを作成してからスクリプトで実装していきます。
簡単なUI作成
Hierarchyで右クリック、「CreateEmpty」を追加。名前を「GroundGroup」にします。

配下に「2DObject」→「Sprites」→「Square」を2つ追加。名前を「ground1」、「ground2」にして位置とスケールを変更。BoxCollider2Dをアタッチします。

さらに、「2DObject」→「Sprites」→「Square」を追加。名前をPlayerにして位置とスケールを変更。「BoxCollider2D」と「Rigidbody2D」をアタッチします。

下記のような画面になります。白い四角が道、緑色の四角がプレイヤーです。緑色を動かして坂を登らせます

スクリプトの作成
まずはプレイヤーを左右に動かすスクリプト、下記のように作成します。キー操作で左右に動きます。
using UnityEngine; public class PlayerMovement : MonoBehaviour { [SerializeField] float PlayerSpeed = 5.0f; private Rigidbody2D _rb; private float _hori; void Start() { _rb = GetComponent<Rigidbody2D>(); } void Update() { _hori = Input.GetAxis("Horizontal"); } private void FixedUpdate() { _rb.velocity = new Vector2(_hori * PlayerSpeed, _rb.velocity.y); } }
試しに動かしてみると、下記のように斜面で転がってしまいます。

転がらないように、Playerの「Rigidbody2D」のConstraintsのZを固定して回転しないようにします。

固定すると、下記のような動きになります。

BoxCollider2Dだと先っぽで衝突判定するのでコライダーのサイズを変えるか、CapsuleCollider2Dに変更すると良いかも。

また、斜面の角度が急な場合、キー操作をしていないと斜面を滑り落ちます。急斜面でも、その場にとどまりたい場合は、下記のような感じにスクリプトを変更します。
using UnityEngine; public class PlayerMovement : MonoBehaviour { [SerializeField] float PlayerSpeed = 5.0f; private Rigidbody2D _rb; private float _hori; void Start() { _rb = GetComponent<Rigidbody2D>(); } void Update() { _hori = Input.GetAxis("Horizontal"); if (_hori == 0) _rb.constraints = RigidbodyConstraints2D.FreezePositionX | RigidbodyConstraints2D.FreezeRotation; else _rb.constraints = RigidbodyConstraints2D.FreezeRotation; } private void FixedUpdate() { _rb.velocity = new Vector2(_hori * PlayerSpeed, _rb.velocity.y); } }
キー操作をしていないときはX軸を固定してプレイヤーが滑り落ちないようにしています。試しに動かしてみると下記のような感じに。
