# physics.rayCast()

 Type Function Library physics.* Return value Array of tables describing each hit Revision Release 2024.3703 Keywords ray, raycast, casting, physics, collision See also physics.reflectRay()

## Overview

This function is used to find the objects that collide with a line, and the collision points along that line.

The positions returned are in content space while the normals returned are in local space.

## Gotchas

If the starting position is inside an object, no hit will be registered for that object.

## Syntax

physics.rayCast( fromX, fromY, toX, toY, behavior )
##### fromX (required)

Number. The starting x position of the ray.

##### fromY (required)

Number. The starting y position of the ray.

##### toX (required)

Number. The ending x position of the ray.

##### toY (required)

Number. The ending y position of the ray.

##### behavior (optional)

String. The collision test behavior, in increasing order of performance cost:

• "any" — Return one result, but not necessarily the closest one.
• "closest" — Return only the closest hit from the starting point, if any. This is the default behavior.
• "unsorted" — Return all results in no particular order.
• "sorted" — Return all results, sorted from closest to farthest.

## Result Properties

hits will be an array of elements containing these properties:

• object — The DisplayObject colliding with the line.
• position.x — The x collision position of object, in content space.
• position.y — The y collision position of object, in content space.
• normal.x — The x component of the normal of the surface hit in local space.
• normal.y — The y component of the normal of the surface hit in local space.
• fraction — The fraction (0..1) along the ray where the hit is located. 0 is the start point of the ray cast and 1 is the end point.

## Example

local hits = physics.rayCast( 0, 0, 200, 300, "closest" )

if ( hits ) then

-- There's at least one hit
print( "Hit count: " .. tostring( #hits ) )

-- Output the results
for i,v in ipairs( hits ) do
print( "Hit: ", i, v.object, " Position: ", v.position.x, v.position.y, " Surface normal: ", v.normal.x, v.normal.y )
end

print( "The first object hit is: ", hits[1].object, " at position: ", hits[1].position.x, hits[1].position.y, " where the surface normal is: ", hits[1].normal.x, hits[1].normal.y, " and where the fraction along the ray is: ", hits[1].fraction )
else
-- No hits on raycast
end