Display random objects in corona without overlappi

2019-08-31 07:58发布

问题:

I want to display random objects on the screen i have one ball but the objects been generated are overlapping with the ball i want to get the coordinated of the ball and according to that only shift the random objects. I am trying like below snippet.

local ballX=ball.x
local ballY=ball.y

local xPos=generate_random(40,600)
local yPos=generate_random(40,920)
if(xPos>=ballX and xPos<=ballX) or (yPos>=ballY and yPos<=ballY) then
  objplace.x=xPos+150
  objplace.y=yPos+150
else
  objplace.x=xPos
  objplace.y=yPos
end

回答1:

You aren't checking if the balls overlap, you are just checking if their centers are at the same position and if so you are shifting them. You need to take into consideration the overall area of the ball (thus its radius). To make this perfect, you would have to use some algebra/geometry (as the radius can be looked at at different angles like a right triangle, where the xPos would be the base length and yPos would be the side height).

Something simple (not perfect) would be like:

while((xPos>=(ballX + ballRadius) || xPos<=(ballX - ballRadius)) ||
    (yPos>=(ballY + ballRadius) || yPos<=(ballY - ballRadius))){
    xPos = xPos + 150;
    yPos = yPos + 150;
}
objplace.x = xPos;
objplace.y = yPos;

Again this is VERY poorly done, there is little on the end of error checking and there are far more parameters that should be taken into account to make things perfect. If you really need me to crunch through it I can, but this would likely be a good project to hone your logical reasoning skills :)