Create a Canvas

The q5.js Canvas function creates a section of the screen that the program can draw on.

await must be used to wait for the canvas to be ready.

Try changing the numerical inputs to Canvas!

What is a sprite?

A sprite is a ghost!

Video game developers use the word "sprite" to refer to characters, items, or anything else that moves above a background.

The new Sprite() constructor creates a sprite object, which contains variables that define a sprite's position, size, and appearance.

Try editing the properties of the box and circle sprites in the code examples below!

Try it!

Try turning the sprite named ball into a blue circle with a diameter of 30 and place it at the top right corner of the canvas.

Update Loop

The q5.update function is run 60 times per second by default.

Define this function to handle user input before each physics simulation update.

If undefined, q5play automatically runs clear to clear the canvas at the start of each frame cycle.

Sprite physics

A sprite's physicsType/physics determines how it behaves in the physics simulation:

  • DYNAMIC/DYN (default): affected by gravity
  • STATIC/STA: doesn't move
  • KINEMATIC/KIN: not moved by other sprites

By default, sprites have a collider that can be used to detect collisions with other sprites.

Click the reload icon on the top right corner of a code example to replay it!

Try it!

Try creating a sprite named peg with a static collider and circle shape. Create a sprite block with a dynamic collider and box shape. Position the block so that it hits the peg and falls to the right.

Each time the q5 draw function finishes, sprites are automatically drawn. Note that world is created when q5play loads but by default there's no gravity. Try setting world.gravity.y to a positive number.

For an extra challenge, try resetting the block to its original position after it falls.

Sprites with an Image

sprite.img can be set to a Q5.Image or a url path to an image file.

sprite.img.offset can be used to offset the image relative to the sprite's center. This can help better align the image with the sprite's physics collider.

Try clicking on the canvas of this example. When the sprite.debug property is set to true you can see the sprite's physics body collider.

Set a sprite's opacity to change the transparency of its appearance. Use a value between 0 (completely transparent) and 1 (completely opaque).

sprite.img.scale changes the display size of the sprite's image. The default is 1.0. If the image appears way too big or small, you should probably change the size of the image file itself.

Emoji Sprites

No images? ๐Ÿซฅ No problem! ๐Ÿ˜„

You can use any emoji as the image for your sprite.

The size of the emoji image will be based on the sprite's size. Great for quick prototyping! ๐Ÿงช

Pixel Art

You can use the spriteArt function to create pixel art images for your sprites. It takes a string as input and returns an image. Each character in the string represents the color value of a pixel in the image.

The second input parameter to the spriteArt function is the scale of the image.

Try it!

Try making your own pixel art! Take a look at the alphabet below to see what color each letter represents by default.

Custom Colors

You can also make pixel art that uses custom colors by creating a color palette and passing it as the third parameter to the spriteArt function.

Color palettes in q5play must be provided in JavaScript Object literal format. A simple JS object is like a dictionary. You can define a color for each letter you use in your pixel art. To create a color use the q5 color function which accepts RGB (red, green, blue) values or HEX color codes.

The easiest way to find colors is to use a color picker.

Sprite movement

Moving a sprite by directly editing its (x, y) coordinates will teleport it to the new position, without moving it through intermediate positions.

Try clicking around this code example.

When teleporting a sprite continuously, it can clip into or pass right through other sprites!

This may be fine for some games, but not if you want realistic physical interactions.

All the other movement methods on this page change the sprite's velocity, aka vel, which is its rate of motion along the x and y axis.

vel is a Vector, you can use any vector functions on it.

Restart this example to see the player sprite hit the block!

Yet, you may find it's more convenient to move a sprite by setting its direction and speed.

You can also set a sprite's direction using an angle value or direction name such as: 'up', 'down', 'left', 'right', 'upLeft', 'upRight', 'downLeft', 'downRight'.

The moveTowards function moves a sprite towards a position, at a percentage of the distance to that position.

In this example, the player moves 10% of the distance to the mouse on every physics simulation update.

Note that the movement methods you've seen on this page are imperative: they override a sprite's current motion, forcing it to move in a new direction. That may not always be what you want! Read the Advanced Movement page to learn how to move a sprite with respect to other forces acting on it, such as gravity.

