随机在一个盒子里放一个圆圈

时间:2015-07-21 00:34:30

标签: lua corona

我正在制作一个游戏,我试图随机将一个圆圈放在一个矩形中。但是,似乎圆圈有时会出现在矩形之外。我必须做什么才能让圆圈始终出现在矩形的某个地方?

这是我的代码:

矩形:

--bottom
local floor = display.newRect(0, display.contentCenterY/.665, display.contentWidth*2, 10)
physics.addBody(floor, "static", {density = 1, friction = 1, bounce = 0})
--top
local floor = display.newRect(0, display.contentCenterY/2, display.contentWidth*2, 10)
physics.addBody(floor, "static", {density = 1, friction = 1, bounce = 0})
--right
local floor = display.newRect(display.contentCenterX*2, display.contentCenterY/1, 10, display.contentHeight/2)
physics.addBody(floor, "static", {density = 1, friction = 1, bounce = 0})
--left
local floor = display.newRect(0, display.contentCenterY/1, 10, display.contentHeight/2)
physics.addBody(floor, "static", {density = 1, friction = 1, bounce = 0})

圆圈:

--Small sprites--
local randomX = math.random(1,display.contentCenterX*2)
local randomY = math.random(1, display.contentCenterY*2)

local smallSprite = display.newCircle(randomX, randomY, display.contentWidth/100)
smallSprite:setFillColor(1, 1, .3, 1) --This will set the fill color to transparent
smallSprite.strokeWidth = 7 --This is the width of the outline of the circle
smallSprite:setStrokeColor(.1,1,1) --This is the color of the outline
smallSprite = display.newGroup(smallSprite)

1 个答案:

答案 0 :(得分:0)

这很容易,你知道矩形的两边是什么(称为rigth,left,top和bottom)和圆的半径,所以:randomX将介于left+radius和{{之间1}},right-radius位于randomYtop+radius

之间
bottom-radius

您可以在您选择的任意两个号码之间生成一个随机数。 还记得你可以使用display.contentHeight和display.contentWidth

作为提示,您可以在文件的开头添加一个包含变量的部分:

-- remember to add/substract the width of the walls
local left = 0 + 10
local right = display.contentCenterX * 2 - 10

--Small sprites--
local randomX = math.random(left+radius,right-radius)
local randomY = math.random(top+radius, bottom-radius)

因此,您只能使用centerX而不是display.contentCenterX

相关问题