How can i measure distance between spawned objects? Im using a timer.performWithDelay to time the objects but if you restart the game a couple of times it messes up. so how can i say if there is 200px between the objects spawn a new one.
also if i try to remove the objects "onComplete" it removes the new objects to is there a simple fix for this ?
holl:removeSelf()
holl = nil
spawn code:
function hollspawn()
screenGroup = self.view
holl = display.newRect( 0, 0, math.random(10, 500), 53 )
holl.y = display.contentHeight - holl.contentHeight/2
holl.x =display.contentWidth + holl.contentWidth/2
holl:setFillColor( 1, 0, 0 )
holl.name = "hollgameover"
physics.addBody(holl, "static", {density=.1, bounce=0.5, friction=.2,filter=playerCollisionFilter } )
screenGroup:insert(holl)
trans55 = transition.to(holl,{time=2000, x=display.contentWidth - display.contentWidth - holl.contentWidth/2 - 20, onComplete=pluspoint, transition=easing.OutExpo } ) --onComplete=jetReady
end
timereholl = timer.performWithDelay( 1500 , hollspawn, 0 )
To get the distance between 2 objects you can use Pythagoras theorem
function getDistance(objA, objB)
-- Get the length for each of the components x and y
local xDist = objB.x - objA.x
local yDist = objB.y - objA.y
return math.sqrt( (xDist ^ 2) + (yDist ^ 2) )
end
To check for a distance less than 200 between "a" and "b" you can do:
if ( getDistance(a,b) < 200 ) then
--Your code here
end
***Note that the distance is not in pixels, but is a measure in relation to the contentWidth and contentHeight that you chose for your Corona Settings.
You can have some trouble with your spawn function because it does not create a new instance each time its called, possibly reusing the same objects over and over. Try something like this as a factory pattern:
function spawnNewObject()
local newInstance = display.newRect( 0, 0, math.random(10, 500), 53 )
-- Do things to newInstance here
newInstance.y = display.contentHeight - (newInstance.contentHeight * 0.5)
newInstance.x = display.contentWidth + (newInstance.contentWidth * 0.5)
newInstance:setFillColor( 1, 0, 0 )
newInstance.name = "hollgameover"
-- Return a new instanced object
return newInstance
end
Use it like this:
local newThing01 = spawnNewObject()
group:insert(newThing01)
local newThing02 = spawnNewObject()
group:insert(newThing02)
This way if you remove newThing01, it should keep newThing02 untouched because they are a separate instance (independent from each other)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.