Quantcast
Viewing all articles
Browse latest Browse all 10

[Unity] Physics.Raycastを使用してオブジェクトが接地しているか判定する

Physics.Raycastを使用して、球(Ball)が地面(Ground)に接地しているかを判定してみます。

※球にはSphereColliderがアタッチされているものとします。

[C#]
using UnityEngine;
using System.Collections;

public class Ball : MonoBehaviour {

    SphereCollider ballCollider;
    GameObject ground;
            
    void Awake() {
        // Ballオブジェクトのコライダを取得
        this.ballCollider = GetComponent<SphereCollider>();
        // Groundオブジェクトを取得
        this.ground = GameObject.Find("Ground");
    }

    void Update() {
        print(IsGrounded());
    }

  /*
   * 地面と接地しているか
   */
    bool IsGrounded() {
       // 鉛直下向きにGroundオブジェクトが存在するかどうかを判定
       return Physics.Raycast(transform.position, new Vector3(0, -1, 0), this.ballCollider.radius);
   }
}

Updateメソッドで監視すると、
接地している場合はIsGroundedメソッドからTrueが返却されているはずです。

Viewing all articles
Browse latest Browse all 10