The code looks good.
However I'm not sure if scene
is correctly allocated.
You have yPos>worldHeight
and below xPos>=worldWidth
which suggests that you're not sure how to compare these. I suspect you got at least one of them wrong. This can easily write outside the scene variable and overwrite yPos or xPos.
Try changing to ypos>=worldHeight
and see if that works.
If not check how much space you allocate for scene
and if it looks OK try making it a bit bigger.