Advertisement
Theshadow989

Draggable Text

Jul 7th, 2016
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.25 KB | None | 0 0
  1. local text_objects = { --All of our text objects
  2.   [1] = { --Layer by layer: it's necessary to do this in seqential order if we want to draw things correctly
  3.     text = "Layer 1",
  4.     color=colors.orange,
  5.     x1=1,
  6.     y =1
  7.   },
  8.   [2] = {
  9.     text=" Layer 2",
  10.     color=colors.blue,
  11.     x1=1,
  12.     y=2
  13.   },
  14.   [3] = {
  15.     text= "Layer 3",
  16.     color=colors.green,
  17.     x1=1,
  18.     y=3
  19.   },
  20.   [4] = {
  21.     text="Layer 4",
  22.     color=colors.cyan,
  23.     x1=1,
  24.     y=3
  25.   }
  26. }
  27.  
  28. local function draw() --The main draw function
  29.   term.setBackgroundColor(colors.black)
  30.   term.clear()
  31.   for index=#text_objects, 1, -1 do --Start at 4, goto 1
  32.     local ref=text_objects[index] --Our "pointer" to the text object
  33.     ref.x2 = ref.x1+#ref.text --The rightermost boundary of the text object
  34.     term.setBackgroundColor(ref.color)
  35.     term.setCursorPos(ref.x1, ref.y)
  36.     term.write(ref.text)
  37.   end
  38. end
  39.  
  40. local function checkClick(x,y) --Check if we have actually clicked on something
  41.   for index=1, #text_objects do --We can start at 1 and goto 4 now because layer 1 is on top
  42.     local ref=text_objects[index] --Our reference again
  43.     if x>=ref.x1 and x<=ref.x2 and y==ref.y then --Check to see if the click is inside of the boundaries
  44.       return index --If it is, then return the index
  45.     end
  46.   end
  47.   return false --Looks like nothing matched. Return false
  48. end
  49.  
  50. local function moveTextObject(index, clickX, dragX, dragY) --Move the text object to a new position
  51.   local ref = text_objects[index]
  52.   ref.x1 = ref.x1 + (dragX-clickX) --Make sure that we don't have jumping text objects!
  53.   ref.y = dragY
  54. end
  55.  
  56. local selector = {false} --All of the data about the "selected" text object
  57. while true do
  58.   draw() --Draw first so we can see what we're clicking
  59.   local e = {os.pullEvent()}
  60.   if e[1] == "mouse_click" then
  61.     selector = {checkClick(e[3], e[4]), e[3]} --Get the data about the click and store it inside of selector
  62.   elseif e[1] == "mouse_drag" then
  63.     if selector[1] then
  64.       moveTextObject(selector[1], selector[2], e[3], e[4]) --Move the text object if there selector[1] ~= false or nil
  65.       selector[2] = e[3] --Since we've moved the text object, our old clickX will no longer apply so we have to set it to the dragX
  66.     end
  67.   end
  68. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement