Gideros Mobile Tutorial 7: Classes & Inheritance

So far we put all the code in one file. In previous example if we wanted to add more balls we would have to add several lines of  code for every ball we add – like creating new bitmap, setting new position, anchor etc. Even the functions are written in a way that they call “ball” methods directly. How to avoid this and make it more universal, more reusable?

Classes &  Instances

I will not go into details about Lua language but in short, Lua does not support classes the way that languages like C++, Java and ActionScript do. It has roots from prototype-based languages. In Lua, each object can define its own behavior through metatables so in a way we emulate OO programming and classes in Lua.

Creating instances is easy through a new function:

local sprite = Sprite.new()
local texture = Texture.new("image.png")
local bitmap = Bitmap.new(texture)
local timer = Timer.new(1000, 0)

Inheritance

It is through the inheritance that we can “emulate” the classes just like in other languages – they will have variables, methods etc. Then we put these classes into their own files and Gideros will load them automatically. We use the Core.class function to create our own classes through inheritance. We can inherit from Sprite, EventDispatcher and so on. Keyword self is the equivalent of the this pointer in C++ and it is a reference to the table which is created as part of the Class.new() command.

Here is a simple inheritance example:

Player = Core.class(Sprite) -- we create our own player class, inherited from the Gideros Sprite core class

--init() function is called automatically when we create(instantiate) new Player
-- it is like a constructor function
function Player:init()
-- do the initialization of Player instance,we set custom variables
self.health = 100
self.speed = 3
end

function Player:walk()
-- this is a Walk method of a Player class
	print("Player Walking - health:", self.health)
end

function Player:jump()
-- jump logic
end

newPlayer = Player.new() --create new Player instance
anotherPlayer = Player.new() --another Player instance
--we add both to stage
stage:addChild(newPlayer)
stage:addChild(anotherPlayer)

print (newPlayer.health)

--we call their methods
newPlayer:walk()
newPlayer.health = 50
anotherPlayer:walk()

As you can see, in the and it looks similar to OO in other languages. In above example we put all the code in main.lua but we could take all the (class,methods..) code (line 1-18) and put it in player.lua file and the rest we would leave in main.lua. This is what we will do in next example.

Now lets take the code from previous tutorial and turn it into what we learned today. First you create a ball.lua file. The code is pretty much copy/paste from or previous ball example except that we access variables and methods with self (it is also used instead of word ball). As you will see we use word self. I understand that we access class variables and class methods with self word but I am not so sure why we need to pass another self to self:addEventListener function (if you know let me know in comments, I am still learning). This self word is use everywhere so it can be quite confusing for beginners.

Put this in ball.lua (Code is commented):

-- create our own Ball class

Ball = Core.class(Sprite)

--init will run every time we create new Ball object (Ball.new)
function Ball:init (texture) --we will pass texture name
	self.direction = 3
	local bitmap = Bitmap.new(Texture.new(texture,true))
	self:setPosition(math.random(0, 270),math.random(0, 430)) --put ball on random position on screen
	bitmap:setAnchorPoint(0.5,0.5)
	self:addChild(bitmap)
	self:addEventListener(Event.ENTER_FRAME, self.rotateBall,self)
	self:addEventListener(Event.MOUSE_DOWN, self.changeBallDirection,self)
	self:addEventListener(Event.MOUSE_UP, self.fallDown,self)
	self:addEventListener(Event.MOUSE_MOVE, self.moveBall,self)
end

-- function rotating ball - executed every frame
function Ball:rotateBall()
self:setRotation(self:getRotation()+self.direction)
end

-- function scale ball - executed every mouse press
-- it is not actually mouse,it means no multi touch
function Ball:changeBallDirection(event)
	if self:hitTestPoint(event.x, event.y) then
		-- zoom the ball - jump up
		GTween.new(self, 0.3, {scaleX = 2, scaleY = 2}, {ease = easing.linear})
		soundJump:play()
		self.direction = math.random(-20,20) --random rotation speed(left or right)
	end
end

function Ball:fallDown(event)
	if self:hitTestPoint(event.x, event.y) then
		-- zoom the ball - jump up
		GTween.new(self, 1.5, {scaleX = 1, scaleY = 1}, {ease = easing.outBounce})
		soundBounce:play()
	end
