| origin | 2D 空間上の レイの 原点 |
| direction | レイの方向を示すベクトル |
| distance | Raycast を行う最大距離 |
| layerMask | 特定のレイヤーのコライダのみを判別するためのフィルター |
| minDepth | この値よりも大きなZ座標(深度)にあるオブジェクトのみを含みます。 |
| maxDepth | この値よりも小さなZ座標(深度)にあるオブジェクトのみを含みます。 |
RaycastHit2D 投げかけた結果が返されます。
シーンのコライダーに対してレイを飛ばします
Raycast は例えるならば、空間上のある地点から特定方向へ発射されたセンサーのようなものです。センサーと接触した全てのオブジェクトは検知され報告されます。 この関数はコライダーが Raycast によりヒットされた場合 RaycastHit オブジェクトを返し、何もヒットしない場合は null を返します。layerMask を使用することで特定レイヤーのオブジェクトのみ判定できます(例えば敵キャラのみヒットを判定できます)。 Raycast は視界の範囲の判定、銃弾によりターゲットの当たり判定、さらに多くのゲームシーンで役に立ちます。 さらにこの関数は線の開始地点のコライダーを検知します。この場合線がコライダーの中で開始していてコライダーの表面と交差していません。つまり返された衝突の法線がテストする線のベクトルの反対にセットされた場合、衝突の法線が計算できません。このような結果は RaycastHit2D のゼロ地点で得られるため、これを検知するのは容易です。 See Also: LayerMask クラス, RaycastHit2D クラス, RaycastAll, Linecast, DefaultRaycastLayers, IgnoreRaycastLayer, raycastsHitTriggers.
// Float a rigidbody object a set distance above a surface.
var floatHeight: float; // Desired floating height.
var liftForce: float; // Force to apply when lifting the rigidbody.
var damping: float; // Force reduction proportional to speed (reduces bouncing).
function FixedUpdate() {
// Cast a ray straight down.
var hit: RaycastHit2D = Physics2D.Raycast(transform.position, -Vector2.up);
// If it hits something...
if (hit.collider != null) {
// Calculate the distance from the surface and the "error" relative
// to the floating height.
var distance = Mathf.Abs(hit.point.y - transform.position.y);
var heightError: float = floatHeight - distance;
// The force is proportional to the height error, but we remove a part of it
// according to the object's speed.
var force = liftForce * heightError - rigidbody2D.velocity.y * damping;
// Apply the force to the rigidbody.
rigidbody2D.AddForce(Vector3.up * force);
}
}
using UnityEngine; using System.Collections; public class ExampleClass : MonoBehaviour { public float floatHeight; public float liftForce; public float damping; 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 - rigidbody2D.velocity.y * damping; rigidbody2D.AddForce(Vector3.up * force); } } }
import UnityEngine import System.Collections public class ExampleClass(MonoBehaviour): public floatHeight as float public liftForce as float public damping as float def FixedUpdate() as void: hit as RaycastHit2D = Physics2D.Raycast(transform.position, -Vector2.up) if hit.collider != null: distance as float = Mathf.Abs((hit.point.y - transform.position.y)) heightError as float = (floatHeight - distance) force as float = ((liftForce * heightError) - (rigidbody2D.velocity.y * damping)) rigidbody2D.AddForce((Vector3.up * force))