我在Corona SDK中的第一步和第一次麻烦。尝试按照this OOP教程创建两个可以移动的框,但这不起作用。我已成功创建了两个盒子,但只有一个是可移动的。当我试图移动另一个时,它没有移动,但第一个移动。猜猜范围有问题,但无法确定究竟在哪里。 谢谢你的帮助。
tile.lua源代码:
module (..., package.seeall)
function new(initX, initY)
local scrnWidth = display.stageWidth
local scrnHeight = display.stageHeight
local squareSize = (scrnWidth*0.9)/4
local tile = display.newRect( initY, initY, squareSize, squareSize )
function move(direction)
if direction == "left" then
transition.moveTo(tile, {x = tile.x+squareSize,y = tile.y,time = 200})
elseif direction == "right" then
transition.moveTo(tile, {x = tile.x-squareSize,y = tile.y,time = 200})
elseif direction == "up" then
transition.moveTo(tile, {x = tile.x,y = tile.y-squareSize,time = 200})
elseif direction == "down" then
transition.moveTo(tile, {x = tile.x,y = tile.y+squareSize,time = 200})
end
end
function tile:touch(event)
if event.phase == "began" then
display.getCurrentStage():setFocus( tile )
beginX = event.x
beginY = event.y
end
if event.phase == "ended" then
endX = event.x
endY = event.y
display.getCurrentStage():setFocus(nil)
checkSwipeDirection();
end
end
function checkSwipeDirection()
xDistance = math.abs(endX - beginX) -- math.abs will return the absolute, or non-negative value, of a given value.
yDistance = math.abs(endY - beginY)
if xDistance > yDistance then
if beginX > endX then
move("right",tile)
else
move("left",tile)
end
else
if beginY > endY then
move("up",tile)
else
move("down",tile)
end
end
end
tile:addEventListener("touch", tile)
return tile
end
我使用main.lua中的以下代码创建对象:
local tileConst = require("tile")
local tile1 = tileConst.new(100,100)
local tile2 = tileConst.new(200,200)
答案 0 :(得分:4)
在tile.lua
场景中,声明一个变量,以便在module (..., package.seeall)
下方保留触摸的精灵:
local touchedSprite -- my temporary sprite variable
然后将目标精灵分配给函数内的上述变量:
function tile:touch(event)
touchedSprite = event.target -- Assigning target to variable
...
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).
保持编码..................:)