View difference between Paste ID: yWNxBRu0 and zVqGJSQX
SHOW: | | - or go back to the newest paste.
1
local dragTargets = {}
2
3
local testWell = display.newRect(0, 0, 60, 60)
4
testWell:setFillColor(0xFF, 0x00, 0x00)
5
testWell.x, testWell.y = display.contentWidth / 2, display.contentHeight * 0.25
6
7
function testWell:touch(event)
8
	local carry = dragTargets[event.id]
9
	if event.phase == "ended" and carry then
10
		carry:Drop(self.x, self.y)
11
		self:setFillColor(0x00, 0x00, 0xFF)
12
		return true
13
	end
14
end
15
testWell:addEventListener('touch', testWell)
16
17
local testDrag = display.newCircle(0, 0, 28)
18
testDrag:setFillColor(0x00, 0xFF, 0x00)
19
testDrag.x, testDrag.y = display.contentWidth / 2, display.contentHeight * 0.75
20
21-
function testDrag:Drop(x, y)
21+
local function dropDraggable(self, x, y)
22
	self.oldX, self.oldY, self.id = nil
23
	self.x, self.y = x or self.x, y or self.y
24
	dragTargets[self], dragTargets[self.id] = nil
25
	Runtime:removeEventListener('touch', self)
26
end
27
28-
function testDrag:touch(event)
28+
local function trackDrag(self, event)
29
	if event.id == self.id then
30
		if event.phase == "moved" then
31
			self.x, self.y = event.x, event.y
32
		elseif event.phase == "ended" then
33
			self:Drop(self.oldX, self.oldY)
34
		end
35
	end
36
end
37
38-
function startDrag(event)
38+
local function startDrag(event)
39
	local id, target = event.id, event.target
40
	if event.phase == "began" then
41
		dragTargets[id], dragTargets[target] = target, id
42
		target.id = id
43
		target.oldX, target.oldY = target.x, target.y
44
		Runtime:addEventListener('touch', target)
45
		return true
46
	end
47
end
48
49-
testDrag:addEventListener('touch', startDrag)
49+
function makeDraggable(object)
50
	object.touch = trackDrag
51
	object.Drop = dropDraggable
52
	object:addEventListener('touch', startDrag)
53
	return object
54
end
55
56
makeDraggable(testDrag)