random - 如何在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
解决方案
在 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
推荐阅读
- facebook - FB Ad Account API - 相同的请求参数,但不同环境下的结果不同
- linux - 如何在引导徽标上隐藏 linux 引导日志?
- delphi - 使用 THTTPRIO 进行 SOAP 调用时如何强制使用 TLS 1.2?
- android - Android - 在完成第一个活动之前打开另一个活动时未调用 onActivityResult
- python - 如何将 message.text 转换为字符串并将其保存到数据库。如何通过电报机器人下载照片。TelegramBotAPI
- flutter - Flutter:如何调用存储在变量中的类
- autodesk-forge - How to receive the RealityCapture results on an email address
- javascript - 当值 <0 时需要红色的进度条
- svg - 使用 imagemagick 从带有覆盖文本的 SVG 创建 PNG 图标
- flutter - 如何存根不属于类的函数