var sprite = createSprite()
Creates a new sprite and assigns it to the variable specified.
Sprites are used to make complex and interesting animations and games. A sprite is able to store images or animations with a set of properties such as position and visibility. Sprites also have properties to report interactions with other sprites or the mouse.
Examples
var sprite = createSprite();
drawSprites();
Red Stripe
A later sprite overwrites and earlier sprite.
// A later sprite overwrites an earlier sprite.
var sprite1 = createSprite(200,200,100,100);
var sprite2 = createSprite(200,200,50,100);
sprite2.shapeColor="red";
drawSprites();
Make Some Stickers
Using 26 different images for stickers, use randomNumber to pick twenty different stickers randomly, and use randomNumber again to pick random places for each sticker.
// Use 10 different images for stickers, and randomNumber to place the stickers
var count = 0;
function draw() {
background("white");
count = count + 1;
if (count < 20) {
var sprite = createSprite(200, 200);
sprite.setAnimation("sticker" + randomNumber(1,10));
sprite.x = randomNumber(40, 360);
sprite.y = randomNumber(40, 360);
}
drawSprites();
}
Syntax
var sprite = createSprite(x, y, w, h)
Parameters
Name | Type | Required? | Description |
---|---|---|---|
x | Number | The x-location in pixels of the center of the sprite from left to right on the display. Default x value is 0. Should be a number from 0 to 400, but negative numbers will center the sprite to the left of the display and numbers greater than 400 will center the sprite to the right of the display (possibly unseen). | |
width | Number | The horizontal width in pixels of the default sprite shape, a rectangle. Default width is 100. Should be a positive number. | |
y | Number | The y-location in pixels of the center of the sprite from top to bottom on the display. Default y value is 0. Should be a number from 0 to 400, but negative numbers will center the sprite above the display and numbers greater than 400 will start the sprite below the display (possibly unseen). | |
height | Number | The vertical height in pixels of the default sprite shape, a rectangle. Default height is 100. Should be a positive number. |
Returns
Tips
- Sprites that are created later are displayed in front of sprites created earlier, unless the
depth
property is changed. - Change the image displayed for the sprite from the default rectangle using the
setAnimation
command. All images must be first loaded and given a label using the Animation tab above the display window in Game Lab. - Sprites all have the same properties and you use the dot notation (combining the name of the sprite, followed by a dot, with the label of the property) to both access and update the property for that sprite.
- If you attempt to set a sprite property to an incorrect value the property reverts to its default value.
Found a bug in the documentation? Let us know at support@code.org.