problem with "y" coordinate

Hi you all, I’m using the following code to do a “game over” feature of my game:

[lua]

local statusText = display.newText("", _W/2, _H/2-100, “PUSAB”, 26)

local timeText = display.newText("", _W/2, _H/2, “PUSAB”, 26)

local function adjustText()

if player.y > _H then

statusText.text = “Game Over”

media.playSound( “suoni/gameover.wav” )

local function replacePlayer()

player:removeSelf()

player = nil

end

timer.performWithDelay( 100, replacePlayer )

statusText:setTextColor(255, 255, 0)

Runtime:removeEventListener(“enterFrame”, scroll)

else

     statusText.text = “”

end

end

Runtime:addEventListener(“enterFrame”, adjustText)

[/lua]

It works fine, the problem is that once player.y is higher than the screen height I get

[lua]

File: …nzoestienne/Desktop/prova director/gameWithSound.lua

Line: 114

Attempt to index upvalue ‘player’ (a nil value)

stack traceback:

    [C]: ?

    …nzoestienne/Desktop/prova director/gameWithSound.lua:114: in function <…nzoestienne/Desktop/prova director/gameWithSound.lua:112>

    ?: in function <?:218>

[/lua]

How can I fix this problem?

Thanks!! :slight_smile:

You are deleting the player after 100 milliseconds in your replacePlayer() function and then still checking the y position of player, which no longer exists (hence player being a nil value). 

So the course of events is:

  1. Every frame you are checking for the y position of the player.
  2. When player.y is high enough, you play a sound, change some text and set a 100ms timer to delete the player.
  3. 100 ms passes - the player object is deleted. 
  4. The enterFrame listener is still running - step 1 is repeated, but the object no longer exists.

The easiest fix would be to simply call Runtime:removeEventListener(“enterFrame”, adjustText) immediately after the line where you call timer.performWithDelay(100, replacePlayer)

You are deleting the player after 100 milliseconds in your replacePlayer() function and then still checking the y position of player, which no longer exists (hence player being a nil value). 

So the course of events is:

  1. Every frame you are checking for the y position of the player.
  2. When player.y is high enough, you play a sound, change some text and set a 100ms timer to delete the player.
  3. 100 ms passes - the player object is deleted. 
  4. The enterFrame listener is still running - step 1 is repeated, but the object no longer exists.

The easiest fix would be to simply call Runtime:removeEventListener(“enterFrame”, adjustText) immediately after the line where you call timer.performWithDelay(100, replacePlayer)