随机将一个圆放入一个盒子中

我正在制作一个游戏,我想随机在一个矩形中放一个圆。但是,有时圆会出现在矩形外面。我应该怎么做才能让圆始终出现在矩形中的某个位置?

这是我的代码:

矩形:

--底部
local floor = display.newRect(0, display.contentCenterY/.665, display.contentWidth*2, 10)
physics.addBody(floor, "static", {density = 1, friction = 1, bounce = 0})
--顶部
local floor = display.newRect(0, display.contentCenterY/2, display.contentWidth*2, 10)
physics.addBody(floor, "static", {density = 1, friction = 1, bounce = 0})
--右边
local floor = display.newRect(display.contentCenterX*2, display.contentCenterY/1, 10, display.contentHeight/2)
physics.addBody(floor, "static", {density = 1, friction = 1, bounce = 0})
--左边
local floor = display.newRect(0, display.contentCenterY/1, 10, display.contentHeight/2)
physics.addBody(floor, "static", {density = 1, friction = 1, bounce = 0})

圆:

--小精灵--
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) --这将设置填充颜色为透明
smallSprite.strokeWidth = 7 --这是圆形轮廓的宽度
smallSprite:setStrokeColor(.1,1,1) --这是轮廓的颜色
smallSprite = display.newGroup(smallSprite)
点赞
用户2360222
用户2360222

那很容易,你知道长方形的边在哪里(称它们为右边、左边、顶部和底部),以及圆形的半径,所以:randomX将介于left + radiusright-radius之间,而randomY将介于top + radiusbottom-radius之间。

-- 记住加/减墙的宽度
local left = 0 + 10
local right = display.contentCenterX * 2 - 10

--小精灵--
local randomX = math.random(left+radius,right-radius)
local randomY = math.random(top+radius, bottom-radius)

你可以在你选择的任意两个数字之间生成一个随机数。 同样要记住,你可以使用display.contentHeightdisplay.contentWidth

作为一个提示,你可以在文件开头添加一个变量部分,像这样:

-- 变量
local w = display.contentWidth
local h = display.contentHeight
local centerX = display.contentCenterX
local centerY = display.contentCenterY

这样你就可以只使用centerX而不是display.contentCenterX

2015-07-23 22:04:09