Create Sprites faster

Inside the Sprite constructor, new Sprite(), you can specify the sprite's position, size, and physics type.

As you saw on the previous Sprite reference pages, you don't need to add any inputs to the Sprite constructor to create a sprite. But, if you do want to set a sprite's size in the constructor you'll need to specify its position first.

By default, if no inputs are given to the Sprite constructor, a new sprite is positioned at the center of the canvas, with a width and height of 50 pixels, and a dynamic collider.

Try it!

Try creating one large sprite and one small sprite using the Sprite constructor.

Collisions

To check for collisions use these functions inside the q5 draw function.

On the first frame that a sprite collides with another sprite, the collides function returns true.

While a sprite is colliding with another sprite, the colliding function returns the number of frames the collision has occurred for.

On the first frame after two sprites collided, the collided function returns true.

Overlaps

Sprites collide by default but they can also overlap!

By default sprites are drawn in the order they were created in.

Layer

You can change the draw order by editing a sprite's .layer property. Sprites with higher layer values get drawn on top of sprites with lower layer values.

For detecting overlaps, use these functions inside the q5 draw function.

On the first frame that a sprite overlaps with another sprite, the overlaps function returns true.

While a sprite is overlapping with another sprite, the overlapping function returns the number of frames the overlap has occurred for.

On the first frame after two sprites overlapped, the overlapped function returns true.

Note that physical interactions between sprites, including collisions and overlaps, can't be properly detected when a sprite is teleported, its position is directly changed!

The delete function deletes a sprite from the physics world simulation and removes it from all the groups it belongs to.

Try it!

Try making the blue sprite change to red only if it's overlapping with the red sprite.

Pass Through

If you don't need to detect overlap events, use the passes function to make a sprite simply pass through another sprite.

When you set an overlap or pass through relationship between two sprites, they will no longer collide, but you can make them have a collision relationship again.

In this example, pressing the space key temporarily allows the player to pass through the wall.

Sprite rotation

Directly changing the rotation property of a sprite will teleport it to the specified rotation angle.

Don't teleport a sprite if you want it to physically interact with other sprites while it's rotating!

All of the other rotation methods on this page work by changing the sprite's rotationSpeed.

Use the rotateTowards function to rotate a sprite towards an angle or towards facing a position.

The optional second parameter is the tracking speed, a percent of the distance the sprite moves on each frame to the target rotation angle, 0.1 (10%) by default.

A sprite's center of mass is the point at which it rotates, which by default is equivalent to its position.

Set centerOfMass to change the sprite's center of mass relative to its position.

When debug is true, the sprite's position is marked with a small green triangle.

Notice that in this example the sprite rotates around its center of mass, and its position changes. If that's undesirable, consider using addCollider instead.

Scaling

Changing sprite.scale will scale the sprite's collider and visual appearance by the specified amount.

Press a number key to see the sprite scale uniformly by that amount.

Click your mouse or touch tap to double the sprite's scale.

Press "x" or "y" to scale the sprite in that direction by a random amount. But note that if the sprite gets scaled unevenly, the image will get distorted and stay that way even when scaled uniformly again.

Physical attributes

Sprites have physical attributes that affect how they interact with the world. Take a look at the code examples to see these attributes in action.

Mass

The larger the sprite, the more mass it has by default.

A sprite's default mass is calculated when its initial size is set, but you can override it by setting mass, like in this example.

Stretching or squishing an object in the real world doesn't change its mass, so in q5play changing a sprite's size doesn't change its mass either.

If you want to recalculate a sprite's mass based on its size, use the resetMass function.

Try it!

This code example shows how sprites of different sizes can balance on a seesaw if their mass is set to the same value. Try changing the mass of one of the sprites.

Advanced Movement

When you change a sprite's velocity vector, that's an imperative for it to defy the forces acting on it, such as gravity. But what if you want to move a sprite in a way that still respects those forces?

The applyForce function can accept force as separate x and y components or as an amount, provided you set the sprite's bearing angle.

A bearing is the direction that needs to be followed to reach a destination. Changing a sprite's bearing won't imperatively change its movement direction.

In this example, the drone has to overcome the force of gravity. Make the drone fly, then let it fall and apply upward force to the drone again. It'll gradually stop falling and fly up!

