Unityで2点間に壁があるかの判定


概要

2つのGameObjectの間に壁があるかを判定する処理のメモ
Raycastを使用する場合は、方向ベクトルを求める必要がある

スクリプト

RayTest.cs

using UnityEngine;
using System.Collections;

public class RayTest : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

        // ターゲットのオブジェクトを検索
        GameObject TragetObject = GameObject.Find ("Target");
        if (TragetObject) {
            RaycastHit hit;

            // ターゲットオブジェクトとの差分を求め
            Vector3 temp =  TragetObject.transform.position - this.transform.position;
            // 正規化して方向ベクトルを求める
            Vector3 normal = temp.normalized;

            if (Physics.Raycast (this.transform.position, normal, out hit, 10)) {

                if (hit.transform.gameObject == TragetObject) {
                    // TargetObjectを見つけた
                    print ("Found TargetObject");
                } else {
                    // TargetObject以外を見つけた
                    print ("Hit Wall");
                }
            }
        }
    }
}

プロジェクトのスクリーンショット