Crafty.polygon Class

The constructor for a polygon object used for hitboxes and click maps. Takes a set of points as an argument, giving alternately the x and y coordinates of the polygon's vertices in order.

For a polygon of n edges exactly n vertex coordinate pairs should be passed to the constructor. It is advised to pass the vertices in a clockwise order.

The constructor accepts the coordinates as either a single array or as a set of individual arguments. If passed an array, the current implementation will use that array internally -- do not attempt to reuse it.

When creating a polygon for an entity, each point should be offset or relative from the entities x and y (don't include the absolute values as it will automatically calculate this).

Example

Two ways to create a triangle with vertices at (50, 0), (100, 100) and (0, 100).

new Crafty.polygon([50, 0, 100, 100, 0, 100]);
new Crafty.polygon(50, 0, 100, 100, 0, 100);

Methods

Back to top

.clone()

public void .clone()

Returns a clone of the polygon.

Example

var poly = new Crafty.polygon([50, 0, 100, 100, 0, 100]);
var shiftedpoly = poly.clone().shift(5,5);
//[55, 5, 105, 5, 5, 105], but the original polygon is unchanged
Back to top

.containsPoint()

public Boolean .containsPoint(Number x, Number y)
x

X position of the point

y

Y position of the point

Method is used to determine if a given point is contained by the polygon.

Example

var poly = new Crafty.polygon([50, 0, 100, 100, 0, 100]);
poly.containsPoint(50, 50); //TRUE
poly.containsPoint(0, 0); //FALSE
Back to top

.intersectRay()

public Number .intersectRay(Object origin, Object direction)
origin

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

direction

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

[Returns]

a Number indicating the distance from the ray's origin to the closest intersection point of the polygon. Returns Infinity if there is no intersection.

Find the distance to the closest intersection point of the supplied ray with any of this polygon's segments.

Example

var poly = new Crafty.polygon([0,0, 50,0, 50,50, 0,50]);

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

var distance = poly.intersectRay(origin, direction);
Crafty.log('Distance from origin to closest intersection point', distance); // logs '1'
Back to top

.shift()

public void .shift(Number x, Number y)
x

Amount to shift the x axis

y

Amount to shift the y axis

Shifts every single point in the polygon by the specified amount.

Example

var poly = new Crafty.polygon([50, 0, 100, 100, 0, 100]);
poly.shift(5,5);
//[[55, 5, 105, 5, 5, 105];