Sunday, 27 April 2014

Corona and the Model-View-Presenter pattern (Part 6)

Welcome to the sixth part of the MVP Tutorial.  One left :)

Regarding Part 5 ; the best way of inverting the display, with the minimal amount of change, is simply to process the 'y' coordinates - replacing model.thing.y with 480-model.thing.y - the game will work exactly the same, it will just be upside down.

One of the advantages of this sort of thing is the ability to make changes without those changes having too many knock on effects. This part, and the next, will show those in practice.

Part 6 is dead simple. We are going to replace the circle with an actual picture of a ball.

This will be very very small on a 320x480 resolution, but it is possible to see it, just. If you want it bigger, you can amend the radius in the model. - the radius is part of the 'game data'.

So, we can change this without worrying about the model, or the presenter, it is just a visual change. To do so, we have to change both the initialise functions, and the update functions. This is the 'new' initialise function (the unchanged bits are, as usual in italics)

view.presenter = presenter
view.batObject:addEventListener( "tap",view )

view.ballObject = display.newImage("ball.png")

view.scoreObject = display.newText("<score>",315,5,native.systemFontBold,32)
view.scoreObject.anchorX,view.scoreObject.anchorY = 1,0

All we have done is take out the circle and replace it with an image. From the viewpoint of the model or the presenter it doesn't matter what it is - it could be three sprites, or drawn out of lines, it doesn't matter.

We have to update the view slightly differently - originally we provided a radius for the circle, now we provide a height and width for the sprite.

function view.update(model)
view.batObject.x = model.bat.x 
view.batObject.y = model.bat.y
view.batObject.width = model.bat.width

view.ballObject.x = model.ball.x
view.ballObject.y = model.ball.y
view.ballObject.width = model.ball.radius * 2
view.ballObject.height = model.ball.radius * 2

view.scoreObject.text = ("00000" .. model.score):sub(-5,-1)

Again, very minimal changes in one part - we remove the view.ballObject.radius and replaces it, updating the width and height to twice the radius.

Run it and it works. This is downloadable from

The exercise, the last one, is to replace the bat with the bat graphics included in the download. Or use your own :)

In Part 7, the last part, we will replace the control (clicking on the bat) with an action button which does the same thing.

No comments:

Post a Comment