Sprite
A Sprite is the main building block of p5.play: an element able to store images or animations with a set of properties such as position and visibility. A Sprite can have a collider that defines the active area to detect collisions or overlappings with other sprites and mouse interactions.
To create a Sprite, use createSprite.
Table of Contents
-
Methods
- _collideWith(typetargetcallback)
- _collideWithOne(typeothercallback)
- addAnimation(labelanimation)
- addImage(labelimg)
- addSpeed(speedangle)
- addToGroup(group)
- attractionPoint(magnitudepointXpointY)
- bounce(targetcallback)
- bounceOff(targetcallback)
- changeAnimation(label)
- changeImage(label)
- collide(targetcallback)
- destroy()
- displace(targetcallback)
- display()
- draw()
- frameDidChange()
- getAnimationLabel()
- getDirection()
- getScaledHeight()
- getScaledWidth()
- getSpeed()
- isTouching(target)
- limitSpeed(max)
- mirrorX(dir)
- mirrorY(dir)
- mouseUpdate()
- nextFrame()
- overlap(targetcallback)
- overlapPixel(pointXpointY)
- overlapPoint(pointXpointY)
- pause()
- play()
- previousFrame()
- remove()
- setAnimation(label)
- setCollider(typeoffsetXoffsetYwidthheightrotation)
- setDefaultCollider()
- setFrame(xy)
- setFrame(frame)
- setSpeed(speedangle)
- setSpeedAndDirection(speedangle)
- setVelocity(xy)
- update()
-
Properties
- _rotation
- animation
- bounciness
- collider
- debug
- depth
- frameDelay
- friction
- groups
- height
- immovable
- life
- lifetime
- mass
- maxSpeed
- mouseActive
- mouseIsOver
- mouseIsPressed
- originalHeight
- originalWidth
- position
- previousPosition
- removed
- restitution
- rotateToDirection
- rotation
- rotationSpeed
- scale
- shapeColor
- touching
- velocity
- velocityX
- visible
- width
- x
- y
- y
Methods
_collideWith
-
type
-
target
-
callback
Internal collision detection function. Do not use directly.
Handles collision with individual sprites or with groups, using the quadtree to optimize the latter.
Parameters:
Returns:
true if a collision occurred
_collideWithOne
-
type
-
other
-
callback
Helper collision method for colliding this sprite with one other sprite.
Has the side effect of setting this.touching properties to TRUE if collisions occur.
Parameters:
-
type
String- 'overlap', 'isTouching', 'displace', 'collide', 'bounce' or 'bounceOff'
-
other
Sprite -
callback
Function- if collision occurred (ignored for 'isTouching')
Returns:
true if a collision occurred
addAnimation
-
label
-
animation
Adds an animation to the sprite. The animation should be preloaded in the preload() function using loadAnimation. Animations require a identifying label (string) to change them. Animations are stored in the sprite but not necessarily displayed until Sprite.changeAnimation(label) is called.
Usage:
- sprite.addAnimation(label, animation);
Alternative usages. See Animation for more information on file sequences:
- sprite.addAnimation(label, firstFrame, lastFrame);
- sprite.addAnimation(label, frame1, frame2, frame3...);
Parameters:
-
label
StringAnimation identifier
-
animation
AnimationThe preloaded animation
addImage
-
label
-
img
Adds an image to the sprite. An image will be considered a one-frame animation. The image should be preloaded in the preload() function using p5 loadImage. Animations require a identifying label (string) to change them. The image is stored in the sprite but not necessarily displayed until Sprite.changeAnimation(label) is called
Usages:
- sprite.addImage(label, image);
- sprite.addImage(image);
If only an image is passed no label is specified
Parameters:
-
label
String | p5.ImageLabel or image
-
[img]
p5.Image optionalImage
addSpeed
-
speed
-
angle
Pushes the sprite in a direction defined by an angle. The force is added to the current velocity.
Parameters:
-
speed
NumberScalar speed to add
-
angle
NumberDirection in degrees
addToGroup
-
group
Adds the sprite to an existing group
Parameters:
-
group
Object
attractionPoint
-
magnitude
-
pointX
-
pointY
Pushes the sprite toward a point. The force is added to the current velocity.
Parameters:
-
magnitude
NumberScalar speed to add
-
pointX
NumberDirection x coordinate
-
pointY
NumberDirection y coordinate
bounce
-
target
-
callback
Checks if the the sprite is overlapping another sprite or a group. If the overlap is positive the sprites will bounce affecting each other's trajectories depending on their .velocity, .mass and .restitution
The check is performed using the colliders. If colliders are not set they will be created automatically from the image/animation bounding box.
A callback function can be specified to perform additional operations when the collision occours. If the target is a group the function will be called for each single sprite colliding. The parameter of the function are respectively the current sprite and the colliding sprite.
Parameters:
-
target
ObjectSprite or group to check against the current one
-
[callback]
Function optionalThe function to be called if overlap is positive
Returns:
True if overlapping
Example:
sprite.bounce(otherSprite, explosion);
function explosion(spriteA, spriteB) {
spriteA.remove();
spriteB.score++;
}
bounceOff
-
target
-
callback
Checks if the the sprite is overlapping another sprite or a group. If the overlap is positive the sprite will bounce with the target(s) treated as immovable.
The check is performed using the colliders. If colliders are not set they will be created automatically from the image/animation bounding box.
A callback function can be specified to perform additional operations when the collision occours. If the target is a group the function will be called for each single sprite colliding. The parameter of the function are respectively the current sprite and the colliding sprite.
Parameters:
-
target
ObjectSprite or group to check against the current one
-
[callback]
Function optionalThe function to be called if overlap is positive
Returns:
True if overlapping
Example:
sprite.bounceOff(otherSprite, explosion);
function explosion(spriteA, spriteB) {
spriteA.remove();
spriteB.score++;
}
changeAnimation
-
label
Changes the displayed animation. See Animation for more control over the sequence.
Parameters:
-
label
StringAnimation identifier
changeImage
-
label
Changes the displayed image/animation. Equivalent to changeAnimation
Parameters:
-
label
StringImage/Animation identifier
collide
-
target
-
callback
Checks if the the sprite is overlapping another sprite or a group. If the overlap is positive the sprite will bounce with the target(s) treated as immovable with a restitution coefficient of zero.
The check is performed using the colliders. If colliders are not set they will be created automatically from the image/animation bounding box.
A callback function can be specified to perform additional operations when the collision occours. If the target is a group the function will be called for each single sprite colliding. The parameter of the function are respectively the current sprite and the colliding sprite.
Parameters:
-
target
ObjectSprite or group to check against the current one
-
[callback]
Function optionalThe function to be called if overlap is positive
Returns:
True if overlapping
Example:
sprite.collide(otherSprite, explosion);
function explosion(spriteA, spriteB) {
spriteA.remove();
spriteB.score++;
}
destroy
()
Alias for remove()
displace
-
target
-
callback
Checks if the the sprite is overlapping another sprite or a group. If the overlap is positive the current sprite will displace the colliding one to the closest non-overlapping position.
The check is performed using the colliders. If colliders are not set they will be created automatically from the image/animation bounding box.
A callback function can be specified to perform additional operations when the collision occours. If the target is a group the function will be called for each single sprite colliding. The parameter of the function are respectively the current sprite and the colliding sprite.
Parameters:
-
target
ObjectSprite or group to check against the current one
-
[callback]
Function optionalThe function to be called if overlap is positive
Returns:
True if overlapping
Example:
sprite.displace(otherSprite, explosion);
function explosion(spriteA, spriteB) {
spriteA.remove();
spriteB.score++;
}
display
()
Manages the positioning, scale and rotation of the sprite Called automatically, it should not be overridden
draw
()
Manages the visuals of the sprite. It can be overridden with a custom drawing function. The 0,0 point will be the center of the sprite. Example: sprite.draw = function() { ellipse(0,0,10,10) } Will display the sprite as circle.
frameDidChange
()
Boolean
Wrapper to access animation.frameChanged
Returns:
true if the animation frame has changed
getAnimationLabel
()
String
Returns the label of the current animation
Returns:
label Image/Animation identifier
getDirection
()
Number
Calculates the movement's direction in degrees.
Returns:
Angle in degrees
getScaledHeight
()
Number
Gets the scaled height of the sprite.
Returns:
Scaled height
getScaledWidth
()
Number
Gets the scaled width of the sprite.
Returns:
Scaled width
getSpeed
()
Number
Calculates the scalar speed.
Returns:
Scalar speed
isTouching
-
target
Alias for overlap(), except without a callback parameter. The check is performed using the colliders. If colliders are not set they will be created automatically from the image/animation bounding box.
Returns whether or not this sprite is overlapping another sprite or group. Modifies the sprite's touching property object.
Parameters:
-
target
ObjectSprite or group to check against the current one
Returns:
True if touching
limitSpeed
-
max
Limits the scalar speed.
Parameters:
-
max
NumberMax speed: positive number
mirrorX
-
dir
Sets the sprite's horizontal mirroring. If 1 the images displayed normally If -1 the images are flipped horizontally If no argument returns the current x mirroring
Parameters:
-
dir
NumberEither 1 or -1
Returns:
Current mirroring if no parameter is specified
mirrorY
-
dir
Sets the sprite's vertical mirroring. If 1 the images displayed normally If -1 the images are flipped vertically If no argument returns the current y mirroring
Parameters:
-
dir
NumberEither 1 or -1
Returns:
Current mirroring if no parameter is specified
mouseUpdate
()
Updates the sprite mouse states and triggers the mouse events: onMouseOver, onMouseOut, onMousePressed, onMouseReleased
nextFrame
()
Alias for animation.nextFrame()
overlap
-
target
-
callback
Checks if the the sprite is overlapping another sprite or a group. The check is performed using the colliders. If colliders are not set they will be created automatically from the image/animation bounding box.
A callback function can be specified to perform additional operations when the overlap occours. If the target is a group the function will be called for each single sprite overlapping. The parameter of the function are respectively the current sprite and the colliding sprite.
Parameters:
-
target
ObjectSprite or group to check against the current one
-
[callback]
Function optionalThe function to be called if overlap is positive
Returns:
True if overlapping
Example:
sprite.overlap(otherSprite, explosion);
function explosion(spriteA, spriteB) {
spriteA.remove();
spriteB.score++;
}
overlapPixel
-
pointX
-
pointY
Checks if the given point corresponds to a transparent pixel in the sprite's current image. It can be used to check a point collision against only the visible part of the sprite.
Parameters:
-
pointX
Numberx coordinate of the point to check
-
pointY
Numbery coordinate of the point to check
Returns:
result True if non-transparent
overlapPoint
-
pointX
-
pointY
Checks if the given point is inside the sprite's collider.
Parameters:
-
pointX
Numberx coordinate of the point to check
-
pointY
Numbery coordinate of the point to check
Returns:
result True if inside
pause
()
Alias for animation.stop()
play
()
Alias for animation.play() with extra logic
Plays/resumes the sprite's current animation. If the animation is currently playing this has no effect. If the animation has stopped at its last frame, this will start it over at the beginning.
previousFrame
()
Alias for animation.previousFrame()
remove
()
Removes the Sprite from the sketch. The removed Sprite won't be drawn or updated anymore.
setAnimation
-
label
Sets the animation from a list in _predefinedSpriteAnimations.
Parameters:
-
label
StringAnimation identifier
setCollider
-
type
-
offsetX
-
offsetY
-
width
-
height
-
rotation
Sets a collider for the sprite.
In p5.play 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 bounding box is not appropriate as the active area for collision detection so you can set a circular or rectangular sprite with different dimensions and offset from the sprite's center.
There are many ways to call this method. The first argument determines the type of collider you are creating, which in turn changes the remaining arguments. Valid collider types are:
-
point
- A point collider with no dimensions, only a position.setCollider("point"[, offsetX, offsetY])
-
circle
- A circular collider with a set radius.setCollider("circle"[, offsetX, offsetY[, radius])
-
rectangle
- An alias foraabb
, below. -
aabb
- An axis-aligned bounding box - has width and height but no rotation.setCollider("aabb"[, offsetX, offsetY[, width, height]])
-
obb
- An oriented bounding box - has width, height, and rotation.setCollider("obb"[, offsetX, offsetY[, width, height[, rotation]]])
Parameters:
-
type
StringOne of "point", "circle", "rectangle", "aabb" or "obb"
-
[offsetX]
Number optionalCollider x position from the center of the sprite
-
[offsetY]
Number optionalCollider y position from the center of the sprite
-
[width]
Number optionalCollider width or radius
-
[height]
Number optionalCollider height
-
[rotation]
Number optionalCollider rotation in degrees
setDefaultCollider
()
Creates a default collider matching the size of the placeholder rectangle or the bounding box of the image.
setFrame
-
x
-
y
Rotate the sprite towards a specific position
Parameters:
-
x
NumberHorizontal coordinate to point to
-
y
NumberVertical coordinate to point to
setFrame
-
frame
Alias for animation.changeFrame()
Parameters:
-
frame
NumberFrame number (starts from 0).
setSpeed
-
speed
-
angle
Set the speed and direction of the sprite. The action overwrites the current velocity. If direction is not supplied, the current direction is maintained. If direction is not supplied and there is no current velocity, the current rotation angle used for the direction.
Parameters:
-
speed
NumberScalar speed
-
[angle]
Number optionalDirection in degrees
setSpeedAndDirection
-
speed
-
angle
Alias for setSpeed()
Parameters:
-
speed
NumberScalar speed
-
[angle]
Number optionalDirection in degrees
setVelocity
-
x
-
y
Sets the velocity vector.
Parameters:
-
x
NumberX component
-
y
NumberY component
update
()
Updates the sprite. Called automatically at the beginning of the draw cycle.
Properties
_rotation
Number
private
Internal rotation variable (expressed in degrees). Note: external callers access this through the rotation property above.
Default: 0
bounciness
Number
Sprite bounciness (alias to restitution).
collider
Object
The sprite's current collider. It can either be an Axis Aligned Bounding Box (a non-rotated rectangle) or a circular collider. If the sprite is checked for collision, bounce, overlapping or mouse events the collider is automatically created from the width and height of the sprite or from the image dimension in case of animate sprites
You can set a custom collider with Sprite.setCollider
debug
Boolean
If set to true, draws an outline of the collider, the depth, and center.
Default: false
depth
Number
Determines the rendering order within a group: a sprite with lower depth will appear below the ones with higher depth.
Note: drawing a group before another with drawSprites will make its members appear below the second one, like in normal p5 canvas drawing.
Default: One more than the greatest existing sprite depth, when calling createSprite(). When calling new Sprite() directly, depth will initialize to 0 (not recommended).
frameDelay
Number
Sprite animation frame delay (alias to animation.frameDelay).
friction
Number
Friction factor, reduces the sprite's velocity. The friction should be close to 0 (eg. 0.01) 0: no friction 1: full friction
Default: 0
groups
Array
Groups the sprite belongs to, including allSprites
height
Number
Height of the sprite's current image. If no images or animations are set it's the height of the placeholder rectangle.
Default: 100
immovable
Boolean
If set to true the sprite won't bounce or be displaced by collisions Simulates an infinite mass or an anchored object.
Default: false
life
Number
Cycles before self removal. Set it to initiate a countdown, every draw cycle the property is reduced by 1 unit. At 0 it will call a sprite.remove() Disabled if set to -1.
Default: -1
lifetime
Number
Sprite lifetime (alias to life).
mass
Number
The mass determines the velocity transfer when sprites bounce against each other. See Sprite.bounce The higher the mass the least the sprite will be affected by collisions.
Default: 1
maxSpeed
Number
Set a limit to the sprite's scalar speed regardless of the direction. The value can only be positive. If set to -1, there's no limit.
Default: -1
mouseActive
Boolean
If set to true sprite will track its mouse state. the properties mouseIsPressed and mouseIsOver will be updated. Note: automatically set to true if the functions onMouseReleased or onMousePressed are set.
Default: false
mouseIsOver
Boolean
True if mouse is on the sprite's collider. Read only.
mouseIsPressed
Boolean
True if mouse is pressed on the sprite's collider. Read only.
originalHeight
Number
Unscaled height of the sprite If no images or animations are set it's the height of the placeholder rectangle.
Default: 100
originalWidth
Number
Unscaled width of the sprite If no images or animations are set it's the width of the placeholder rectangle.
Default: 100
previousPosition
p5.Vector
The sprite's position at the beginning of the last update as a vector (x,y).
removed
Boolean
True if the sprite has been removed.
restitution
Number
Coefficient of restitution. The velocity lost after bouncing. 1: perfectly elastic, no energy is lost 0: perfectly inelastic, no bouncing less than 1: inelastic, this is the most common in nature greater than 1: hyper elastic, energy is increased like in a pinball bumper
Default: 1
rotateToDirection
Boolean
Automatically lock the rotation property of the visual element (image or animation) to the sprite's movement direction and vice versa.
Default: false
rotation
Number
Rotation in degrees of the visual element (image or animation) Note: this is not the movement's direction, see getDirection.
Default: 0
rotationSpeed
Number
Rotation change in degrees per frame of thevisual element (image or animation) Note: this is not the movement's direction, see getDirection.
Default: 0
scale
Number
Determines the sprite's scale. Example: 2 will be twice the native size of the visuals, 0.5 will be half. Scaling up may make images blurry.
Default: 1
shapeColor
Color
If no image or animations are set this is the color of the placeholder rectangle
touching
Object
Object containing information about the most recent collision/overlapping To be typically used in combination with Sprite.overlap or Sprite.collide functions. The properties are touching.left, touching.right, touching.top, touching.bottom and are either true or false depending on the side of the collider.
velocity
p5.Vector
The sprite's velocity as a vector (x,y) Velocity is speed broken down to its vertical and horizontal components.
velocityX
Number
Sprite x velocity (alias to velocity.x).
visible
Boolean
The sprite's visibility.
Default: true
width
Number
Width of the sprite's current image. If no images or animations are set it's the width of the placeholder rectangle.
Default: 100
x
Number
Sprite x position (alias to position.x).
y
Number
Sprite y position (alias to position.y).
y
Number
Sprite y velocity (alias to velocity.y).