Dips
Dips

Reputation: 145

Re-set spawn after collision

Basically what happens is objects spawn off screen at random positions and then flow in and out of the screen view. as they flow of screen they reset at a random position off screen again, however I cannot get that to happen if the player collides with it.

So to summarise, how would I make the object position respawn off screen again on collision with player?

Heres the object code.

UFO = display.newImage("ufo.png")
  UFO.name = "UFO"
  UFO.x = 640
  UFO.y = 100
  UFO.speed = math.random(2,6)
  UFO.initY = UFO.y
  UFO.amp = math.random(20,100)
  UFO.angle = math.random(1,360)
  physics.addBody(UFO, "static")

function moveUFO(self,event)
  if self.x < -50 then
     self.x = math.random(500,1500)
     self.y = math.random(90,220)
     self.speed = math.random(2,6)
     self.amp = math.random(20,100)
     self.angle = math.random(1,360)
else 
    self.x = self.x - self.speed
    self.angle = self.angle + .1
    self.y = self.amp*math.sin(self.angle)+self.initY
end

Here is the code for collision detection

    function ship:collision(event)
            if (event.other.name == 'UFO') then
                    event.other:removeSelf(self)
                    scoreAnim = display.newText('+10', ship.x, ship.y-10, native.systemFontBold, 16)
                    transition.to(scoreAnim, {time = 1000, y = scoreAnim.y - 30, alpha = 0, onComplete = function() display.remove(scoreAnim) scoreAnim = nil end})
                    scoreAnim:setTextColor(0,255,12)
                   --increases score
                    collectedN.text = tostring(tonumber(collectedN.text) + 1)

ship:addEventListener("collision", onCollision, ship, addTime)

Upvotes: 0

Views: 303

Answers (1)

Doğancan Arabacı
Doğancan Arabacı

Reputation: 3982

If I didn't misunderstand you don't know about collision detection. You should study this page:http://developer.coronalabs.com/content/game-edition-collision-detection

edit part:

function ship:collision(event)
    if (event.other.name == 'UFO') then
          timer.performWithDelay( 50, function() event.other.x = math.random( 0, 320 ); event.other.y = math.random( 0.480 ); end, 1 )
          scoreAnim = display.newText('+10', ship.x, ship.y-10, native.systemFontBold, 16)
          transition.to(scoreAnim, {time = 1000, y = scoreAnim.y - 30, alpha = 0, onComplete = function() display.remove(scoreAnim) scoreAnim = nil end})
          scoreAnim:setTextColor(0,255,12)
          --increases score
          collectedN.text = tostring(tonumber(collectedN.text) + 1)

This will do it.. You can modify random values over there. And you couldn't move your object right in collision time, because Corona physics, lock all physics objects in collision time. So you should move your objects right after collision.

Upvotes: 0

Related Questions