Activity: Generate Sprites using create and on created
Many games need to spawn sprites for the player to do things like collect coins or avoid oil spills.
We will use the set mySprite to block from the Sprites menu to spawn a new empty sprite, with nothing in it yet. Then we can use an on created event to set the image and a random position for newly generated sprites.
The on created block uses the sprite’s kind so we can give our new sprites the exact attributes we want, like an image, velocity, or position.
Concept: Create with on created event
Example #1: Random clouds
This example uses the on created event to set the sprite image and location after a sprite of a particular kind is spawned.
- Review the code below
- Create a new project and name it “spawnCloud”
- Create the sample code and run the code
- Carefully examine the sprite of kind oval in the set cloud to blocks and the on created event
Student Task #1: More Random Clouds
The on created event allows us to set code to run whenever a new sprite is created. This is used to create new clouds multiple times with the same code. Now we will create new clouds with set cloud to blocks with empty image editors.
- Start with example #1 or your own similar code
- Add two more set cloud to blocks for clouds
- Add a new set mySprite to block for a different kind. Use the on created event to
- set an image for the sprite that is created (for example, a bird or a butterfly)
- set the sprite to be in a random position
- Use set mySprite to blocks to create at least five of the kinds
- Challenge: create an event for the Helicopter overlap with the new kind that has an action that gives the new kind a fast velocity so that it will fly off the screen after they overlap
What did we learn?
- Describe how a kind label is used in generating a sprite by creating an empty sprite block.
- Explain what the on created block does for you.