end

--move the ball
function Ball:moveBall(event)

	if self:hitTestPoint(event.x, event.y) then
		local dx = event.x - self:getX()
		local dy = event.y - self:getY()

		self:setX(self:getX() + dx)
		self:setY(self:getY() + dy)
		self.x0 = event.x
		self.y0 = event.y

	 --not sure why this is here, maybe once we start moving ball
         -- we don't need to check if the ball is moved?
           event:stopPropagation()
	end
end

Gideros will automatically load and run this file when you run the program. Now create main.lua, it will be much shorter and you will see how easy is to create new balls:

-- you can apply some settings to your entire application
application:setKeepAwake(true)
application:setScaleMode("letterbox") --proper "full screen" scaling for most devices

-- global direction variable,rotate counterclockwise -3
--direction = 3

-- load background image
local field = Bitmap.new(Texture.new("gfx/field.png",true))

-- load sound that will be played when we press on ball
soundJump = Sound.new("snd/jump.mp3")
soundBounce = Sound.new("snd/bounce.mp3")

-- here we create new ball instances,we pass texture name as argument
-- Ball.new will create objects that we defines in ball.lua
--ball2.png and ball3.png are just different balls - try using your own images
newBall = Ball.new("gfx/ball5.png")
newBall2 = Ball.new("gfx/ball2.png")
newBall3 = Ball.new("gfx/ball3.png")

--add field for background and all balls to stage
stage:addChild(field)
stage:addChild(newBall)
stage:addChild(newBall2)
stage:addChild(newBall3)

and that’s it. You can see it is much clearer this way and we only need to create new Ball objects and you will have new ball with all the methods and all. Try to add new balls and you will see them appearing on the screen and each ball can be picked up, dragged etc. You can create of course a lot of classes like this, for every object you want. If you had a football(soccer) game then we have the ball class already. Then you would for example create player.lua and put all logic for all players there – they all behave in similar way. You could create a goalie.lua and referee.lua class/file for goal keeper and referee if you want because they behave differently and have different logic than players (or you could use different methods in player.lua class, as you wish). If you had an active audience you can create audience.lua class etc. You don’t need to create these classes just for objects – you can also create it for example to handle all the audio effects in the game and so on.

Passing arguments to functions

We are currently just passing a texture file name to Ball class init() method and then randomly setting x and y but you can of course change this and pass x and y .

So in ball.lua you need to modify function init (I am only showing lines that need to be changed):

function Ball:init (texture,x,y) --2 new arguments
        --everything stays the same except 
        self:setPosition(x,y) --explicitly set x and y
        --everything else is the same
end

and now we also change few lines in main.lua:

newBall = Ball.new("gfx/ball5.png",10,200)
newBall2 = Ball.new("gfx/ball2.png",200,40)
newBall3 = Ball.new("gfx/ball3.png",150,300)

This way you can create new ball at any position you wan’t. You can of course pass other arguments ,as many as you wan’t.

Gideros Mobile Tutorial 5: Events

So far we only displayed some graphics on the screen, we even animated (not real animation though, just rotation of one bitmap) it but there was no user interaction at all. We had one event in Tutorial 4 but it was not really explained in details what it does.

Events and addEventListener

With events we handle responses and they allow us to create interactive applications. The target of an event is a listener function and an optional data value so when an event is dispatched, the registered function is called.  If the optional data value is given, it is used as a first parameter while calling the listener function.  In Gideros we have built-in events generated by the system (e.g. ENTER_FRAME event, touch events, timer events, etc.) and custom events which can be generated by the user.

Here are few examples of kinds of events:

  • ENTER_FRAME  – this event is dispatched every frame. If your game is 60 fps then 60 times/s
  • MOUSE_DOWN – dispatched every time someone presses “mouse” button
  • MOUSE_UP – dispatched every time “mouse” button is released
  • TOUCHES_BEGIN – dispatched every time screen is touched
  • TIMER  – events tied to timers

Just to make it less confusing: We don’t actually use mouse on smartphones of course so you can use MOUSE_ events to handle only a single touch on specific object. In case you want to handle multi touch then you should use TOUCHES_ events because they will provide you with more information about current touch id and all available touches on the screen.

