2014-10-02 27 views
0

可在触摸和运行时在blank.png(800 X 800)上绘制可变尺寸的圆形。触摸时,坐标(触摸时运行时的x轴和y轴坐标位置)将存储在两个变量myCoordx和myCoordy开始事件中。当用户在屏幕上移动他/她的手指时,将根据计算出的半径和坐标绘制圆圈。现在错误不断出现。请帮我调试这段代码。如何使用Lua在触摸时绘制可变尺寸的圆形

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) 
+0

您发布的代码有两个原因是不对的:第14行指向'Runtime'之前的'end'。错误消息可能在第16行,但第3行会首先引起问题。请编辑您的帖子,将实际的代码示例与您能够重现该错误的代码示例相对比,并更新错误消息。 – Schollii 2014-10-05 02:20:54

回答

0

显然试图:touch方法添加到drawCircle,但你没有任何地方定义它。您应该将其初始化为至少一个空表 - 即{}或使用相关的电晕法来创建它。

0

我想你可以像这样的东西去:

-- 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) 

没得上测试模拟器上的代码的机会,我会稍后再试,如果需要更新的答案。

更新: 测试它,它的工作原理与我预期的一样。

0

根据我的评论,发布的代码无法写入,或错误信息是错误的。我会假设错误是错误的,因为第3行的语句function drawCircle:touch(event)尝试将一个名为touch(self)的方法添加到drawCircle表中;但代码不会在任何地方创建此表。您是丢失drawCircle = display.newSomething...,或者你可以简单地用一个函数不是方法:只

function touch(event)  
    ... 
end 

Runtime:addEventListener("touch", touch) 

后者的作品,因为你的触摸功能不使用关键字self,这是方法隐式创建变量。