我问过类似的问题,但我问的是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
但是当我右键单击以添加一个圆圈(增加for循环运行的次数)时,它不会为我添加第二个圆圈以独立于第一个圆圈移动。帮助
答案 0 :(得分:0)
我处理多个椭圆实例的方法是为每个椭圆创建一个表格,该表格可以保存它的属性和draw
函数。
local ellipses = {} -- store all ellipses into a table
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 -- insert new ellipse into ellipses table
return ellipse
end
function love.draw()
for i = 1,#ellipses do
ellipses[i].draw(); -- call each ellipse's separate draw function
end
end
function love.mousereleased(x,y,button)
if button == 2 then
create_ellipse(x,y,50,50,255,0,0) -- bonus: every ellipse is created where the user clicked
end
end
function love.update(dt)
if love.mouse.isDown(1) then
local mousex,mousey = love.mouse.getPosition() -- there is no need to request the mouse position every frame, but only when a user clicks anywhere on the screen
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,你甚至可以制作自己的Ellipse课程。