Using Clones for Particle Effects

Материал из Поле цифровой дидактики
Описание Как создать эффект частиц с помощью клонов?
Область знаний Химия, Биология, Информатика
Область использования (ISTE) Computational Thinker
Возрастная категория 10


Поясняющее видео
Близкие рецепту понятия Flocking, Клон
Среды и средства для приготовления рецепта: Snap!, Scratch

Клоны появились в Scratch с версии 2. They allowed you to create complete duplicates of sprites, which can then individually run tasks.

Using clones properly is important — you should make sure your scripts are concise, fast, and readable. This tutorial will explain how to use clones to create a utility for particle effects. This will begin with using clones to create a 'spark' effect, then optimize the code, and finally create an easy-to-use package for a user so that they can incorporate it into a project easily. The goal is to create a single block called "Create a spark at x: () y: ()".

Instructions

Creating the Effect

First, you need to create the parent sprite. This sprite will generate all the particles of the spark effect not that it itself will never be one of the particles. The general plan of the code is:

  • To generate a spark effect, go to the required position
  • Create 10 clones, each of which is a particle of the spark
  • When the particles are created, they fly out and fall, together giving the effect of a spark

First, create your sprite. Name it "Spark" and make its costume a single orange dot. Шаблон:Note

To begin, create two local variables and call then velocity x and velocity y. Make sure that they're "for this sprite only".

  • Always use local variables where you can so that you do not add too many new variables to the user's palette. If the user has variables of the same name, there will be errors. If you do need a global variable, prefix its name. For example, use "(spark).color" instead of "color".

Now you will need to write the common velocity-arc script under a "when I start as a clone" block:

Whenspacekeypressedrepeat10createcloneofmyselfendWhenIstartasaclonesetvelocityxtopickrandom-5to5/3setvelocityytopickrandom1to10repeat20changexbyvelocityxchangeybyvelocityychangevelocityyby-1enddeletethisclone

At this point, you can run the script! Just press space to see some sparks.

How come the velocity variables do not get muddled with each other and get reset by each clone? When we clicked "for this sprite only", we made it a lexically scoped variable which is duplicated along with the sprite. That is, each clone had its own velocity x and velocity y variables independent of each other.

One of the issues with this script is that if you press space multiple times, each spark duplicates itself. This is clearly wrong behavior; it happens because when space is pressed, each clone starts creating copies. So we need a new variable which tells us whether we are a clone or not:

whenclickedsetisclone?tonowhenspacekeypressedifisclone?=nothenrepeat10createcloneofmyselfendendwhenIstartasaclonesetisclone?toyessetvelocityxtopickrandom-5to5/3setvelocityytopickrandom1to10repeat20changexbyvelocityxchangeybyvelocityychangevelocityyby-1enddeletethisclone

The is clone? variable tells the sprite whether or not to duplicate itself. Make sure this is local, too. You can also fix the issue by instead of using when space key pressed you could use

whenclickedforeverifkeyspacepressedthenrepeat10createcloneofmyselfendendend

Optimizations and Improvements

In this section, we will add the following optimizations to the spark engine:

  • Sparks will be created gradually, instead of suddenly
  • Sparks will fade out and "die" automatically, instead of waiting to touch the edge

First, we hide the parent spark, because it should not be visible. We also make the spark creation routine a custom block. Then we add a small delay when creating a clone, which changes over time to give a more realistic effect:


whenclickedsetisclone?tonohidewhenIstartasacloneshowsetisclone?toyessetvelocityxtopickrandom-5to5/3setvelocityytopickrandom1to10repeat20changexbyvelocityxchangeybyvelocityychangevelocityyby-1enddeletethisclonedefineCreateeffectatxygotox:xy:ysetcreation_delayto-0.05ifisclone?=nothenrepeat10changecreation_delayby0.001waitcreation_delay*creation_delaysecscreatecloneofmyselfendendwhenspacekeypressedCreateeffectat11

