Hello, Can I ask a question
I wanna make a bar with buttons ,and the button can be dragged.
when you drag the button , it will generate a new object also can be dragged.
Like the Plants vs. Zombies
How can I do that?
Here is a quick example of something that works… just to give you an idea to work on and build from. There would be several things I would change if I was doing this for myself … this is just to illustrate one way.
You will have to replace the image paths I have in this code and the sizes and positions ( I have hard coded in here) as my config lua has width 1080, height 1920.
-- each tower created will have a sequential id
local objInc = 1
local icon1, icon2
local iconSz = 100
local baseX1 = 200
local baseY1 = 200
local baseX2 = 400
local baseY2 = 200
-- ASSUME A TOWER DEFENSE PLACEMENT AREA, PLACEMENT BLOCK etc..
-- THAT THE TOWERS NEED TO BE PLACED IN; in this case a large area
local pb = display.newRect(MID_W, H * .7, 800, 800)
local function pointInRect( pointX, pointY, _img )
local left = _img.x - (_img.width/2)
local top = _img.y - (_img.height/2)
if pointX >= left and pointX <= left + _img.width and pointY >= top and pointY <= top + _img.height then
return true
else
return false
end
end
local function makeObj(params)
local obj
if params.towerType == 1 then
obj = display.newImageRect("Textures/UI/act_itemsBtn.png", iconSz, iconSz)
obj.baseX = baseX1
obj.baseY = baseY1
elseif params.towerType == 2 then
obj = display.newImageRect("Textures/UI/act_jumpBtn.png", iconSz, iconSz)
obj.baseX = baseX2
obj.baseY = baseY2
end
obj.towerType = params.towerType
obj.x = obj.baseX
obj.y = obj.baseY
obj.isLive = false
function obj:touch(e)
if e.phase == "began" then
display.getCurrentStage():setFocus( e.target )
self.oldX = self.x
self.oldY = self.y
self.hasFocus = true
elseif self.hasFocus then
if e.phase == "moved" then
self.x = (e.x - e.xStart) + self.oldX
self.y = (e.y - e.yStart) + self.oldY
elseif e.phase == "ended" or e.phase == "cancelled" then
if pointInRect(self.x, self.y, pb) == false then
print(" NOT IN PLACEMENT AREA !!! ")
self.x = obj.baseX
self.y = obj.baseY
else
-- make a new obj, placing it on top of the icon
-- for next time an obj needs to be created
if self.isLive == false then
obj.id = objInc
objInc = objInc + 1
makeObj({towerType = obj.towerType})
self.isLive = true
end
end
display.getCurrentStage():setFocus(nil)
self.hasFocus = false
print(" obj self.id " , self.id)
end
end
return true
end
obj:addEventListener("touch", obj)
end
icon1 = display.newImageRect("Textures/UI/act_itemsBtn.png", iconSz, iconSz)
icon1.x = baseX1
icon1.y = baseY1
makeObj({towerType = 1})
icon2 = display.newImageRect("Textures/UI/act_jumpBtn.png", iconSz, iconSz)
icon2.x = baseX2
icon2.y = baseY2
makeObj({towerType = 2})
Hope this helps!
Best of luck!