Display random objects in corona without overlapping on the other objects on screen

折月煮酒 提交于 2019-12-25 04:22:19

问题


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 :)



来源:https://stackoverflow.com/questions/22357537/display-random-objects-in-corona-without-overlapping-on-the-other-objects-on-scr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!