To make sparks fade out, we simply change the ghost effect:

whenclickedsetisclone?tonohidewhenIstartasacloneshowsetisclone?toyessetvelocityxtopickrandom-5to5/3setvelocityytopickrandom1to10repeat20changeghosteffectby5changexbyvelocityxchangeybyvelocityychangevelocityyby-1enddeletethisclonedefineCreateeffectatxygotox:xy:ysetcreation_delayto-0.03ifisclone?=nothenrepeat10changecreation_delayby0.001waitcreation_delay*creation_delaysecscreatecloneofmyselfcreatecloneofmyselfcreatecloneofmyselfcreatecloneofmyselfendendwhenspacekeypressedCreateeffectat11

We also create more sparks for a richer effect, and tweak the creation delay mildly.

Distributing the Code

To distribute the sparks library, we need to create a custom block which can be defined on any sprite. When called by the user, it should send a broadcast to the spark sprite to generate a spark effect.

We do this by creating a global list called "(spark) preferences" which contains a list of information about the spark library. It has, in order:

  1. X position to spawn
  2. Y position to spawn
  3. Color to spawn

Adding these touches, we have:

whenspacekeypressedcreateeffectat11definecreateeffectatxygotox:xy:ysetcreation_delayto-0.002ifisclone?=nothenrepeat3changecreation_delayby0.005waitcreation_delay*creation_delaysecscreatecloneofmyselfcreatecloneofmyselfcreatecloneofmyselfcreatecloneofmyselfendendwhenIstartasacloneshowsetisclone?toyessetvelocityxtopickrandom-5to5/3setvelocityytopickrandom1to10repeat20changeghosteffectby5changexbyvelocityxchangeybyvelocityychangevelocityyby-1enddeletethisclonewhenclickedsetisclone?tonohidewhenIreceive(spark)spawnsetcoloreffecttoitem3of(spark)preferencescreateeffectatitem1of(spark)preferencesitem2of(spark)preferences

We also create the global block, and a small demo script:

whenspacekeypressedSpawnSparkEffectatx:mousexy:mouseycolor:pickrandom1to200defineSpawnSparkEffectatx:xy:ycolor:colorreplaceitem1of(spark)preferenceswithxreplaceitem2of(spark)preferenceswithyreplaceitem3of(spark)preferenceswithcolorbroadcast(spark)spawn

An issue here is that when you create a spark while an old one is running, the old spark effect stops. This is because of the broadcast. To avoid this, we use a trigger variable instead of a broadcast. We add a new item to our preferences list. Whenever a new spark is created, we simply set this to "new", and our library resets it back to blank once the effect has been created:

whenclickedsetisclone?tonohidewhenIstartasacloneshowsetisclone?toyessetvelocityxtopickrandom-5to5/3setvelocityytopickrandom1to10repeat20changeghosteffectby5changexbyvelocityxchangeybyvelocityychangevelocityyby-1enddeletethisclonedefineCreateeffectatxygotox:xy:ysetcreation_delayto-0.002ifisclone?=nothenrepeat3changecreation_delayby0.005waitcreation_delay*creation_delaysecscreatecloneofmyselfcreatecloneofmyselfcreatecloneofmyselfcreatecloneofmyselfendendwhenclickedforeverifnew=item4of(sparks)preferencesthenreplaceitem4of(sparks)preferenceswithsetcoloreffecttoitem3of(sparks)preferencesCreateeffectatitem1of(sparks)preferencesitem2of(sparks)preferenceswhenspacekeypressedSpawnSparkEffectatx:mousexy:mouseycolor:pickrandom1to200defineSpawnSparkEffectatx:xy:ycolor:colorreplaceitem1of(spark)preferenceswithxreplaceitem2of(spark)preferenceswithyreplaceitem3of(spark)preferenceswithcolorreplaceitem4of(spark)preferenceswithnew

An example project can be found here.

See Also