I wrote a quick piece of code to help align objects to each other:
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 | local A = display.newRect(0,0,50,50) A:setFillColor(255,255,255) A.x,A.y = 90, 150 <code> local B = display.newRect(0,0,50,50) B:setFillColor(255,0,0) B.x,B.y = 150, 150 <code> local function onTouch(event) local t = event.target local phase = event.phase <code> if "moved" == phase then t.x = event.x t.y = event.y elseif "ended" == phase then if math.sqrt((A.x-B.x)^2) < 50 and math.sqrt((A.y-B.y)^2) < 20 then A.y = B.y elseif math.sqrt((A.y-B.y)^2) < 50 and math.sqrt((A.x-B.x)^2) < 20 then A.x = B.x end end end <code> A:addEventListener("touch",onTouch) |
Thanks for the optimizations! That was my first run through it, needless to say its more organized now, and better optimized (thanks to you).
Thanks for the input!
Jeff,
thanks for this example!
However, given, that such code is
- not natively executed but evaluated through a VM and
- we are using devices with limited resources only
it is wise to change the distance calculation a bit:
math.sqrt((A.x-B.x)^2) < 50(and similar) can (and should) be rewritten as
(A.x-B.x)^2 < 50*50(of course, you could - and should - even precalculate "50*50", but the explicit multiplication has been used here for clarity)
From a mathematical (better: numerical) viewpoint, both terms are identical - but the latter form does without a square root calculation. The difference might be neglectible within this example, but as soon as you do such calculations for a larger number of objects, you will experience a noticeable speed gain!
By the way: how does the iPhone perform IEEE calculations? Does it have hardware support for them? If not, you should even write
local Difference = A.x-B.x; if (Difference < 0) then Difference = -Difference; end;if (Difference < 50) ...in order to avoid the multiplication.
There are additional possibilities to optimize this code further, but that's a different issue.
Kind regards,
Andreas Rozek