How to prevent spawned objects from overlapping?

This code spawns several aircraft on the screen in random x,y positions.

How can I modify it to ensure that the objects never overlap each other?

1
2
3
4
5
6
7
8
9
10
11
12
local mapRightBoundary = display.contentWidth
local mapBottomBoundary = display.contentHeight
 
local phantomAircraft = {}
 
for i=1,5 do
        phantomAircraft[i] = display.newImage("airplane.png")
        
                                
        phantomAircraft[i].x = math.random (0, mapRightBoundary)
phantomAircraft[i].y = math.random (0, mapBottomBoundary)                       
end 

Here you go. This should work.. Note that this will fail if no. of images you are trying to spawn is big.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
local mapRightBoundary = display.contentWidth
local mapBottomBoundary = display.contentHeight
 
local phantomAircraft = {}
 
local abs = math.abs 
local random = math.random
 
local function checkOverlap(obj1, obj2) --returns true if obj1 and obj2 are overlapping
        local xdiff = abs(obj2.x - obj1.x)
        local ydiff = abs(obj2.y - obj1.y)
        
        local w1 = obj1.width
        local w2 = obj2.width
        local h1 = obj1.height
        local h2 = obj2.height
        
        if xdiff < (w1+w2)*0.5  and ydiff < (h1+h2)*0.5 then
                return true
        else
                return false
        end
end
 
local adjust
 
function adjust(obj, tbl)  -- adjusts position of obj such that it doesn't overlap with any object in table tbl
        for i = 1, #tbl do
                if checkOverlap(obj,tbl[i]) then
                        obj.x = random (0, mapRightBoundary)
                        obj.y = random (0, mapBottomBoundary)
                        adjust(obj,tbl)
                end
        end
end
 
for i=1,10 do
        local tempImg = display.newImage("airplane.png")
        
        tempImg.isVisible = false
        tempImg.x = random (0, mapRightBoundary)
        tempImg.y = random (0, mapBottomBoundary)
        
        adjust(tempImg,phantomAircraft)
        
        phantomAircraft[i] = tempImg
        phantomAircraft[i].isVisible = true 
        tempImg = nil 
        
end 

Awesome, thank!

views:1006 update:2011/10/5 21:23:48
corona forums © 2003-2011