Changing images of a display.newImage()

I’m building a couple of different games trying to learn Corona. In one game I want to swap out the background image based on what level you’re one. The other I want to tap on an image and change its bitmap.

So I can do a

gameboard = display.newGroup()  
background = display.newImage("background1.png")  
gameboard:insert(background)  

– code to add other things to the group like labels, scores, etc…
So when I go to the next level, how do I change out that background image?

In the second case, I want to create the graphic button of a random graphic. I think I’m getting a weird assert error because I’m in the middle of processing a touch event. I remove the graphic by calling :removeSelf() then I do a new object = display.newImage(randomimage) followed by adding a touch handler to it. So what I want to do is create the graphic once and just change the image when I want to.

I would paste in some code for it, but I’ve rearranged the code while trying to solve this problem.

Its basically:

local function removeObject(tapped)   
 if tapped then  
 -- do the score code  
 end  
 object:removeSelf();  
 object = nil -- tried this to try and completely remove object.  
 object = display.newObject(randomImage)  
 -- more init code  
 object::addEventListener("touch", listener )  
  
end  
  
local function listener(event)   
 local phase = event.phase  
 if "began" == phase then  
 removeObject(true)  
 end  
 return true   
end   
  

This would in theory do what I want, but it blows apart with an assert error, which I expect because I’m in the middle of the event handler.

I’m going to fix this by moving the create code to my gameLoop/state machine code on an enterFrame event. So I end up doing the destroy in the touch handler, and then create in the enterFrame event.

Still there has to be an easier way to just swap the graphics.

Thoughts? [import]uid: 19626 topic_id: 7452 reply_id: 307452[/import]

do it as a sprite/movieclip and change the frame [import]uid: 6645 topic_id: 7452 reply_id: 26369[/import]

for sprites look in the samples folder under sprites HorseAnimation and JungleAnimation to see what sprites are and how to instantiate them

c [import]uid: 24 topic_id: 7452 reply_id: 26375[/import]

carlos, say we weren’t to use sprites (although personally i would), I believe the deferred state machine enterFrame approach is the correct way to approach this issue.

however since display objects are essentially synced with the box2d physics world objects under the hood, it would presumably be possible to have a function eg [lua]physObj.image = display.newImage[/lua] added to corona?

I believe you know anyway we have requested some features regarding separating physics and visual objects anyway. i realise this does lead to more complex setup code - physics in *6* lines :wink: - but it would be good to have the option to use more advanced methods

[import]uid: 6645 topic_id: 7452 reply_id: 26379[/import]