Discuss Scratch
- Discussion Forums
- » Help with Scripts
- » Automatically shooting at closest Enemy Clone (Tower Defense) (Need HELP!)
- FalloutFanboy_
-
2 posts
Automatically shooting at closest Enemy Clone (Tower Defense) (Need HELP!)
Hi 
I just joined the Scratch Community to ask this question..
While working on my first Tower Defense Game I realised its pretty hard to make the towers aim and shoot at the closest enemy clone. I tried to solve this problem for hours - Now I think its almost impossible to do. Im a Beginner and have scarcely experience and skill in working with Scratch :I
really need some help, because I have to do this game for school. Deadline is Wednesday.
Some Informations about my game (if necessary):
• 3 different maps (I think this doesnt really matter)
• 5 given places (all of them are marked) at which you can place your tower
• 3 different tower to buy (the range is always the same)
• 3 types of enemies (i think that doesnt matter too)
Thanks in advance, and sorry for my bad, baad english

I just joined the Scratch Community to ask this question..
While working on my first Tower Defense Game I realised its pretty hard to make the towers aim and shoot at the closest enemy clone. I tried to solve this problem for hours - Now I think its almost impossible to do. Im a Beginner and have scarcely experience and skill in working with Scratch :I
really need some help, because I have to do this game for school. Deadline is Wednesday.
Some Informations about my game (if necessary):
• 3 different maps (I think this doesnt really matter)
• 5 given places (all of them are marked) at which you can place your tower
• 3 different tower to buy (the range is always the same)
• 3 types of enemies (i think that doesnt matter too)
Thanks in advance, and sorry for my bad, baad english

