如果之前有人问过道歉,我试着搜索无济于事。无论如何,我有一些逻辑错误,当我试图移动它时,阻止我的玩家对象左右移动。任何提示都会受到赞赏,因为我是Lua的初学者。感谢您的时间。
function spawnPlayer()
player = display.newImage('player.png')
player.x = display.contentWidth * 0.5
player.y = display.contentHeight - player.height
player.name = 'player'
physics.addBody(player)
Score()
end
function Score()
score = display.newText('Score: ', 1, 0, native.systemFontBold, 14)
score.x = _W / 9
score.y = 0
score.text = score.text .. tostring(intscore)
Listeners('add')
end
function Listeners(event)
if event == 'add' then
--Runtime:addEventListener("accelerometer", accelPlayer)
--player:addEventListener("touch", touchPlayer)
player:addEventListener('touch', touchPlayer)
player:addEventListener('accelerometer', accelPlayer)
elseif event == 'remove' then
Runtime:removeEventListener("accelerometer", accelPlayer)
player:removeEventListener("touch", touchPlayer)
end
end
function touchPlayer:touch(event)
if isSimulator then
if event.phase == "began" then
moveX = event.x - player.x
elseif event.phase == "moved" then
player.x = event.x - moveX
end
if((player.x - player.width * 0.5) < 0) then
player.x = player.width * 0.5
elseif((player.x + player.width * 0.5) > display.contentWidth)
then
player.x = display.contentWidth - player.width * 0.5
end
end
end
function accelPlayer:accelerometer(event)
player.x = display.contentCenterX - (display.contentCenterX * (event.yGravity * 3))
if((player.x - player.width * 0.5) < 0) then
player.x = player.width * 0.5
elseif((player.x + player.width * 0.5) > display.contentWidth)
then
player.x = display.contentWidth - player.width * 0.5
end
end
答案 0 :(得分:1)
尝试
print("in touch event")
if isSimulator then
if event.phase == "began" then
print("touch started")
startX = event.x
elseif event.phase == "moved" then
local changeSinceLast = event.x - startX
player.x = player.x + changeSinceLast
startX = event.x
print("touch moved")
end
<强>更新强>
如果没有打印任何内容,那么你必须查看导致touchPlayer:touch(event)
被调用的内容。它是Listeners('add')
。此外,该函数有touchPlayer
,但调用此函数时是否存在touchPlayer?所以试试:
function Listeners(event)
if event == 'add' then
print('adding touch listener:', touchPlayer)
player:addEventListener('touch', touchPlayer)
答案 1 :(得分:0)
因为您没有在设备上分配触摸侦听器。您已为模拟器分配了触摸侦听器,您无法在模拟器上测试触摸事件。 因此,也要为设备分配,并在开始条件下添加以下行。
display.getCurrentStage():setFocus(event.target)