This is a read-only archive of the old Scratch 1.x Forums.
Try searching the current Scratch discussion forums.

#1 2012-02-24 00:26:44

RedAlertFan
New Scratcher
Registered: 2011-01-21
Posts: 6

Finding smallest distance between several objects

I need to find the object with the smallest distance out of 14 others to one object, but they constantly move, and the script must recalculate the minimum distance constantly. I cannot figure out how.

Offline

 

#2 2012-02-24 01:05:17

Magnie
Scratcher
Registered: 2007-12-12
Posts: 1000+

Re: Finding smallest distance between several objects

http://scratch.mit.edu/projects/Magnie/718306, it detects which one is closest to the center.

You can probably put a forever loop around it so it'll continue to detect the closest one.

Offline

 

#3 2012-02-24 06:27:11

RedAlertFan
New Scratcher
Registered: 2011-01-21
Posts: 6

Re: Finding smallest distance between several objects

Thanks. Is there a way to use that information to make it point to the closest one?

Offline

 

#4 2012-02-24 06:48:05

LS97
Scratcher
Registered: 2009-06-14
Posts: 1000+

Re: Finding smallest distance between several objects

RedAlertFan wrote:

Thanks. Is there a way to use that information to make it point to the closest one?

Once you know which sprite is closest, you can use the following simple block:

point towards (closest sprite name)
or
if <(name) = [a]>
point towards[a v]
else
point towards [b v]
end
depending on your needs...

Include it in the forever loop after the closest sprite has been calculated  smile

Last edited by LS97 (2012-02-24 06:49:43)

Offline

 

#5 2012-02-24 12:55:01

Smozzick
Scratcher
Registered: 2011-10-23
Posts: 100+

Re: Finding smallest distance between several objects

Pythagoras theorem

c^2 = a^2 + b^2

Put the names of the sprites in a list called sprites (or anything, really) with the exception of the sprite you are comparing to.


Forever
set (ShortestDistance) to [1000]
set (Counter) to [0]
Repeat [13]
change (counter) by [1]
set (DistanceX) to <[abs v] of <([x position v] of (item (counter) of [Sprites v])) - ([x position v] of [sprite v])>>
set (DistanceY) to <[abs v] of <([y position v] of (item (counter) of [Sprites v])) - ([y position v] of [sprite v])>>
set (DistanceXSq) to <(DistanceX) * (DistanceX)>
set (DistanceYSq) to <(DistanceY) * (DistanceY)>
if <[<[sqrt v] of <(DistanceXSq) + (DistanceYSq)>>] < [(ShortestDistance)]>
set (ShortestDistance) to <[sqrt v] of <(DistanceXSq) + (DistanceYSq)>>
set (ClosestSprite) to (Counter)
end
end

The text bits are temporary until I can fix em.

EDIT: It works.

Example project here.

Feel free to download it and view the scripts there, they probably will be more understandable and clear. I will add comments shortly.

Also feel free to use the script if you want to.

Last edited by Smozzick (2012-02-24 13:14:24)


http://i50.tinypic.com/ded8m.png

Offline

 

Board footer