sprite.setCollider()

Category:Sprites

Sets the collider for a sprite.

A collider is an invisible circle or rectangle that can have any size or position relative to the sprite and which will be used to detect collisions and overlapping with other sprites, or the mouse cursor.

If the sprite is checked for collision, bounce, overlapping or mouse events a rectangle collider is automatically created from the width and height parameter passed at the creation of the sprite or the from the image dimension in case of animated sprites.

Often the image default rectangle collider is not appropriate for collision detection so you can set a smaller circular or rectangular collider and offset from the sprite's center.

Examples

var sprite = createSprite(200, 200);
sprite.setAnimation("carrot_1");
sprite.scale = 4;
sprite.setCollider("rectangle", 0, 0, 20, 80, -45);
sprite.debug = true;
drawSprites();

Syntax

setCollider(type, xOffset, yOffset, width/radius, height, rotationOffset)

Parameters

NameTypeRequired?Description
type String The shape of the collider, "rectangle" or "circle".
xOffset Number The offset in the x-direction from the center of the sprite to the center of the collider. The default is 0.
yOffset Number The offset in the y-direction from the center of the sprite to the center of the collider. The default is 0.
width/radius Number The width of a rectangle collider or the radius of a circle collider. The default is determined by the size of the sprite.
height Number The height of a rectangle collider or the radius of a circle collider. The default is determined by the size of the sprite.
rotationOffset Number The clockwise rotation in degrees of the collider with respect to the sprite. The default is 0.

Returns

No return value. Determines sprite collisions and sprite-mouse interactions.

Tips

  • When your games have complex interactions between sprites or the mouse set sprite.debug to true so the sprite is shown with the outline of the collider, the depth, and center.
  • If setCollider() is called for a sprite before it is scaled, the collider is not scaled. But if a sprite is first scaled and then the collider set, the scale is also applied to the collider.

Found a bug in the documentation? Let us know at documentation@code.org