Distance between two objects

In almost any game you will need to calculate distance between two objects.
Let’s do it.

Ok, distance^2 = delta_x^2+delta_y^2

delta_x = object2.x-object1.x

delta_y = object2.y-object1.y

Result:

1
distance = math.sqrt((object2.x-object1.x)^2+(object2.y-object1.y)^2)

Sample of usage:

Code:

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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
-- calculate distance between o1 and o2
function distance(o1,o2)
return math.sqrt((o1.x-o2.x)^2+(o1.y-o2.y)^2)
end

-- check is point(p) in rect(r)
function is_in_rect(p, r)
if p.x>=r[1] and p.x=r[2] and p.y return true
end
return false
end

-- hide status bar
display.setStatusBar( display.HiddenStatusBar )

-- fill background
local bg = display.newRect(0,0, display.contentWidth, display.contentHeight)
bg:setFillColor(160, 230, 255)

-- create two objects
local object1 = display.newRect(100,100, 10,10)
local object2 = display.newRect(200,200, 10,10)

-- line between objectslocal
local line

-- distance label
local distance_lbl = display.newText("", 300,10, native.systemFont, 14)
distance_lbl:setTextColor(0,0,0)

-- run this function on touch
local function move_object(event)
local o1, o2 = object1, object2
local ro1 = {o1.x-o1.width/2, o1.y-o1.height/2, o1.x+o1.width/2, o1.y+o1.height/2}
local ro2 = {o2.x-o2.width/2, o2.y-o2.height/2, o2.x+o2.width/2, o2.y+o2.height/2}
if event.phase=="began" then
-- just began - check which object is touched and mark it
if is_in_rect(event, ro1) then
object1.moving = true
elseif is_in_rect(event, ro2) then
object2.moving = true
end
elseif event.phase=="moved" then
-- moving - move touched object
if object1.moving then
object1.x, object1.y = event.x, event.y
elseif object2.moving then
object2.x, object2.y = event.x, event.y
end
elseif event.phase=="ended" then
-- end - mark both objects as untouched
object1.moving, object2.moving = false, false
end
end

Runtime:addEventListener("touch", move_object)

-- calculate distance between objects and update distance label every 1/30 second
local function main_loop()
distance_lbl.text = distance(object1, object2)
if line then line:removeSelf() end
line = display.newLine(object1.x, object1.y, object2.x, object2.y)
end
Runtime:addEventListener("enterFrame", main_loop)

One thought on “Distance between two objects

  1. Just wanted to let you know of an issue on line 8….
    if p.x>=r[1] and p.x>=r[2] and p.y then return true
    is how it should read….

    Other than that it’s great thanks!!!!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>