2D壁登り(アクション向け)
今回は上記の動画のように前方に壁がある時によじ登る挙動を実装しました。
これに少し手を加えると 崖掴み > よじ登り ができます。
コーディング
Rayは自機頭上と自機正面から飛ばしています。
これで正面に壁がある時に登る事ができるようになります。
using UnityEngine;
public class GrabCliff : MonoBehaviour
{
public float climbSpeed = 5f; // 駆け上り速度
public LayerMask whatIsLedge; // 指定レイヤー(inspectorから指定)
private bool isClimbing = false;
private Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
// Climbは Edit > Project Settings > Input Manager から設定
if (IsNearLedge() && Input.GetButtonDown("Climb"))
{
isClimbing = true;
Debug.Log("Climbing");
}
if (isClimbing)
{
// 上昇処理
rb.velocity = new Vector2(rb.velocity.x, climbSpeed);
// 登りきったら駆け上り終了判定
if (IsOverLedge())
{
isClimbing = false;
}
}
}
private bool IsNearLedge()
{
Vector2 direction = transform.localScale.x > 0 ? Vector2.right : Vector2.left; // キャラクターの向きに応じてRaycastの方向を決定
Vector2 origin = transform.position + Vector3.up; // Raycastの起点を自機の位置から上にずらす
RaycastHit2D hit = Physics2D.Raycast(origin, direction, 1f, whatIsLedge);
Debug.DrawRay(origin, direction * 1f, Color.red); // Rayを赤色で描画
return hit.collider != null; // Rayが何かに当たったらtrueを返す
}
private bool IsOverLedge()
{
Vector2 direction = transform.localScale.x > 0 ? Vector2.right : Vector2.left;
RaycastHit2D hit = Physics2D.Raycast(transform.position, direction, 1f, whatIsLedge);
Debug.DrawRay(transform.position, direction * 1f, Color.blue); // Rayを青色で描画
return hit.collider == null; // Rayが何も当たらなかったらtrueを返す
}
}
この記事が気に入ったらサポートをしてみませんか?