Legacy Documentation: Version 4.5.0

Script language:

  • JS
  • C#
  • Boo
Script language

Select your preferred scripting language. All code snippets will be displayed in this language.

Physics2D.Raycast

static function Raycast(origin: Vector2, direction: Vector2, distance: float = Mathf.Infinity, layerMask: int = DefaultRaycastLayers, minDepth: float = -Mathf.Infinity, maxDepth: float = Mathf.Infinity): RaycastHit2D;
static RaycastHit2D Raycast(Vector2 origin, Vector2 direction, float distance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, float minDepth = -Mathf.Infinity, float maxDepth = Mathf.Infinity);
static def Raycast(origin as Vector2, direction as Vector2, distance as float = Mathf.Infinity, layerMask as int = DefaultRaycastLayers, minDepth as float = -Mathf.Infinity, maxDepth as float = Mathf.Infinity) as RaycastHit2D

Parameters

originThe point in 2D space where the ray originates.
directionVector representing the direction of the ray.
distanceMaximum distance over which to cast the ray.
layerMaskFilter to detect Colliders only on certain layers.
minDepthOnly include objects with a Z coordinate (depth) greater than this value.
maxDepthOnly include objects with a Z coordinate (depth) less than this value.

Returns

RaycastHit2D The cast results returned.

Description

Casts a ray against colliders in the scene.

A raycast is conceptually like a laser beam that is fired from a point in space along a particular direction. Any object making contact with the beam can be detected and reported.

This function returns a RaycastHit object with a reference to the collider that is hit by the ray (the collider property of the result will be NULL if nothing was hit). The layerMask can be used to detect objects selectively only on certain layers (this allows you to apply the detection only to enemy characters, for example).

Raycasts are useful for determining lines of sight, targets hit by gunfire and for many other purposes in gameplay.

Additionally, this will also detect Collider(s) at the start of the ray. In this case the ray is starting inside the Collider and doesn't intersect the Collider surface. This means that the collision normal cannot be calculated in which case the collision normal returned is set to the inverse of the ray vector being tested. This can easily be detected because such results are always at a RaycastHit2D fraction of zero.

See Also: LayerMask class, RaycastHit2D class, 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))