mit-scratch

In Scratch, how can the clone A of Sprite2 detect if it's touching another clone B of the same Sprite2 and delete both clones?


This is for a mini program in Scratch.

What I want to do:

When a clone A of Sprite2 touches another clone B of the same Sprite2, both clones are deleted, but any other clone stays existing and executing.

What I have tried:

I have tried finding if there was an option like "touching another clone", but I haven't found it.

No option found1

I also tried putting a sensor that detects if a clone is making contact with its same color (if[color{red}is touching color{red}] then) => (delete clone), but it didn't work, it entered an infinite loop where the page begun to get choppy so I deleted that.

I even made the function outside the sprite (where I could find the option (touching [sprite2] ?)) and then moved the function inside sprite2 but it ignores that new inserted function.

Do you know how this could be done?


Solution

  • As seen in your screenshot, the dropdown list of the 'touching' block shows a list of all sprites in the project (in this case Sprite1) except the current sprite (Sprite2).

    Fortunately, it is possible to have a 'touching Sprite2' block within Sprite2. It's a bit of a hack, but it works. Follow these steps:

    1. Go to the code area of Sprite1. (Any sprite will do except Sprite2. If Sprite2 is the only sprite in the project, add a dummy sprite; you can safely remove it after step 4.)
    2. From the 'sensing' group, drag a 'touching' block onto the code area.
    3. Open the block's dropdown and select Sprite2.
    4. Drag the block from the code area to Sprite2 (as seen in the sprite collection, bottom right).
    5. Go to Sprite2. Notice there's a 'touching Sprite2' block there. Drag it to the script where you need it.

    When using this to make clones disappear as they collide, you may notice that only one clone will disappear, and the other will survive. This is a 'race condition': simultaneous events never happen exactly at the same time. The first clone to detect the collision deletes itself, thereby erasing the incident before the other clone has had a chance to detect it.

    In most cases, this can be fixed by adding a 'wait 0 seconds' block immediately above the 'delete this clone' block. Waiting zero seconds may seem like a no-op, but it actually has effect: it gives other threads (scripts, clones, sprites) the time to catch up with the current one.

    Live demo: https://scratch.mit.edu/projects/704352756/