Lua Love2d 写代码实例一次,多次使用,每个实例都是独一无二的。

我曾经问过一个类似的问题,但那是关于Processing.JS的。现在我正在用LOVE2D Lua做一些东西,我想要做的是有一个按钮,点击它可以在屏幕上添加一个圆。我已经有了代码,当我单击并按住圆时,我可以移动它。但是当我添加第二个圆时,它们都使用相同的变量。我希望这样只编写一次移动和添加圆的代码,但我可以多次调用它,并且每个都是独特的,而不需要编写预先考虑无限圆的代码。以下是我的代码:

obn = 0
ellipsex = 50
ellipsey = 50
ellipsew = 50
ellipseh = 50
ellipser = 255
ellipseg = 0
ellipseb = 0
function love.draw()
mousex, mousey = love.mouse.getPosition()
for i=0,obn,1 do
ellipse()
end
end

function love.mousereleased(x, y, button)
   if button == 2 then
      obn = obn + 1
   end

end

function love.update(dt)
if love.mouse.isDown(1) then
       if mousex > ellipsex and mousex < ellipsex + ellipsew and mousey > ellipsey and mousey < ellipsey + ellipseh then
ellipsex = mousex
ellipsey = mousey
end
end
end

function ellipse()

love.graphics.setColor(ellipser, ellipseg, ellipseb)
love.graphics.ellipse("fill", ellipsex, ellipsey, ellipsew, ellipseh)

end

但是,当我右键单击以添加圆形(增加循环运行的次数)时,它没有为我添加第二个圆形,以便我可以独立于第一个圆形移动。请帮忙?

点赞
用户5734275
用户5734275

我处理多个椭圆的方式是为每个椭圆创建一个表格,该表格保存它的属性和一个draw函数。

local ellipses = {} -- 将所有椭圆存储在一个表中

function create_ellipse(x,y,w,h,r,g,b)
    local ellipse = {
        x = x,
        y = y,

        w = w,
        h = h,

        r = r,
        g = g,
        b = b
    }

    function ellipse.draw()
        love.graphics.setColor(ellipse.r,ellipse.g,ellipse.b)
        love.graphics.ellipse("fill",ellipse.x,ellipse.y,ellipse.w,ellipse.h)
    end

    ellipses[#ellipses+1] = ellipse -- 将新的椭圆插入到椭圆表中

    return ellipse
end

function love.draw()
    for i = 1,#ellipses do
        ellipses[i].draw(); -- 调用每个椭圆的独立draw函数
    end
end

function love.mousereleased(x,y,button)
    if button == 2 then
        create_ellipse(x,y,50,50,255,0,0) -- 奖励:每个椭圆都是在用户单击的位置创建的
    end
end

function love.update(dt)
    if love.mouse.isDown(1) then
        local mousex,mousey = love.mouse.getPosition() -- 没有必要每帧都请求鼠标位置,只需要当用户在屏幕上的任何位置点击时

        for i = 1,#ellipses do
            local current_ellipse = ellipses[i]

            if mousex >= current_ellipse.x and mousex <= current_ellipse.x+current_ellipse.w and mousey >= current_ellipse.y and mousey <= current_ellipse.y+current_ellipse.h then
                current_ellipse.x = mousex
                current_ellipse.y = mousey
            end
        end
    end
end

如果你喜欢OOP,甚至可以自己创建一个椭圆类。

2016-01-03 19:45:48