首页 > 解决方案 > 如何在love2d中随机绘制一次

问题描述

我目前正在尝试使用 love2d 创建砖块破坏器,但问题是每当使用math.random()生成随机砖块时,love 应用程序都会多次运行它并且砖块不断移动。

编辑:所以我想在特定列生成砖,但应该随机选择行。我的基本想法是执行 math.random(2) == 1 然后使用 for 循环绘制砖块,但问题是它每秒都会更新/绘制,并且砖块不断闪烁/移动。我只想随机(仅随机选择 y 坐标,我的 x 坐标是固定的)在执行代码时绘制一次,但它一直闪烁

我面临的问题 - https://youtu.be/AJB5vH7yfHc

我的代码

    for y = 0, VIRTUAL_HEIGHT- 4, 10 do
        if math.random(2) == 1 then
            love.graphics.rectangle('line', VIRTUAL_WIDTH - 10, y, 5, 10)
        end
    end

标签: randomluarandom-seedlove2d

解决方案


在 love.load() 中生成块位置

--VIRTUAL_WIDTH, VIRTUAL_HEIGHT  = love .graphics .getDimensions( )

block_pos  = {}  --  table to store block positions
rows, columns  = 5, 8  --  you decide how many

chance_of_block  = 75  --  % chance of placing a block

block_width  = math .floor( VIRTUAL_WIDTH /columns )
block_height  = math .floor( VIRTUAL_HEIGHT /rows )

for  row = 0,  rows -1  do
    for  col = 0,  columns -1  do

        if love .math .random() *100 <= chance_of_block then
            local xpos  = col *block_width
            local ypos  = row *block_height

            local red   = love .math .random()
            local green = love .math .random()
            local blue  = love .math .random()

            block_pos[ #block_pos +1 ] = { x = xpos,  y = ypos,  r = red,  g = green,  b = blue }
        end  --  rand

    end  --  #columns
end  --  #rows

(编辑:实现的行和列应该从 0 索引开始,所以它们在屏幕上排列)


然后用 love.draw() 绘制它们

for b = 1, #block_pos do
    local block  = block_pos[b]

    love .graphics .setColor( block.r,  block.g,  block.b )
    love .graphics .rectangle( 'fill',  block.x,  block.y,  block_width,  block_height )
end  --  #block_pos

推荐阅读