Version: 5.6
public static RaycastHit2D Raycast (Vector2 origin, Vector2 direction, float distance= Mathf.Infinity, int layerMask= DefaultRaycastLayers, float minDepth= -Mathf.Infinity, float maxDepth= Mathf.Infinity);

パラメーター

origin 2D 空間上のレイの原点
direction The vector representing the direction of the ray.
distance Ray を投影する最大距離
layerMask 特定のレイヤーのコライダーのみを判別するためのフィルター
minDepth この値以上の Z 座標(深度)を持つオブジェクトのみを含みます。
maxDepth この値以下の Z 座標(深度)を持つオブジェクトのみを含みます。

戻り値

RaycastHit2D 投げかけた結果が返されます。

説明

シーンのコライダーに対してレイを飛ばします

Raycast は例えるならば、空間上のある地点から特定方向へ発射されたセンサーのようなものです。センサーと接触したすべてのオブジェクトは検知され報告されます。

この関数はレイがヒットするコライダーへの参照をもつ RaycastHit オブジェクトを返します。何もヒットしない場合は、結果のコライダープロパティーは null になります。layerMask を使用すると、特定のレイヤーのオブジェクトだけを検出できます(例えば敵キャラクターのみ検出するように設定できます)。

Overloads of this method that use contactFilter can filter the results by the options available in ContactFilter2D.

Raycast は視界の範囲の判定、銃弾によりターゲットの当たり判定、さらに多くのゲームシーンで役に立ちます。

さらにこの関数は線の開始地点のコライダーを検知します。この場合線がコライダーの中で開始していてコライダーの表面と交差していません。つまり返された衝突の法線がテストする線のベクトルの反対にセットされた場合、衝突の法線が計算できません。このような結果は RaycastHit2D の 0 地点で得られるため、これを検知するのは容易です。

関連項目: LayerMask クラス、RaycastHit2D クラス、RaycastAllLinecastDefaultRaycastLayersIgnoreRaycastLayerraycastsHitTriggers.

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour { public float floatHeight; public float liftForce; public float damping; public Rigidbody2D rb2D; void Start() { rb2D = GetComponent<Rigidbody2D>(); } void FixedUpdate() { RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up); if (hit.collider != null) { float distance = Mathf.Abs(hit.point.y - transform.position.y); float heightError = floatHeight - distance; float force = liftForce * heightError - rb2D.velocity.y * damping; rb2D.AddForce(Vector3.up * force); } } }

public static int Raycast (Vector2 origin, Vector2 direction, ContactFilter2D contactFilter, RaycastHit2D[] results, float distance= Mathf.Infinity);

パラメーター

origin 2D 空間上のレイの原点
direction The vector representing the direction of the ray.
contactFilter The contact filter used to filter the results differently, such as by layer mask, Z or depth buffer, or normal angle.
results The array to receive results. The size of the array determines the maximum number of results that can be returned.
distance Ray を投影する最大距離

戻り値

int Returns the number of results placed in the results array.

説明

Casts a ray against colliders in the Scene.

Raycast は例えるならば、空間上のある地点から特定方向へ発射されたセンサーのようなものです。センサーと接触したすべてのオブジェクトは検知され報告されます。

This function returns the number of contacts found and places those contacts in the results array. The results can also be filtered by the contactFilter.

See Also: ContactFilter2D and RaycastHit2D.