- drmcw
-
1000+ posts
Automatically shooting at closest Enemy Clone (Tower Defense) (Need HELP!)
It's a very common question so searching should find you plenty of answers. The two main methods are to store all the locations in a list and then calculate the shortest distance. A better way, but possibly harder to understand is to use broadcasts https://scratch.mit.edu/projects/18248372/
- MADCAL
-
36 posts
Automatically shooting at closest Enemy Clone (Tower Defense) (Need HELP!)
Well maybe try making your tower point at the clone. I am not 100% sure it will work.
- Birdlegs
-
1000+ posts
Automatically shooting at closest Enemy Clone (Tower Defense) (Need HELP!)
As drmcw said, the easiest way to understand (And it's kinda hard, still!) would be putting their distances into lists, so I'll try and explain it to you so that it's easy. This won't be necessarily the most efficient way–I just want to make it easy
Okay, so first you're going to need a list that contains the X positions of every clone and the Y positions of every clone
Now, when you make a clone of a sprite, it gets its own copy of the sprite's “for this sprite only” variables. This will come in handy for making a sort of “clone ID.” The original sprite can have a for-this-sprite-only variable, which we can just call “CloneID”
The purpose of this variable is for each clone to remember what point in the lists it's X and Y positions go in.
The first clone, for instance, will have a CloneID of 1, and so will put its position into the first slot in the list, and so on.
Here's something to visualize what we have so far
Now…
It's important to clear out the lists and set CloneID back to zero when the flag is clicked, of course.
Now what we have is a number of positions the tower could be pointing toward on each given frame, but it needs to decide which one is closest, and how to point to it. For this, we need to be able to control list data well.
Each tower should have a “for this sprite only variable” you could call “i.” This is a common name for list-reading variables. All we need is to set “i” to one, the first spot in the list, and go over every value in the lists to find which ones represent the closest enemy's position.
To do this, we first need to check the first value in “Xpositions,” subtract that from the tower's own x position and take the absolute value, and add that to the absolute value of the first value in “Ypositions” subtracted from the tower's y position, which will give us a value akin to what the (distance to ) block would give us, if only we could use it! We then need to store that value, along with where it was in the list, so that we can compare it to the next value (And then the next, and so on) and remember where in the list it was. If the next value is less than the previous, we can just replace the data in those variables, because we know the first enemy was already further away than the second.
Now, by the end of that script, (SmallestDistance) will equal the distance to the closest enemy, and (i of SmallestDistance) will tell us where that enemy is storing its list data (That enemy's “CloneID,” actually!) Now you can set some more variables for simplicity:
We're almost done. The tower knows where the closest enemy is. It just needs to point there. For that, we need right triangles!
But that's as far as I can take you with that–I was toying around with it in the editor, and I can't work out the exact trig functions for getting angle. I hope someone else can help!
Oh, and to speed up the list-reading process, it should be done as a custom block with “run without screen refresh” checked.
Okay, so first you're going to need a list that contains the X positions of every clone and the Y positions of every clone
Now, when you make a clone of a sprite, it gets its own copy of the sprite's “for this sprite only” variables. This will come in handy for making a sort of “clone ID.” The original sprite can have a for-this-sprite-only variable, which we can just call “CloneID”
The purpose of this variable is for each clone to remember what point in the lists it's X and Y positions go in.
The first clone, for instance, will have a CloneID of 1, and so will put its position into the first slot in the list, and so on.
Here's something to visualize what we have so far
change [CloneID v] by (1)Note that the above should only be run by the original sprite–not its clones
create clone of [Enemy v] // Be wary of "Create clone of myself," because then you can get clones of clones
Now…
when I start as a clone
add (x position) to [Xpositions v] // These two ensure that there's a space in each list at the proper place for each clone.
add (y position) to [Ypositions v]
forever
Whatever AI scripts you're using
replace item (CloneID) of [Xpositions v] with (x position) // Replaces the data we just put in
replace item (CloneID) of [Ypositions v] with (y position)
end
It's important to clear out the lists and set CloneID back to zero when the flag is clicked, of course.
Now what we have is a number of positions the tower could be pointing toward on each given frame, but it needs to decide which one is closest, and how to point to it. For this, we need to be able to control list data well.
Each tower should have a “for this sprite only variable” you could call “i.” This is a common name for list-reading variables. All we need is to set “i” to one, the first spot in the list, and go over every value in the lists to find which ones represent the closest enemy's position.
To do this, we first need to check the first value in “Xpositions,” subtract that from the tower's own x position and take the absolute value, and add that to the absolute value of the first value in “Ypositions” subtracted from the tower's y position, which will give us a value akin to what the (distance to ) block would give us, if only we could use it! We then need to store that value, along with where it was in the list, so that we can compare it to the next value (And then the next, and so on) and remember where in the list it was. If the next value is less than the previous, we can just replace the data in those variables, because we know the first enemy was already further away than the second.
forever
set [i v] to [1]
set [i of SmallestDistance v] to [1]
set [SmallestDistance v] to (([abs v] of (x position) - (item (i) of [Xpositions v])) + ((abs of (y position) - (item (i) of [Ypositions v]))
repeat (length of [Xpositions v] :: list) // We could use the length of either list, since they'll have the same length
if <(([abs v] of (x position) - (item (i) of [Xpositions v])) + ((abs of (y position) - (item (i) of [Ypositions v])) < (SmallestDistance)> then
set [SmallestDistance v] to (([abs v] of (x position) - (item (i) of [Xpositions v])) + ((abs of (y position) - (item (i) of [Ypositions v]))
set [i of SmallestDistance v] to (i)
end
change [i v] by (1)
end
end
Now, by the end of that script, (SmallestDistance) will equal the distance to the closest enemy, and (i of SmallestDistance) will tell us where that enemy is storing its list data (That enemy's “CloneID,” actually!) Now you can set some more variables for simplicity:
set [ClosestEnemy's X v] to (item (i of SmallestDistance v) of [Xpositions v] :: list)
set [ClosestEnemy's Y v] to (item (i of SmallestDistance v) of [Ypositions v] :: list)
We're almost done. The tower knows where the closest enemy is. It just needs to point there. For that, we need right triangles!
But that's as far as I can take you with that–I was toying around with it in the editor, and I can't work out the exact trig functions for getting angle. I hope someone else can help!
Oh, and to speed up the list-reading process, it should be done as a custom block with “run without screen refresh” checked.
Last edited by Birdlegs (May 15, 2017 20:33:22)
- gtoal
-
1000+ posts
Automatically shooting at closest Enemy Clone (Tower Defense) (Need HELP!)
Here's a simpler somewhat hacky way to do it.
create a circular sprite with 99% transparency so it isn't visible. (or maybe it'll work even if hidden - I'm not sure, I've never tried that)
loop over increasing the size of the circle by 1 until it touches the enemies.
Have the clone identify itself. Be wary of two clones at the same distance.
G
create a circular sprite with 99% transparency so it isn't visible. (or maybe it'll work even if hidden - I'm not sure, I've never tried that)
loop over increasing the size of the circle by 1 until it touches the enemies.
Have the clone identify itself. Be wary of two clones at the same distance.
G
- Birdlegs
-
1000+ posts
Automatically shooting at closest Enemy Clone (Tower Defense) (Need HELP!)
Ohh, that's a good way to avoid all that list management! Here's a simpler somewhat hacky way to do it.
create a circular sprite with 99% transparency so it isn't visible. (or maybe it'll work even if hidden - I'm not sure, I've never tried that)
loop over increasing the size of the circle by 1 until it touches the enemies.
Have the clone identify itself. Be wary of two clones at the same distance.
G
Also, 100% ghosting works fine as well. Collisions are only not detected when the sprite is hidden–ghost effect doesn't change collision at all
- TheDeadbushNoob
-
16 posts
Automatically shooting at closest Enemy Clone (Tower Defense) (Need HELP!)
try this
when green flag clicked
forever
wait (0.1) secs
point towards [enemy]
create clone of [myself]
when I start as a clone
switch costume to [bullet]
forever
move (10) steps
if <<touching [enemy] ?> or <touching [edge] ?>> then
delete this clone
end
end
Last edited by TheDeadbushNoob (May 16, 2017 05:54:58)
- TheLogFather
-
1000+ posts
Automatically shooting at closest Enemy Clone (Tower Defense) (Need HELP!)
If you're going to create a whole new sprite for the job, and place it at the current required ‘central’ position, then you might as well just send a broadcast that tells all the clones to check their distances from that sprite, comparing against current closest, and marking their own co-ords if closer than that (and updating the distance ready for next clone to compare against). Here's a simpler somewhat hacky way to do it.
create a circular sprite with 99% transparency so it isn't visible. (or maybe it'll work even if hidden - I'm not sure, I've never tried that)
loop over increasing the size of the circle by 1 until it touches the enemies.
Have the clone identify itself. Be wary of two clones at the same distance.
G
Once they have all done the comparison, you have your answer – no need to have Scratch waste CPU cycles on resizing and touching tests, etc…
And then, once you've done that, you realise that you don't even need the extra sprite at all – just a couple of global vars that contain the current ‘central’ co-ords, and the clones can then respond to the broadcast by checking their distance from those co-ords instead.
And then you're basically at the method in the project that drmcw linked above…

Last edited by TheLogFather (May 16, 2017 11:11:41)
- gtoal
-
1000+ posts
Automatically shooting at closest Enemy Clone (Tower Defense) (Need HELP!)
Once they have all done the comparison, you have your answer – no need to have Scratch waste CPU cycles on resizing and touching tests, etc…
sometimes the trade-off is not for machine memory or CPU cycles but for human memory and brain cycles :-)
It's not a waste if it goes fast enough and simplifies the code considerably.
That said, doing an efficient implementation of the circle sweep algorithm might not be that simple. I had forgotten when I posted the suggestion that we'd looked at something like this a couple of years ago and it had required a bit of effort to do it reasonably quickly…
https://scratch.mit.edu/projects/115648650/
G
Last edited by gtoal (May 16, 2017 18:06:56)
- Birdlegs
-
1000+ posts
Automatically shooting at closest Enemy Clone (Tower Defense) (Need HELP!)
That's an interesting sort of thing to me, trading efficient code for ease of understanding. I agree, though. I'd suggest gtoal's solution, just because it's so simple. TheLogFather's, though, is definitely the best if you ever need a function like this again down the road and you're experienced enough to tackle it. It's definitely far fasterOnce they have all done the comparison, you have your answer – no need to have Scratch waste CPU cycles on resizing and touching tests, etc…
sometimes the trade-off is not for machine memory or CPU cycles but for human memory and brain cycles :-)
It's not a waste if it goes fast enough and simplifies the code considerably.
That said, doing an efficient implementation of the circle sweep algorithm might not be that simple. I had forgotten when I posted the suggestion that we'd looked at something like this a couple of years ago and it had required a bit of effort to do it reasonably quickly…
https://scratch.mit.edu/projects/115648650/
G
- asivi
-
1000+ posts
Automatically shooting at closest Enemy Clone (Tower Defense) (Need HELP!)
Hi, if you are thinking of a minimum distance to detect enemies(field of view) you might create a clone being a circled ghosted with the radius you want so when a it touches the cloned enemy it or the cloned enemy checks the direction in between, assumig that enemies are moving across the terrain.
Last edited by asivi (May 16, 2017 18:38:26)
- gtoal
-
1000+ posts
Automatically shooting at closest Enemy Clone (Tower Defense) (Need HELP!)
That's an interesting sort of thing to me, trading efficient code for ease of understanding.
It's also a question of when and how much optimisation to put into a project. When I write something I'll usually do the first implementation using the stupidest(*) algorithms - for example if I need to look something up in a table, I'll write a custom block to do the lookup, but all it will be is a simple loop and a comparison. Then later if the code runs slowly, I might replace that linear lookup with a binary search. The main thing is to use an interface that allows you to switch algorithms without needing to recode other parts of the program.
Most times it'll turn out that the ‘dumb’ algorithm is actually good enough, since modern machines are so fast. As long as you can respond in 1/30th of a second (for animated stuff) or about 1/10 of a second for anything that completely replaces what's on screen, then it's fast enough…
G
*: The other thing about the ‘stupid’ algorithm is that it is so obvious that you can be reasonably confident that it is bug free.
- Birdlegs
-
1000+ posts
Automatically shooting at closest Enemy Clone (Tower Defense) (Need HELP!)
I tend not to go for that model of development because I work on a Chromebook, and I like my games to be able to run on a wide range of computers, so it's important to me that I can get each game as optimized as I can reasonably hope without sacrificing too much of what I want to do (I recently put in a water splash particle effect, for instance, just because it makes the game feel better, but I also made it as easy as I could for the computer to run)
- rpglurker
-
100+ posts
Automatically shooting at closest Enemy Clone (Tower Defense) (Need HELP!)
You could use a voting algorithm where the sprites vote on who is closest in response to a broadcast…It is basically the same algorithm that is used to route traffic on a network… There are many examples available online. If you need more help coding, I would be happy to assist…. It does feel oddly ironic to have sprites voting on who should be shooting them, but it should work
… (It will depend on how quickly you can get and process responses (limit to those within "range)

- DomKat1372
-
10 posts
Automatically shooting at closest Enemy Clone (Tower Defense) (Need HELP!)
I still don't understand any of this
- cs4463935
-
8 posts
Automatically shooting at closest Enemy Clone (Tower Defense) (Need HELP!)
You could just make it so that when you click a clone, all tower in range shoots at it, the way is by making it so that if you click a clone, make an invisible smaller version of the clone in the clone so that turrets will hit the clone as the invisible clone cant be shot as its smaller, also make it so that the invisible clone follows the clone you are targetting
- TaiterTotJ
-
1 post
Automatically shooting at closest Enemy Clone (Tower Defense) (Need HELP!)
As drmcw said, the easiest way to understand (And it's kinda hard, still!) would be putting their distances into lists, so I'll try and explain it to you so that it's easy. This won't be necessarily the most efficient way–I just want to make it easy
Okay, so first you're going to need a list that contains the X positions of every clone and the Y positions of every clone
Now, when you make a clone of a sprite, it gets its own copy of the sprite's “for this sprite only” variables. This will come in handy for making a sort of “clone ID.” The original sprite can have a for-this-sprite-only variable, which we can just call “CloneID”
The purpose of this variable is for each clone to remember what point in the lists it's X and Y positions go in.
The first clone, for instance, will have a CloneID of 1, and so will put its position into the first slot in the list, and so on.
Here's something to visualize what we have so farchange [CloneID v] by (1)Note that the above should only be run by the original sprite–not its clones
create clone of [Enemy v] // Be wary of "Create clone of myself," because then you can get clones of clones
Now…when I start as a clone
add (x position) to [Xpositions v] // These two ensure that there's a space in each list at the proper place for each clone.
add (y position) to [Ypositions v]
forever
Whatever AI scripts you're using
replace item (CloneID) of [Xpositions v] with (x position) // Replaces the data we just put in
replace item (CloneID) of [Ypositions v] with (y position)
end
It's important to clear out the lists and set CloneID back to zero when the flag is clicked, of course.
Now what we have is a number of positions the tower could be pointing toward on each given frame, but it needs to decide which one is closest, and how to point to it. For this, we need to be able to control list data well.
Each tower should have a “for this sprite only variable” you could call “i.” This is a common name for list-reading variables. All we need is to set “i” to one, the first spot in the list, and go over every value in the lists to find which ones represent the closest enemy's position.
To do this, we first need to check the first value in “Xpositions,” subtract that from the tower's own x position and take the absolute value, and add that to the absolute value of the first value in “Ypositions” subtracted from the tower's y position, which will give us a value akin to what the (distance to ) block would give us, if only we could use it! We then need to store that value, along with where it was in the list, so that we can compare it to the next value (And then the next, and so on) and remember where in the list it was. If the next value is less than the previous, we can just replace the data in those variables, because we know the first enemy was already further away than the second.forever
set [i v] to [1]
set [i of SmallestDistance v] to [1]
set [SmallestDistance v] to (([abs v] of (x position) - (item (i) of [Xpositions v])) + ((abs of (y position) - (item (i) of [Ypositions v]))
repeat (length of [Xpositions v] :: list) // We could use the length of either list, since they'll have the same length
if <(([abs v] of (x position) - (item (i) of [Xpositions v])) + ((abs of (y position) - (item (i) of [Ypositions v])) < (SmallestDistance)> then
set [SmallestDistance v] to (([abs v] of (x position) - (item (i) of [Xpositions v])) + ((abs of (y position) - (item (i) of [Ypositions v]))
set [i of SmallestDistance v] to (i)
end
change [i v] by (1)
end
end
Now, by the end of that script, (SmallestDistance) will equal the distance to the closest enemy, and (i of SmallestDistance) will tell us where that enemy is storing its list data (That enemy's “CloneID,” actually!) Now you can set some more variables for simplicity:set [ClosestEnemy's X v] to (item (i of SmallestDistance v) of [Xpositions v] :: list)
set [ClosestEnemy's Y v] to (item (i of SmallestDistance v) of [Ypositions v] :: list)
We're almost done. The tower knows where the closest enemy is. It just needs to point there. For that, we need right triangles!
But that's as far as I can take you with that–I was toying around with it in the editor, and I can't work out the exact trig functions for getting angle. I hope someone else can help!
Oh, and to speed up the list-reading process, it should be done as a custom block with “run without screen refresh” checked.
sure helpful for me
- samurai_master123
-
100+ posts
Automatically shooting at closest Enemy Clone (Tower Defense) (Need HELP!)
You don't get it, all the enemies are also clones and you can't pick one to shoot at because they are all clones of one sprite. try thiswhen green flag clicked
forever
wait (0.1) secs
point towards [enemy]
create clone of [myself]
when I start as a clone
switch costume to [bullet]
forever
move (10) steps
if <<touching [enemy] ?> or <touching [edge] ?>> then
delete this clone
end
end
- Discussion Forums
- » Help with Scripts
-
» Automatically shooting at closest Enemy Clone (Tower Defense) (Need HELP!)