Page 1 of 1
Click and Drag with Z-order
Posted: Fri Apr 07, 2017 1:17 pm
by herrinbleu
At the moment, I have several objects overlapping each other and when I click and drag, overlapping objects are all moved.
Code: Select all
function dragging_detect(x, y, button)
for i,v in ipairs(objects) do
if x > v.x and x < v.x + v.width
and y > v.y and y < v.y + v.height then
v.dragging.active = true
v.dragging.diffX = x - v.x
v.dragging.diffY = y - v.y
end
end
end
How should I make it such that only the top object is moved?
And also, how can I allow objects clicked to be moved to the top of the z order?
Re: Click and Drag with Z-order
Posted: Fri Apr 07, 2017 2:07 pm
by zorg
herrinbleu wrote: ↑Fri Apr 07, 2017 1:17 pm
At the moment, I have several objects overlapping each other and when I click and drag, overlapping objects are all moved.
-- Code was here...
How should I make it such that only the top object is moved?
And also, how can I allow objects clicked to be moved to the top of the z order?
Hi and welcome to the forums!
First, let's assume that your objects table is already z-sorted (1==top, #objects==bottom), in which case you only need to do the following small edit:
Code: Select all
function dragging_detect(x, y, button)
for i,v in ipairs(objects) do
if x > v.x and x < v.x + v.width
and y > v.y and y < v.y + v.height then
v.dragging.active = true
v.dragging.diffX = x - v.x
v.dragging.diffY = y - v.y
-- In lua, the below code works, you don't need any temporary variable to store one of them.
objects[1], objects[i] = objects[i], objects[1]
-- And we break so we don't process any other object.
break
end
end
end
This is the simplest solution, although it reorders the objects a bit (swaps the top object with the one the click was registered with, regardless of its x and y position), a bit better solution would be to move the selected to the top, and slide all the objects that were above it by 1.
Re: Click and Drag with Z-order
Posted: Sat Apr 08, 2017 4:40 am
by herrinbleu
Thanks for the quick reply!! I managed to figure out how to work around it with another method..
Code: Select all
function dragging_detect(x, y, button)
for i,v in ipairs(objects) do
if x > v.x and x < v.x + v.width
and y > v.y and y < v.y + v.height then
v.dragging.active = true
v.dragging.diffX = x - v.x
v.dragging.diffY = y - v.y
-- Instead of break, I used return. I'm not sure if there's a difference.
return
-- This allows the objects to slide by 1.
top = objects[i]
table.remove(objects, i)
table.insert(objects, top)
end
end
Re: Click and Drag with Z-order
Posted: Sat Apr 08, 2017 9:25 am
by zorg
Yep, that looks workable too!
The difference between break and return is that break would only break out of the for loop, and the code would continue below that block; return exits the whole function.