Randomly spawned objects doesn't remove

Here’s the function. Thanks in advance!

local function cow (event) local sheetData = {width = 100,height = 100,numFrames = 8,sheetContentWidth = 200,sheetContentHeight = 400} local mySheet = graphics.newImageSheet ("CowWalk.png",sheetData) local sequenceData = {name = "cowOne",start = 1,count = 8,time = 950,loopcount = 0,looDirection = "forward"} cowOne = display.newSprite (mySheet,sequenceData) cowOne.x = 35 cowOne.y = 300 cowOne.rotation = 90 cowOne:play() end local function cowSpawnOne (event) for i = 0,0 do cow() cowOne.x = 35 cowOne.y = math.random (600,800) cowOneMovement = transition.to (cowOne,{time = 21000,y = -20}) if cowOne.y == -20 then cowOne:removeSelf() cowOne = nil return true end end end

At the time your code checks the position of cowOne, it will never be -20, so it will never remove. 

[lua]

local function cow ()

    local sheetData = {width = 100,height = 100,numFrames = 8,sheetContentWidth = 200,sheetContentHeight = 400}

    local mySheet = graphics.newImageSheet (“CowWalk.png”,sheetData)

    local sequenceData = {name = “cowOne”,start = 1,count = 8,time = 950,loopcount = 0,looDirection = “forward”}

    local cow = display.newSprite (mySheet,sequenceData)

    cow.x = 35

    cow.y = 300

    cow.rotation = 90

    cow:play()

    return cow

end

local function cowSpawnOne ()

  local cow = cow()

  cow.x = 35

  cow.y = math.random(600,800)

  local removeCow = function ()

    display.remove(cow)

    cow = nil

  end

  cow.transition = transition.to (cow,{time = 21000,y = -20, onComplete = removeCow })

end

[/lua]

Thanks man,it worked. So it permanently remove the spawned cow without affecting the performance?

At the time your code checks the position of cowOne, it will never be -20, so it will never remove. 

[lua]

local function cow ()

    local sheetData = {width = 100,height = 100,numFrames = 8,sheetContentWidth = 200,sheetContentHeight = 400}

    local mySheet = graphics.newImageSheet (“CowWalk.png”,sheetData)

    local sequenceData = {name = “cowOne”,start = 1,count = 8,time = 950,loopcount = 0,looDirection = “forward”}

    local cow = display.newSprite (mySheet,sequenceData)

    cow.x = 35

    cow.y = 300

    cow.rotation = 90

    cow:play()

    return cow

end

local function cowSpawnOne ()

  local cow = cow()

  cow.x = 35

  cow.y = math.random(600,800)

  local removeCow = function ()

    display.remove(cow)

    cow = nil

  end

  cow.transition = transition.to (cow,{time = 21000,y = -20, onComplete = removeCow })

end

[/lua]

Thanks man,it worked. So it permanently remove the spawned cow without affecting the performance?