Skip to content

Instantly share code, notes, and snippets.

@smallrice45
Created April 26, 2014 14:41
Show Gist options
  • Save smallrice45/11321862 to your computer and use it in GitHub Desktop.
Save smallrice45/11321862 to your computer and use it in GitHub Desktop.
Unity 向前方打出射線判斷是否為牆壁,並計算中心點。
using UnityEngine;
using System.Collections;
public class PlaneRayCast : MonoBehaviour {
// 射線長度
public float rayLength = 100;
// 射線擊中資訊
RaycastHit hit;
// 設定設線偵測圖層
public LayerMask wallLayer;
void Update() {
Vector3 fwd = transform.TransformDirection(Vector3.forward);
RaycastHit hit;
// 偵測射線判斷,由 自身座標 的 前方 射出,以 rayLength 為長度,並且只偵測 wallLayer 圖層
if (Physics.Raycast(transform.position, fwd, out hit, rayLength, wallLayer))
{
// 繪出起點至射線擊中的綠色線段
Debug.DrawLine( transform.position, hit.point, Color.green, 0.01f, false);
// 計算兩點之間中心點
Vector3 centerPoint = (transform.position + hit.point) / 2;
// 繪出起點至中心點的紅色線段
Debug.DrawLine( transform.position, centerPoint, Color.red, 0.01f, false);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment