Lua(Corona SDK)中的面向对象编程和事件监听器

我的Corona SDK第一步和第一个问题。试图制作两个可以移动的方块,按照此OOP教程,但这不起作用。我成功地创建了两个盒子,但只有一个是可移动的。当我尝试移动另一个时,它不会移动,但第一个会移动。我想可能是作用域的问题,但无法确定确切的位置。谢谢任何帮助。

tile.lua源代码:

模块(…,包.看到全部)

function new(initX,initY)

    显示阶段宽度=显示.stageWidth
显示阶段高度=显示.stageHeight
正方形大小 =(scrnWidth * 0.9)/ 4

   本地瓷砖 =显示.newRect(initY,initY,squareSize,squareSize)

   function move(direction)
       如果方向==“左”则
            过渡.moveTo(tile,{x = tile.x + squareSize,y = tile.y,时间 = 200elseif direction == “right” then
         过渡.moveTo(tile, {x = tile.x - squareSize,y = tile.y,时间 = 200})
    elseif 方向==“上”则
          过渡.moveTo(tile,{x = tile.x,y = tile.y-squareSize,时间 = 200elseif 方向==“下”则
            过渡.moveTo(tile,{x = tile.x,y = tile.y + squareSize,时间 = 200end
   end

功能瓷砖:触摸事件(事件)
        如果事件.阶段==“开始”则
            显示.getCurrentStage():setFocus(tile )
                开始X =事件.X
                beginY =事件.Y
        end

        如果事件.阶段==“结束”然后
                结束X =事件.X
                endY =事件.Y
            显示.getCurrentStage():setFocus(nil)

                检查滑动方向();
        end
    end

函数checkSwipeDirection()

        xDistance =  math.abs(endX - beginX) -数学。abs将返回给定值的绝对值或非负值。
        yDistance =  math.abs(endY - beginY)

        如果XDistance> YDistance then
                如果beginX> endX then
                         move(“right”,瓷砖)
                else
                       move(“left”,瓷砖)

                end
        else
                如果beginY> endY then
                         move(“up”,瓷砖)
                else
                         move(“down”,瓷砖)
                end
        end

end

tile:addEventListener(“touch”,tile)
   返回瓷砖

end

我在main.lua中使用以下代码创建对象:

    localrequire(“tile”)
    local tile1 = tileConst.new(100,100local tile2 = tileConst.new(200,200
点赞
用户1979583
用户1979583

在你的 tile.lua 场景中,在 module (..., package.seeall) 下方声明一个变量来保存触摸的精灵:

local touchedSprite -- 我的临时精灵变量

然后在以下函数中将目标精灵分配给上述变量:

function tile:touch(event)
    touchedSprite = event.target -- 分配目标到变量
    ...
end

现在按照如下方式更改 move 函数:

function move(direction)
  if direction == "left" then
    transition.to(touchedSprite, {x = touchedSprite.x+squareSize,y = touchedSprite.y,time = 200})
  elseif direction == "right" then
    transition.to(touchedSprite, {x = touchedSprite.x-squareSize,y = touchedSprite.y,time = 200})
  elseif direction == "up" then
    transition.to(touchedSprite, {x = touchedSprite.x,y = touchedSprite.y-squareSize,time = 200})
  elseif direction == "down" then
    transition.to(touchedSprite, {x = touchedSprite.x,y = touchedSprite.y+squareSize,time = 200})
  end
end

请注意,我已将 transition.moveTo 更改为 transition.to,并将你的 transition tile 更改为 touchedSprite(target).

继续编码.................. :)

2014-01-09 21:03:06