gpt4 book ai didi

android - 在 Corona SDK 中,如何将我的局部变量转换为全局变量?

转载 作者:行者123 更新时间:2023-12-01 16:39:01 24 4
gpt4 key购买 nike

我想转换 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在下一个函数中,我收到一条错误消息:

attempt to index global 'line'(a nil value):


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

如果有人可以提供帮助,我将不胜感激。

最佳答案

您可以在创建行时添加事件监听器,而不是从单独的函数中添加。
如果您需要对线路何时响应碰撞以及何时不响应进行额外控制,您可以通过物理体的一些标志来执行此操作。 (我从未使用过物理模块)

关于android - 在 Corona SDK 中,如何将我的局部变量转换为全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25954083/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com