The applyForceScaled function multiplies the force applied to the sprite by its mass.

You can use this function to give sprites their own gravity!

By default, force is applied to the sprite's center of mass. But these force functions can also accept, as the last input parameter, a relative position on the sprite where the force should be applied.

Use the attractTo function to attract the sprite to a position by applying force. The position can be given as an object with x and y properties or as separate x and y parameters.

This example shows an electron orbiting the nucleus of an atom. (Note this visualization isn't realistic based on current scientific understanding, but it looks cool!)

Note that the advanced movement functions shown on this page will not wake sleeping sprites!

Torque is the force that causes rotation. Use applyTorque to non-imperatively affect the sprite's rotation.

In this example, the robot rolls slower going uphill than it does going downhill.

Chains

Chain colliders are composed of one or more lines.

One way to create a chain is to provide an array of vertices to the Sprite constructor.

These vertices can be given in [x, y] array format or as objects with x and y properties.

In this example, the sprite's position is highlighted by a small white square.

Try changing the vertexes of the chain sprite in the code example to make the ball stay on the floor!

Another way to create a chain is to provide the Sprite constructor a position and an array of relative vertices.

This provides a nice way to creating multiple sprites with the same chain collider shape.

Additionally, you can provide the Sprite constructor an (x,y) position and a list of line lengths and angles. Each angle is relative to the previous line's angle.

Note that when using this mode, the chain's (x, y) position will be located at the average of all its vertices, which may not be a point on the chain.

Try changing the lengths of these lines and their angles!

Known issue with q5play beta: sprites created this way are not positioned properly.

Polygon Colliders

Regular polygons can be created by providing the Sprite constructor with a side length and the name of the polygon.

Here are the names you can use: triangle, square, pentagon, hexagon, septagon, octagon, enneagon, decagon, hendecagon, and dodecagon.

If the start and end of a chain is at the same point and the resulting shape is convex, it automatically becomes a polygon!

Known issue with q5play beta: sprites created this way are not positioned properly.

Here's the code for making a regular star with five points.

Note that because the star is a concave shape it can't have a polygon collider.

Now you can see how the tumbler demo on the q5play homepage was made!

Closed chains are empty on the inside and they can act as a container for many smaller sprites.

Adding Colliders

By using the addCollider function you can add more colliders to a sprite. It supports the same input arguments as the Sprite constructor, except the first two parameters are x and y offsets from the sprite's position.

Only use this feature when it's really necessary for gameplay!

Usually if something requires a lot of colliders, like the walls of a maze, you should create multiple sprites, each with their own collider.

Also, even if a sprite's image is complex, typically a box or circle will be just fine for physics interactions, especially for small sprites.

Yet sometimes, you'll truly need to create a sprite with multiple colliders. For example, if you want to model a pinball flipper!

Note that adding a collider to a sprite will automatically recalculate the sprite's mass.

Adding Sensors

Overlap sensors determine if a sprite overlaps with another sprite.

By default when an overlap checking function is used, and the sprite has no sensors, the addDefaultSensors function is used behind the scenes to create sensors for each of the sprite's colliders.

You can add additional sensors to a sprite by using the addSensor function. Note that they're invisible, unless debug is true.

Custom Update

A sprite's update function runs before each physics simulation update, by default. You can customize the sprite's update function with user input handling and sprite specific logic.

Custom Draw

Sometimes you won't be able to use pre-drawn animations to get the kind of visual effect you want for a sprite in motion.

Fortunately, you can customize the sprite's draw function to make it display anything you want! By default, sprites are drawn after physics simulation updates.

Note that inside the sprite's draw function, the center of the sprite is at position (0, 0).

This code example rotates the sprite's ellipse to the direction it's moving and makes the ellipse stretch in that direction proportional to its speed. Kind of complicated but a nice effect!

Movement Sequencing

If you want a sprite to follow another sprite, set its direction to be the angle between the sprites using the angleTo function.

In this example, the q5 dist function is used to calculate the distance between the player and its ally. If the distance is greater than 50 pixels, the ally moves towards the player. If the distance is less than 40 pixels, the ally stops moving.

Previous Page Next Page