Here is a quick example of an event and function it calls. Let’s suppose we already loaded bitmap ball.

-- function that will be called every time event is dispatched
function rotateBall(event)
 --some code to rotate the ball
end
-- we attach event to ball's addEventListener
ball:addEventListener(Event.ENTER_FRAME, rotateBall)

So basically what this means is we attached addEventListener to our ball object and what it will do is it will call function rotateBall on every frame change. If we would have Event.MOUSE_DOWN instead then rotateBall function would be called every time we press/touch the ball.

At the end of this tutorial we will have a rotating ball that will randomly change direction, rotation speed and play a sound every time you press it.  In next tutorial (tutorial 6) we will add some events that will make the ball dragable and the effects of picking up and dropping the it.

Ok, enough of theory, let’s build an app (with graphics and sound effects). Create project “Events” and add main.lua.

Note: So far we put all the files in one folder but as the app grows larger it is better to be organized. So we will put graphics in gfx  folder and sounds in snd  folder. I prepared a file for you so download it and extract it to your project folder. Important: Gideros project folder  structure is independent of your OS folder structure so you will have to create folder in Gideros by yourself and add existing files there. In theory this means that you might have all the files in one folder on disk but in Gideros they are nicely structured – or the opposite of course!

Add this code to main.lua :

-- you can apply some settings to your entire application
application:setKeepAwake(true) 
application:setScaleMode("letterbox") --proper "full screen" scaling for most devices

-- global direction variable,rotate clockwise 3
direction = 3

-- load the textures and create bitmap objects
--2nd texture parameter can be set to true to get anti-aliasing
local field = Bitmap.new(Texture.new("gfx/field.png",true))
local ball = Bitmap.new(Texture.new("gfx/ball5.png",true))

-- load sound that will be played when we press on ball
local soundJump = Sound.new("snd/jump.mp3")

-- set the anchor point in the center of ball it rotates around center
ball:setPosition(120,150)
ball:setAnchorPoint(0.5,0.5)

-- function changeBallDirection - executed every frame
function rotateBall(event)
	ball:setRotation(ball:getRotation()+direction)
end

-- function changeBallDirection - executed every mouse press
-- it is not actualy mouse, it means no multi touch
function changeBallDirection(event)
		soundJump:play()
		direction = math.random(-20,20) --random rotation speed(left or right)
end

-- rotateBall function will be called on every frame change
ball:addEventListener(Event.ENTER_FRAME, rotateBall)
-- when we click on the ball it will (or not) change direction
ball:addEventListener(Event.MOUSE_DOWN, changeBallDirection)
-- when we move the mouse then ball also moves

stage:addChild(field)
stage:addChild(ball)

Run it and you will have a nice rotating ball on the field. Now press the ball and it will randomly change the rotation direction and speed, not to mention it will play a sound every time you press it. If you do it long enough you might even make the ball stop rotating (speed=0) 😉

But what a minute – the ball changes rotation/speed even if we click anywhere on the screen! That is not very useful. No worries though, it is easy to fix this,we just need to wrap the reaction between 2 lines. Replace the changeBallDirection function with this:

function changeBallDirection(event)
	if ball:hitTestPoint(event.x, event.y) then
		soundJump:play()
		direction = math.random(-20,20) --random rotation speed(left or right)
	end
end

So we just wrapped the code with hitTestPoint function (lines 2 and 5). This hitTestPoint function simply checks if the given coordinates are in bounds of the sprite/object. Run it and now it only works if you “click” on the ball.

I don’t want to make this tutorial too long and hard to comprehend so we will add some additional events in the next tutorial.

Gideros Mobile Tutorial 4: Graphics

Textures, bitmaps and sprites

Most of the games use graphics so let’s learn how to display it on the screen and apply some transformations to it. You will also meet 3 new object types: textures, bitmaps and sprites.

  • Texture – class that is used to load an image file. You can’t really do much with it, it just holds the data stored in the image file
  • Bitmap – it inherits from Sprite and wraps a Texture object for on-screen display.
  • Sprite – think of it as a object that groups other objects (or separate them in different layers) like images, texts and shapes

