如何使用Lua在触摸时绘制可变大小的圆圈

时间:2014-10-02 09:47:55

标签: lua corona

可变尺寸的圆圈将在触摸和运行时绘制在blank.png(800 X 800)上。触摸时,坐标(触摸时运行中的x轴和y轴坐标的位置)将存储在启动事件中的两个变量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 )

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分: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 )

没有机会在模拟器上测试代码,我会稍后再尝试并在需要时更新答案。

<强>更新 经过测试,它按预期工作。

答案 2 :(得分:0)

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

function touch(event)    
    ...
end

Runtime:addEventListener( "touch", touch)

后者的工作原理仅仅是因为您的触摸功能不使用关键字self,这是一个隐式创建的方法变量。