我想把local line
转换成一个全局变量,以便以后可以引用它
local physics = require "physics"
physics.start()
local line
lineGroup = display.newGroup()
local prevX,prevY
local isDrawing = false
local i = 0
local function distanceBetween(x1, y1, x2, y2)
local dist_x = x2 - x1
local dist_y = y2 - y1
local distanceBetween = math.sqrt((dist_x*dist_x) + (dist_y*dist_y))
return distanceBetween
end
local function drawLine(e)
if(e.phase == "began") then
if(line) then
lineGroup:remove(1)
line = nil
end
prevX = e.x
prevY = e.y
isDrawing = true
elseif(e.phase == "moved") then
local distance = distanceBetween(prevX, prevY, e.x, e.y)
if(isDrawing and distance < 100) then
if(line) then lineGroup:remove(1) end
line = display.newLine(prevX, prevY, e.x, e.y)
line:setStrokeColor( 0.5,0,1 )
line.strokeWidth = 5
local dist_x = e.x - prevX
local dist_y = e.y - prevY
physics.addBody(line, "static", { density = 1,
friction = 0.5,
bounce = 2,
shape = {0, 0, dist_x, dist_y, 0, 0} } )
lineGroup:insert(line)
end
elseif(e.phase == "ended") then
isDrawing = false
end
end
Runtime:addEventListener("touch",drawLine)
每当我试图在下一个函数中引用line
时,我都会收到一条错误消息,上面写着:
尝试索引全局"行"(零值):
function onCollision(e)
audio.play(bounceSnd)
score.text = tostring(tonumber(score.text) + 1)
score.x = 300
end
gameListeners('add')
end
function gameListeners(action)
if(action == 'add') then
line:addEventListener( 'collision', onCollision )
else
line:addEventListener( 'collision', onCollision)
end
end
如果有人能帮忙,我将不胜感激。
您可以在创建行时添加事件侦听器,而不是从单独的函数中添加。如果你需要额外的控制线何时对碰撞做出反应,何时不对,你可能可以通过物理体的一些标志来做到这一点。(我从未使用过物理模块)
这看起来好像没有mydata.loa文件。我知道在这些例子中,他们经常使用这个引用,但如果你想使用它,你必须创建一个mydata.loa文件。这是一种他们用来创建全局对象的技术,该对象可以在不同的文件中引用。例如:
mydata.lua
local M = {}
M.someVariable = WhateverYouWant
return M
然后在任何你想访问mydata的文件中:
local mydata = require("mydata")
然后你可以在那个文件中使用它。