i have 3 sprites in an array i know how to make it so uppon a button press a specific sprite is killed, but i need a way to kill the closest sprite to the player
Alright, @temmie , you can use the sprite utils extension and the sprite-data extension and use the distance from sprite to sprite block to check the distance between the sprites and then kill the closest one; like this:
And also, since you’re using an array make sure to remove the enemy from the array so you don’t cause any accidental null/undefined bugs!
I created a function that gets the closest sprite among a sprite array toward another sprite. Note that the sprite utils extension needs to be installed for it to work.
function getClosestInAnArray(spriteArray: Sprite[], sprite: Sprite) {
let closestDistance: number = 1/0
let currentSprite: Sprite = null
for (let spriteValue of spriteArray) {
let spriteDistance: number = spriteutils.distanceBetween(spriteValue, sprite)
if (spriteDistance < closestDistance) {
closestDistance = spriteDistance
currentSprite = spriteValue
}
}
return(currentSprite)
}
As a bonus, here’s a demo project:
Finding the closest sprite is actually quite complex. Something you will need first is the distance between block from the Sprite Utils extension. Then you will set the first sprite in the array to “the current closest” Now you must go through the array and see if the distance between the new sprite is less than the distance between the last closest one. Once you go through all of them checking in this way, the current closest will be the most closest.