Let’s do a simple example so it will be more clear. First, I suggest you to download Gideros Asset Library (Contains set of backgrounds, tilesets, texture, sprites, icons and music files for beginners like us) . You will find this Character-Pink-Girl.png in the Tilesets\PlanetCute PNG directory. I am also including all files needed for this tutorial in the ZIP at the end of the post.

Character Pink Girl

Create new project “Graphics”,  create main.lua and add this PNG to your project.  Add this code to main.lua

-- you can apply some settings to your entire application
application:setKeepAwake(true) --prevent screen dimming on your phone.
application:setBackgroundColor(0x65E17b) -- set background color of application to look like green grass

-- load some textures and create bitmaps from them
-- We will create 2 bitmaps using the same texture to show the difference
local girlTexture = Texture.new("Character Pink Girl.png") --load new texture into girlTexture variable
local girl = Bitmap.new(girlTexture) --create bitmap girl that holds girlTexture texture.
local upsideDownGirl = Bitmap.new(girlTexture) --create another bitmap upsideDownGirl with girlTexture texture
upsideDownGirl:setAnchorPoint(0.5, 0.5) --set the anchor point in the middle of the bitmap
upsideDownGirl:setRotation(180) --lets rotate this second bitmap upsideDownGirl 180°

-- let us set some properties then we display these objects on the screen (add them to stage)
girl:setPosition(30,100)
upsideDownGirl:setPosition(70,350)
stage:addChild(girl) -- display girl on the screen
stage:addChild(upsideDownGirl) -- display upsideDownGirl to the screen

And there you have it! Run Gideros Player and you should see 2 girls (one upside down) on the green background. As you can see we used the same texture for 2 different bitmaps.  Texture is just a picture and bitmap is an object that contains this texture and does all kinds of modifications on it.

Maybe let me explain just this part:

upsideDownGirl:setAnchorPoint(0.5, 0.5) --set the anchor point in the middle of the bitmap

Each Bitmap object has an anchor point that affects the positioning of the texture displayed. By modifying the anchor point, you change the origin of the texture. Values go from 0 to 1 and you can see here how anchor point moves.  By default it is set to 0,0. We usually want it to rotate on the spot so we set it to center of the texture to the origin (0.5, 0.5)

anchor point

Fun with Textures, Bitmaps and  Sprites

Let’s modify the code to include sprites and some other things. I will mostly comment just the new code:

-- you can apply some settings to your entire application
application:setKeepAwake(true)
application:setBackgroundColor(0x65E17b)

--load some textures and create bitmaps from them
local girlTexture = Texture.new("Character Pink Girl.png")
local girl = Bitmap.new(girlTexture)
local upsideDownGirl = Bitmap.new(girlTexture)
upsideDownGirl:setAnchorPoint(0.5, 0.5)
upsideDownGirl:setRotation(180)

-- lets add some more textures and create bitmaps out of them so we can manipulate them
-- as you see we can pass and create texture.new as an argument in bitmap.new so only 1 line is enough
local boy = Bitmap.new(Texture.new("Character Boy.png")) --create texture and bitmap in 1 line
local bug = Bitmap.new(Texture.new("Enemy Bug.png"))
local tree = Bitmap.new(Texture.new("Tree Tall.png"))
local rock = Bitmap.new(Texture.new("Rock.png"))

-- let's group all boys and girls together as people with sprite object
-- we will later be able to manipulate all these boys and girls at the same time
local people = Sprite.new()

-- who is people? What objects are in group people?
-- we could add rock or tree to people too but that wouldn't make sense
people:addChild(girl) --girl is people
people:addChild(upsideDownGirl) --upsideDownGirl is people too
people:addChild(boy) --boy is people

-- place bitmaps on the screen/stage
girl:setPosition(30,100)
upsideDownGirl:setPosition(70,350)
boy:setPosition(140,100)
bug:setPosition(100,100)
tree:setPosition(140,60)
rock:setPosition(130,250)
people:setAlpha(0.5) -- we set transparency to people so you will see how this impacts entire group/sprite

stage:addChild(bug)
stage:addChild(tree)
stage:addChild(rock)
stage:addChild(people) --we add sprite (group) to stage,no need to add one by one

