object:rayCast()

Type Function
Object ParticleSystem
Library physics.*
Return value Array
Revision Release 2024.3703
Keywords rayCast, physics, LiquidFun
See also physics.newParticleSystem()
object:queryRegion()

Overview

This function is used to find the particles that collide with a line. It returns an array of tables describing each hit.

Gotchas

If the starting position is inside a particle, no hit will be registered for that particle.

Syntax

ParticleSystem:rayCast( from_x, from_y, to_x, to_y, behavior )
from_x (required)

Number. The starting x position of the ray.

from_y (required)

Number. The starting y position of the ray.

to_x (required)

Number. The ending x position of the ray.

to_y (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:

Example

local hits = ParticleSystem: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, " Position: ", v.x, v.y, " Surface normal: ", v.normal.x, v.normal.y )
    end

    print( "The first particle hit 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