在触摸和运行时,将在blank.png (800X800)上绘制不同大小的圆圈。在触摸时,坐标(触摸运行时x轴和y轴坐标的位置)将存储在began中的两个变量myCoordx和myCoordy中。当用户在屏幕上移动手指时,将根据计算出的半径和坐标绘制圆。现在错误一直出现。请帮我调试这段代码。
Runtime error
d:\corona projects\enterframeevent\main.lua:14: attempt to index global 'drawCircle' (a nil value)
stack traceback:
d:\corona projects\enterframeevent\main.lua:14: in main chunk这是我的main.lua文件。
local screen = display.newImage( "blank.png")
function drawCircle:touch(event)
if event.phase == "began" then
local myCoordx = event.x
local myCoordy = event.y
elseif event.phase == "moved" then
local rad = (event.x - myCoordx) ^ 2
local myCircle = display.newCircle(event.x, event.y, rad )
myCircle:setFillColor( 1, 0, 1 )
end
end
Runtime:addEventListener( "touch", drawCircle )发布于 2014-10-02 20:30:59
显然,您试图将:touch方法添加到drawCircle中,但是您没有在任何地方定义它。你应该至少把它初始化到一个空表中--比如{}或者使用相关的Corona方法来创建它。
发布于 2014-10-03 22:41:54
我认为你可以这样做:
-- I think you should define these outside the function
-- since they'll be out of scope in the "moved" phase
local myCoordx = 0
local myCoordy = 0
-- Moved this declaration outside the function
-- so it can be reused, and removed
local myCircle
function onTouch(event)
if event.phase == "began" then
myCoordx = event.x
myCoordy = event.y
elseif event.phase == "moved" then
local rad = (event.x - myCoordx) ^ 2
-- Keep in mind that this line will draw a new circle everytime you fall into the "moved" phase, keeping the old one
-- if i understood well, this is not what you want
-- local myCircle = display.newCircle(event.x, event.y, rad )
-- Try this instead, removing the old display object...
if myCircle then
myCircle:removeSelf()
myCircle = nil
end
-- ...and adding it again
myCircle = display.newCircle(event.x, event.y, rad )
myCircle:setFillColor( 1, 0, 1 )
end
end
-- Since "drawCircle" is not defined, point it directly to a function (in this case, "onTouch")
-- Runtime:addEventListener( "touch", drawCircle )
Runtime:addEventListener( "touch", onTouch )我没有机会在模拟器上测试代码,我会稍后尝试,并在需要时更新答案。
更新:对它进行了测试,它的工作情况和我预期的一样。
发布于 2014-10-05 10:25:25
根据我的评论,发布的代码不能写,或者错误消息是错误的。我假设错误是错误的,因为第3行的语句function drawCircle:touch(event)试图向drawCircle表添加一个名为touch(self)的方法;但是代码并没有在任何地方创建这个表。您可能缺少drawCircle = display.newSomething...,或者您可以简单地使用函数而不是方法:
function touch(event)
...
end
Runtime:addEventListener( "touch", touch)后者之所以有效,是因为您的触摸函数没有使用关键字self,它是为方法隐式创建的变量。
https://stackoverflow.com/questions/26158306
复制相似问题