public Array .raycast(Object origin, Object direction[, Number maxDistance][, String comp][, Boolean sort])

the point of origin from which the ray will be cast. The object must contain the properties _x and _y.


the direction the ray will be cast. It must be normalized. The object must contain the properties x and y.


the maximum distance up to which intersections will be found. This is an optional parameter defaulting to Infinity. If it's Infinity find all intersections. If it's negative find only first intersection (if there is one). If it's positive find all intersections up to that distance.


check for intersection with entities that have this component applied to them. This is an optional parameter that is disabled by default.


whether to sort the returned array by increasing distance. May be disabled to slightly improve performance if sorted results are not needed. Defaults to true.


an array of raycast-results that may be empty, if no intersection has been found. Otherwise, each raycast-result looks like {obj: Entity, distance: Number, x: Number, y: Number}, describing which obj entity has intersected the ray at intersection point x,y, distance px away from origin.

Cast a ray from its origin in the direction and report entities that intersect with it, given the parameter constraints.

Raycasting only reports entities, that have the Collision component applied to them.


Crafty.e("2D, Collision")
      .setName('First entity')
      .attr({x: 0, y: 0, w: 10, h: 10});

Crafty.e("2D, Collision")
      .setName('Second entity')
      .attr({x: 20, y: 20, w: 10, h: 10});

var origin = {_x: -25, _y: -25};
var direction = new Crafty.math.Vector2D(1, 1).normalize();

var results = Crafty.raycast(origin, direction, -1); // find only 1st intersection
Crafty.log('Intersections found', results.length); // logs '1'

var result = results[0];
Crafty.log('1st intersection:');
Crafty.log('Entity name:', result.obj.getName()); // logs 'First entity'
Crafty.log('Distance from origin to intersection point', result.distance); // logs '25 * Math.sqrt(2)'
Crafty.log('Intersection point:', result.x, result.y); // logs '0' '0'