-- set anchor point of bug to center
bug:setAnchorPoint(0.5, 0.5)

--rotate the bug -1 every frame
stage:addEventListener(Event.ENTER_FRAME, function()
bug:setRotation(bug:getRotation()-1)
end)

Run this and you should see something like this (on tablet it will be smaller):

graphics-gideros

As you can use grouping bitmaps into sprites is useful because you can manipulate the entire sprite(group). Sprite can be a little confusing word for those who remember C64 and earlier because at that time sprite meant objects composed of images. In Gideros sprites are used to group other objects (or separate them in different layers) as images, texts and shapes. In example above we made sprite people containing all “people”. You could also make a sprite “nature” that would contain bitmaps like trees, rocks, sun etc. Grouping elements into sprite is useful because we can for example turn off all objects contained in one sprite. In example above we set transparency of entire people sprite to 50% so you can see all people are partially transparent.

The last thing is the rotation of a bug. We will cover events and event listeners soon so don’t think about this too much.  In short: We add event listener to stage that calls a function every time a frame changes. What does this function do? It simply rotates the bug 1° counter clockwise. Note: the bug is not rotating around center because the texture is not square.

You can download all files (graphics and main.lua) for this tutorial here.

Gideros Mobile Tutorial 3: Shapes

It’s nice to have something else on the screen than just text. Let’s try to draw some shapes. I will leave out step-by-step explanation on how to add files to projects, how to start Gideros Player etc because this was covered in previous tutorials.

Drawing Shapes

You can draw primitive shapes with Gideros on the screen.  Create new project, name it “Shapes”, add new main.lua file and open it in editor.

Remember that in Gideros we create every new object (sprites,textfield,shape,bitmap…) with the keyword new. Add this code (comments — are in the code) to main.lua, run the player and you will see black line on your screen.

local myShape = Shape.new() -- create the shape object assigned to variable myShape
myShape:beginPath()         -- We have to tell shape to begin a path
myShape:setLineStyle(1)     -- set the line width = 1
myShape:moveTo(100,100)     -- move pen to start of line
myShape:lineTo(200,100)     -- draw line to new coordinates
myShape:endPath()           -- end the path
stage:addChild(myShape )    -- add the shape to the stage - display it

I think it is not hard to see what is going on here. We can use pen & paper analogy to explain it even simpler: The “moveTo” function is like lifting a pen off the paper and moving it to a different location without drawing anything. The “lineTo” function draws a straight line from current pen location to the destination location. As you can see once we create new Shape object named myShape we always use “myShape:” to change it’s properties, do something with it etc.

I am sure developers understand the screen coordinate system (line from 100,100 to 200,100) but here is the coordinate system just in case:
coordinates

Fun with Shapes

Now let’s draw a rectangle, fill it will color and apply some transformations learned in previous lessons. Shapes are “anchored” at the graph origin (0,0). The anchor point affects how the shape behaves when manipulated (e.g., rotated, scaled). If we want to prevent out rectangle from previous example to move off the screen we first create the shape at 0,0 coordinates (left top corner) and then move it to 100,100.

Modify the code so it will look like this:

local myShape = Shape.new() -- create the shape object assigned to variable myShape
myShape:beginPath()         -- We have to tell shape to begin a path
myShape:setLineStyle(2)     -- set the line width = 2
myShape:setFillStyle(Shape.SOLID, 0xFF0000) -- solid red fill color
myShape:moveTo(0,0)     -- move pen to start of line
myShape:lineTo(100,0)     -- draw top of rectangle
myShape:lineTo(100,100)     -- draw right side of rectangle
myShape:lineTo(0,100)     -- draw bottom of rectangle
myShape:lineTo(0,0)     -- draw left side of rectangle
myShape:endPath()           -- end the path
-- now we apply some transformations to the shape we created
myShape:setPosition(100,100) -- move the entire shape to 100,100
myShape:setScale(1.2,1.5) -- scale x by 1.2 and y by 1.5. The shape wont be rectangle anymore
myShape:setRotation(40) -- rotate shape by 40 degrees
stage:addChild(myShape )     -- add the shape to the stage - display it

Play with it a little, create different shapes.