Search code examples
luacoronasdkmoai

Changing to display object position in corona


I am new to programming this question might sound very simple. I have created a object as a module called box

box = {}
m={}
m.random = math.random

function box:new(x,y)
     box.on=false
     local box = display.newRect(0,0,100,100)
     box:setFillColor(m.random(120,200),m.random(120,200),m.random(120,200))
     box.x = x
     box.y = y
     box.type = "box"


     return box
end


return box

in my main.lua I want to create as many boxes and ,like an adventure game how can I switch two of the boxes position,example I click on one of them,then it is selected,and simply I click on the other one and they change position with each other. Thanks in advance


Solution

  • I don't know Corona, but the general logic for what you're doing is this:

    • Add an event handler which allows you to detect when a box is clicked.
    • Add some way of tracking the selected box.
    • When a box is clicked:
      • if no box is yet selected, select the current box
      • if another box was previously selected, swap with the current box
      • if the already-selected box was clicked, ignore (or toggle off selected)

    General idea (not sure if this is valid Corona event handling, but should get you close):

    box = {}
    m={}
    m.random = math.random
    
    -- track the currently selected box
    local selected = nil
    
    function box:new(x,y)
         box.on=false
         local box = display.newRect(0,0,100,100)
         box:setFillColor(m.random(120,200),m.random(120,200),m.random(120,200))
         box.x = x
         box.y = y
         box.type = "box"
         function box:touch(event)
             if not selected then
                 -- nothing is selected yet; select this box
                 selected = self
                 -- TODO: change this box in some way to visually indicate that it's selected
             elseif selected == self then
                 -- we were clicked on a second time; we should probably clear the selection
                 selected = nil
                 -- TODO: remove visual indication of selection
             else
                 -- swap positions with the previous selected box, then clear the selection
                 self.x, self.y, selected.x, selected.y 
                     = selected.x, selected.y, self.x, self.y
                 selected = nil
             end
         end
         return box
    end