Corona – Game Loops part 3

Following up on my previous two posts, this discussion will continue with the game loop topic. Here I’ll create a couple game objects, or actor objects, that will work with the game loop.

As previously discussed, actors work need to interface with the game loop by implementing the update(deltaTime) method. This interface is just a function that each actor object must posses. How the actors implement this function is up to the actor.

In this example I’ll create two types of objects. One object will start at the top of the screen and move down the screen. I’ll call these objects rocks.

The second object will move to the location of a touch on the screen. I’ll call this a ship.

Object when created will need to add themselves to the game_loop. To make this easy we’ll use the singleton nature of Lua modules to help. Every file that uses require(“game_loop”) will be getting a reference to the same programming object. Any module that require game loop will be talking to the same game loop.

The rock objects will remove themselves from the display when they reach the bottom of the screen. This means, rocks will also have to remove themselves from the game loop at the time they remove themselves from the display. To make this easy we’ll make use of the singleton nature of the game_loop module again.

rocks.lua –
I made a file named rocks.lua. This file contains the code that will produce “rock” objects. The rocks will fall down the and remove themselves when they get past the bottom edge of the screen.

The rocks module have the following methods.

make() rock – This function returns a rock.

This module requires game_loop.

The rocks module acts as factory that produces rock objects. Each rock is is a Corona shape object, a rectangle. Corona display objects are essentially tables. Each rock has two methods.

rock:remove() – removes the rock from game_loop, and then from display.
rock:update( deltaTime ) – updates the position of the rock.


--------------------------------------------------------------------
--
-- rocks.lua 
-- 
--------------------------------------------------------------------
local M = {}
--------------------------------------------------------------------

local game_loop = require("game_loop")

local xMax = display.contentWidth
local xMin = 0
local yMax = display.contentHeight + 40
local yMin = 0

local function make()
	local rock = display.newRect( 0, 0, 40, 40 )
	rock:setFillColor( 0, 1, 0 )
	rock.x = math.random( xMin, xMax )
	rock.y = yMin - 40
	rock.speed = math.random() * 3 
	
	function rock:remove()
		game_loop.remove( self )
		display.remove( self ) 
	end
	
	function rock:update( dt ) 				-- receive dt here as a parameter. 
		self.y = self.y + self.speed * dt 	-- Use dt, multiply by pixels per frame (speed)
		if self.y > yMax then 
			
			self:remove()
		end 
		return self
	end
	
	game_loop.add( rock )
	 
	return rock
end 
M.make = make

--------------------------------------------------------------------
return M

ship.lua –
The ship.lua module is very similar to the rocks module. This module acts as factory that produces ship objects. The ship module has a single method.

make() ship – The make method returns a a ship object.

The ship module requires the game_loop module. Each ship created is added to game_loop.

Ship objects have three methods.

ship:move_to( x, y ) – starts the ship moving towards the x, and y.
ship:remove() – Removes the ship from game_loop and from the display.
ship:update( deltaTime ) – Updates the position of the ship.


-----------------------------------------------
--
-- ship.lua
-- 
-----------------------------------------------
local M = {}
-----------------------------------------------
local game_loop = require( "game_loop" )
-----------------------------------------------

local function make()
	local ship = display.newRect( display.contentCenterX, display.contentHeight - 100, 20, 40 )
	
	ship.target_x = ship.x
	ship.target_y = ship.y
	
	function ship:move_to( x, y )
		self.target_x = x
		self.target_y = y
	end 
	
	function ship:remove()
		game_loop.remove( self )
		display.remove( self )
	end 
	
	function ship:update( dt )
		ship.x = ship.x - (ship.x - ship.target_x) * 0.1
		ship.y = ship.y - (ship.y - ship.target_y) * 0.1
	end 
	
	game_loop.add( ship )
	
	return ship
end 
M.make = make

-----------------------------------------------
return M 

Here’s a simple program to test out the modules defined above.


-----------------------------------------------------
-- Import the game loop module 
local game_loop = require("game_loop")
game_loop:run()
-----------------------------------------------------

-- Make a player
local ship = require( "ship" ) 
local player = ship.make()

local function move_ship( x, y )
	player:move_to( x, y )
end 

local function on_touch( event )
	if event.phase == "began" then 
		move_ship( event.x, event.y )
	elseif event.phase == "moved" then 
		move_ship( event.x, event.y )
	end
end 
Runtime:addEventListener( "touch", on_touch )
-----------------------------------------------------

-- A function to make rocks
local rocks = require( "rocks" )

local function make_rock()
	local rock = rocks.make()
end 

-- Use a timer to make rocks periodically
local rock_timer = timer.performWithDelay( 900, make_rock, 0 )
-----------------------------------------------------

Let’s take a look at each part. The first two lines load up the game_loop module, and start it running.


local game_loop = require("game_loop")
game_loop:run()

Next we make a player object. The player object will be made from a ship object. To move the ship I’m calling on the ship objects move_to( x, y ) method. Here I made a touch event that calls on move_to() with the event.x and event.y. Which tells the player/ship to move to the position of the touch event.

The event calls move_ship() during both the began and moved phases. The effect is that the ship will start moving to the position of the point your finger makes contact with the screen, and updates position as you drag your finger across the screen.


local ship = require( "ship" ) 
local player = ship.make()

local function move_ship( x, y )
	player:move_to( x, y )
end 

local function on_touch( event )
	if event.phase == "began" then 
		move_ship( event.x, event.y )
	elseif event.phase == "moved" then 
		move_ship( event.x, event.y )
	end
end 
Runtime:addEventListener( "touch", on_touch )

Lest create a timer to create a new rock every 900 milliseconds.


local rocks = require( "rocks" )

local function make_rock()
	local rock = rocks.make()
end 

-- Use a timer to make rocks periodically
local rock_timer = timer.performWithDelay( 900, make_rock, 0 )

Here’s a few ideas to try on your own.

Make a new object type that moves differently from the two examples here.
Add some new features to the one or both of the objects here. For example make the rocks rotate as they move down the screen.
Use images, or better yet sprites, in place of the rectangles I used.

Corona – Game Loop part 2

Here’s a follow up to the previous post on game loops. The game loop works with actor objects. Actors are stored in an array. The game loop sends it’s actors an update message each frame, and passes the delta time.

Here I have created a Lua module to handle the game and appropriately named it: game_loop. Using a module gives us three advantages.

First, the code is easily portable. You can copy this Lua file/Module into another project and use the game there.

Second, the code is isolated. This makes it easier to edit the game loop if necessary.

Last, Lua modules are only loaded once. If we load this file with require() in file A, and then load it again with require() in file B, file B sees the same game_loop with the same variable values. It doesn’t load a new unique instance. In effect Lua modules act like singleton objects. For the game loop this is perfect. We will only need one game loop, and many other modules will want to access it.

Here’s the game_loop module. Move all of the code here into a file named game_loop.lua.


---------------------------------------------------
--
-- game_loop.lua
--
---------------------------------------------------
local M = {}
---------------------------------------------------

local MSPF = 1000 / display.fps
local actors_array = {}
local last_ms = 0
local isRunning = false


function add( obj ) 
	if table.indexOf( actors_array, obj ) == nil then 
		actors_array[#actors_array+1] = obj
	end 
end 
M.add = add
	
function remove( obj )
	local index = table.indexOf( actors_array, obj )
	if index ~= nil then 
		table.remove( actors_array, index )
	end  
end 
M.remove = remove
	
function enterFrame( event )
	local ms = event.time
	local dt = MSPF / ( ms - last_ms )
	last_ms = ms
	
	for i = #actors_array, 1, -1 do 
		local actor = actors_array[i]
		actor:update( dt )
	end 
end 

	
function run()
	if isRunning == false then 
		Runtime:addEventListener( "enterFrame", enterFrame )
		isRunning = true
	end 
end 
M.run = run	


function pause()
	if isRunning then 
		Runtime:removeEventListener( "enterFrame", enterFrame )
		isRunning = false
	end 
end 
M.pause = pause
---------------------------------------------------
return M

Load game_loop.lua with require(“game_loop”). When using require() do not include the .lua file extension.

The game_loop object/table has four methods.

game_loop.add( obj ) — Adds obj to the game loop, obj must implement
the update(dt) method.

game_loop.remove( obj ) — Removes obj from the game loop.

game_loop.run() — Starts the game loop by adding an enterFrame listener.

game_loop.pause() — pauses the game loop by removing the enterFrame listener.

A game_loop keeps track of objects, we’ll refer to these as actors, in an array/table. Each frame game_loop sends each of the actors an update() message and passes the delta time (dt).

To use this in a game all actor objects must implement the update() method.
Actors are added to the game_loop using game_loop.add( actor ). When an actor
is to be removed from the display it should also be removed from the game_loop using

game_loop.remove( actor )

The game_loop can be stopped and started with:

game_loop.run() 
game_loop:pause()

To test this you can add the following code to main.lua in a new project. The code below first creates a new game loop. Touching the screen creates a new box. Boxes are added to the game loop that sends them update messages each frame. Touching a box removes it from the game loop, and then from the screen.

At the bottom I created two buttons to to run and pause the game loop.

-- Import the game loop module 
local game_loop = require("game_loop")
-- Start the game loop 
game_loop.run()

-- make green boxes
local function make_green_box()
	local box = display.newRect( 0, 0, 40, 40 )
	box:setFillColor( 0, 1, 0 )
	box.x = 0
	box.y = math.random( 0, 480)
	box.speed = math.random() * 3 
	
	function box:update( dt ) -- receive dt here as a parameter. 
		self.x = self.x + self.speed * dt -- Use dt, multiply by pixels per frame (speed)
		if self.x > 320 then 
			self.x = 0
		end 
	end 
	return box
end 




-- Tap a box to remove a box
local function remove_box( event )
	if event.phase == "began" then 
		-- Remove the box from the loop
		local box = event.target
		game_loop.remove( box )		-- Remove box from loop
		display.remove( box )	-- Remove box from display
	end 
	return true
end 


-- Tap the screen to add a box
local function add_box( event )
	if event.phase == "began" then
		local box = make_green_box() -- Make a new box
	
		box.x = event.x	-- Position box
		box.y = event.y
	
		box:addEventListener( "touch", remove_box ) -- Add a touch event 
	
		game_loop.add( box )	-- Add box to the game loop 
	end 
	return true
end 

Runtime:addEventListener( "touch", add_box )





local run_button = display.newRect( 31, 21, 60, 40 )
run_button:setFillColor( 0, 200/255, 0 )

local pause_button = display.newRect( 92, 21, 60, 40 )
pause_button:setFillColor( 200/255, 0, 0 )

local function touch_run( event )
	if event.phase == "began" then 
		game_loop.run()
	end 
	return true 
end 

local function touch_pause( event )
	if event.phase == "began" then 
		game_loop.pause()
	end 
	return true
end 

run_button:addEventListener( "touch", touch_run )
pause_button:addEventListener( "touch", touch_pause )

To expand on what’s here, you could imagine every actor in the actor_array as a table. These
actor tables could contain properties describing how the game_loop should treat each
actor. A simple idea might be to give each a type, and active property. As is the game
loop can be paused and run. Using this idea you could pause or run actors in groups.

Corona – Game Loop

The Game Loop is a system that organizes all of your game actions under a common timer. Imagine the heart of your game system sending out a message to all of it’s actor objects once each “tick”. Imagine a tick is a short time span between actions.

Corona, like many other software frameworks, redraws the screen at a fixed frame rate. Typically Corona projects run at 30 or 60 FPS. In other words, Corona redraws everything on the screen 60 times each second, if the frame rate is set to 60 FPS.

Corona provides an event to notify you of these updates. This event, named “enterFrame”, is fired just before each redraw. This is a perfect opportunity for your program to move objects on the screen. Imagine increasing the x property of an object by 1 each frame. The object would appear to move to the right, 60 pixels each second. The enterFrame event acts like a game loop to some extent.

The timer can also be used to create a game loop. The transition.to(), and related methods, can also be used to create animation. In this article I will focus on enterFrame.

The best way to learn is by doing. I encourage everyone to follow create these examples for themselves.

Below are a series of examples you can try for yourself.

Make a box and move it across the screen. Here we make a box. Position it on the right of the screen, about half way from the top. An enterFrame handler moves the box 1 pixel to the right each frame.


local box = display.newRect( 0, 0, 40, 40 )
box.x = 0
box.y = 200

local function on_frame( event )
	box.x = box.x + 1 
end 

Runtime:addEventListener( "enterFrame", on_frame )

make 10 boxes and move them across the screen.
This time we use a for loop to create 10 boxes.
Each box is added to an array. The enterFrame handler, on_frame,
loops through all of the boxes in box_array and moves each.


local box_array = {}

for i = 1, 10 do 
	local box = display.newRect( 0, 0, 40, 40 )
	box.x = 0
	box.y = math.random( 0, 480)
	box_array[#box_array+1] = box
end 

local function on_frame( event )
	for i = 1, #box_array do 
		local box = box_array[i]
		box.x = box.x + 1
	end
end 

Runtime:addEventListener( "enterFrame", on_frame )

This time make the boxes loop. Here we’ll check the position of each box and
move it to x = 0 when it’s x is greater than (>) 320.


local box_array = {}

for i = 1, 10 do 
	local box = display.newRect( 0, 0, 40, 40 )
	box.x = 0
	box.y = math.random( 0, 480)
	box_array[#box_array+1] = box
end 

local function on_frame( event )
	for i = 1, #box_array do 
		local box = box_array[i]
		box.x = box.x + 1
		if box.x > 320 then 
			box.x = 0
		end 
	end
end 

Runtime:addEventListener( "enterFrame", on_frame )

Give each box a different speed. Since display objects are tables new properties
can be added. Here each box is assigned a new property speed, and the speed of each
is assigned a random value between 1 and 3.
As the boxes are moved each box applies it’s own speed to it’s x so each moves
at a different rate.


local box_array = {}

for i = 1, 10 do 
	local box = display.newRect( 0, 0, 40, 40 )
	box.x = 0
	box.y = math.random( 0, 480)
	box.speed = math.random() * 3
	box_array[#box_array+1] = box
end 

local function on_frame( event )
	for i = 1, #box_array do 
		local box = box_array[i]
		box.x = box.x + box.speed
		if box.x > 320 then 
			box.x = 0
		end 
	end
end 

Runtime:addEventListener( "enterFrame", on_frame )

Give each box an update function. Here we’ve assigned each box a function
named update(). The enterFrame handler now calls the update on each box.
Notice the self reference. As we call update() on each box. The function
has a reference to the current box in self. This allows each box to set it’s
own x with it’s own speed.

Note that speed in this case is represented as pixels per frame. That is the object
will move the number of pixels as the value of speed each frame.


local box_array = {}

for i = 1, 10 do 
	local box = display.newRect( 0, 0, 40, 40 )
	box.x = 0
	box.y = math.random( 0, 480)
	box.speed = math.random() * 3
	
	function box:update()
		self.x = self.x + self.speed
		if self.x > 320 then 
			self.x = 0
		end 
	end 
	
	box_array[#box_array+1] = box
end 

local function on_frame( event )
	for i = 1, #box_array do 
		local box = box_array[i]
		box:update()
	end
end 

Runtime:addEventListener( "enterFrame", on_frame )

Make different kinds of boxes. Better to have a function to create a box of type.
Here both boxes implement the update() method.
Being able to make different types of objects that move in different ways is
very difficult using the earlier frame loop. Here it is easy since each box
implements that same method: update(). The frame loop itself doesn’t need to know
anything about the box or how it moves. The frame loop only needs to call the
object’s update(). Each object can implement update() to suit it’s needs. This
a programming concept called polymorphism.

 
local box_array = {}

-- make green boxes
local function make_green_box()
	local box = display.newRect( 0, 0, 40, 40 )
	box:setFillColor( 0, 1, 0 )
	box.x = 0
	box.y = math.random( 0, 480)
	box.speed = math.random() * 3
	
	function box:update()
		self.x = self.x + self.speed
		if self.x > 320 then 
			self.x = 0
		end 
	end 
	return box
end 

-- make red boxes
local function make_red_box()
	local box = display.newRect( 0, 0, 10, 20 )
	box:setFillColor( 1, 0, 0 )
	box.x = math.random( 0, 320 )
	box.y = 0
	box.speed = math.random() * 3 + 3
	
	function box:update()
		self.y = self.y + self.speed
		if self.y > 480 then 
			self.y = 0
		end 
	end 
	return box
end 

-- Make 10 green boxes
for i = 1, 10 do 
	box_array[#box_array+1] = make_green_box()
end 

-- Make 15 red boxes
for i = 1, 15 do 
	box_array[#box_array+1] = make_red_box()
end

local function on_frame( event )
	for i = 1, #box_array do 
		local box = box_array[i]
		box:update()
	end
end 

Runtime:addEventListener( "enterFrame", on_frame )

Using enterFrame to move objects across the screen, creates fairly smooth motion.
But it is not perfect. Imagine a scenario where the system is slowed by another
process. In a perfect world a frame rate of 30 fps would have 33.33 ms between
enterFrame events. The frame sometimes sped up or slowed down the time between
frames might go higher than this number at times. In those moments objects on the
screen would appear to move more slowly.
Prevent this type of slow down we can vary the speed of objects over time based on
the time between frames. Think about speed of objects become pixels per ms rather
pixels per frame.
The enterFrame event objects has a time property that holds the number of ms
since the app was started. Here’s a sample:

event.time

2014-05-04 20:21:58.234 Corona Simulator[359:507] 84.183
2014-05-04 20:21:58.264 Corona Simulator[359:507] 114.168
2014-05-04 20:21:58.296 Corona Simulator[359:507] 146.563
2014-05-04 20:21:58.330 Corona Simulator[359:507] 180.306
2014-05-04 20:21:58.363 Corona Simulator[359:507] 212.987

About 32ms each frame. 1000ms / 30fps = 33mspf

To find the number of ms for each frame subtract the event.time of the last frame
from event.time of the current frame. Delta is a word that describes an amount
of change. Here’s another sample:

dt

2014-05-04 20:29:10.910 Corona Simulator[359:507] 84.915 84.915
2014-05-04 20:29:10.938 Corona Simulator[359:507] 113.071 28.156
2014-05-04 20:29:10.972 Corona Simulator[359:507] 146.972 33.901
2014-05-04 20:29:11.005 Corona Simulator[359:507] 179.935 32.963
2014-05-04 20:29:11.039 Corona Simulator[359:507] 213.002 33.067

About 33 ms per frame.

The second number is the delta time. You can see the first frame was lot longer
than the other frames, starting the app probably has some overhead. The second frame
is shorter than it should be. After this the other frames settle in very close to
33 ms. This app doesn’t have much going on. If there was more happening we might see
longer frames appear every so often. In other words objects on the screen would
slow down or speed up.

To calculate delta as a function of the frame rate divide the difference by the
frame rate. Then multiply this number by the pixels per frame your object wants to move.

Think about it this way. If the frame rate of the project is 30, the number of ms per
frame is 1000 / 30 or 33 (really it’s 33.333)

If the delta time for a frame is 33,

33/33=1

Multiply this by the number of pixels per frame your object should move. If your
object was supposed to move 10 pixels per frame then 1 * 10ppf = 10 pixels.

Now a imagine a long frame where the computer has slowed for some reason, delta time
might be 40ms.

40/33 = 1.2

Multiply by the same 10 pixels per frame and you get 12. This frame the object moved
a little further to compensate for game lag.

We can incorporate this system by passing the delta time divided by the frame rate to
to each object as a parameter of update(). Now each object can use this value to handle
it own move in any way it chooses.

Note: This system is still imperfect! In extreme situations you might pass a large
number that might move an a larger distance. Imagine if delta passed 2, 5 or 10! Your
object might 20, 50 or 100 pixels in one frame. This can move an object through other
objects causing your game to miss a collision. Delta time should probably have a cap
to set a maximum value. In these cases the game will slow by the system won’t break.


local box_array = {}

-- make green boxes
local function make_green_box()
	local box = display.newRect( 0, 0, 40, 40 )
	box:setFillColor( 0, 1, 0 )
	box.x = 0
	box.y = math.random( 0, 480)
	box.speed = math.random() * 3 
	
	function box:update( dt ) -- receive dt here as a parameter. 
		self.x = self.x + self.speed * dt -- Use dt, multiply by pixels per frame (speed)
		if self.x > 320 then 
			self.x = 0
		end 
	end 
	return box
end 

-- Make 10 green boxes
for i = 1, 10 do 
	box_array[#box_array+1] = make_green_box()
end 


local last_ms = 0				-- Last time in ms
local mspf = 1000 / display.fps	-- milliseconds per frame
local function on_frame( event )
	-- 
	local ms = event.time
	local dt = ms - last_ms
	last_ms = ms
	
	-- print( event.time, dt )
	
	dt = dt / mspf -- divide by frame rate
	
	for i = 1, #box_array do 
		local box = box_array[i]
		box:update( dt )	-- Pass the delta time to update
	end
end 

Runtime:addEventListener( "enterFrame", on_frame )

Corona – Display objects properties practice

Here’s a few ideas if you want to practice your programming skills.

Let’s talk about display objects. All of the display objects act the same way and support the same properties. This includes, images, shapes, like the rectangle and circle, text objects. These properties also apply to the group. Think of a group as an empty display container that you can add other objects. It’s like a layer in Illustrator.

Display objects have the properties that determine how they are displayed. Properties are always accessed with the dot (.), and you set their value with the equal sign. For example:

obj.property = value

Here’s a list of properties.

x – horizontal position

y – Vertical position

xScale – horizontal scale

yScale – vertical scale

anchorX – horizontal position of the object’s anchor point

anchorY – vertical position of the object’s anchor point

Here’s a few things to try with this. Create a new project with the default settings. In main.lua add the following at the top.

local box = display.newRect( 0, 0, 40, 40 )

This should create a rectangle in the upper left corner. The first two parameters (0,0) set the x and y initially. The center of the object is located at the upper left corner.

Set the position of the box to the center of the screen. Since the default size is 320 by 480 the center is 160, 240.
 box.x = 160
 box.y = 240

Set some other properties.

box.rotation = 33 -- this degrees
 box.xScale = 0.5 -- should be 50% scale on the horizontal
 box.yScale = 2 -- should be 200% on the vertical
 box.alpha = 0.5 -- Should be 50% transparent

Try changing these values to see what happens. You could have done all of this with any other type of display object like text, or images.

Generate a random number with math.random(). This can be used in two ways. Either to generate a random number from 0 to 1, for example 0.826727384. Or generate an integer value between any two numbers. For example 1 to 6. Here’s what this would look like in code form:

math.random() -- something like 0.826727384
math.random( 1, 6 ) -- a random from 1 to 6.

You can test these in the terminal with

print( math.random() )
print( math.random(1,6) )

Apply this to the box:

box.x = math.random( 40, 280 ) -- Moves the anywhere from x 40 to x 280.

You can make this interactive with:

local function move_box( event )
box.x = math.random(40, 280)
end
box:addEventListener( "tap", move_box )

Tap the box and it moves to a random position. Randomize the y property of box on your own.

This would be more interesting with some motion. Modify the function above to look like this:

local function move_box( event )
transition.to( box, {x=math.random(40, 240), time=1000} )
end
box:addEventListener( "tap", move_box )

Animate the y on your own.

Let’s make this more challenging. Make 10 boxes. Use a loop. The basic loop syntax looks like this:

for i = 1, 10 do
-- repeat this code 10 times
end

so to make 10 boxes. Use the following.

for i = 1, 10 do
local box = display.newRect( 0, 0, 30, 30 )
box.x = math.random( 40, 280 )
box.y = math.random( 40, 440 )
end

You should have 10 boxes all over the screen. Here’s where things get interesting. Since you have declared box as local within the loop this variable is local to that code block it isn’t accessible outside the loop.

Try this, remove all of the other code except for the code below.

for i = 1, 10 do
local box = display.newRect( 0, 0, 30, 30 )
box.x = math.random( 40, 280 )
box.y = math.random( 40, 440 )
end
box.x = 100 -- error on this line!

You should get an error message pointing to the last line. Read the error message closely, it should include the line number for the last line: box.x = 100. We can’t access box, since it’s local to the loop!

Beside this which box would be accessing? We’d like to get to tap on any of the boxes and have them move and spin to a new location.

Add this function above the loop.

local function move_box( event )
 local new_x = math.random( 40, 280 )
 local new_y = math.random( 40, 440 )
 local new_rotation = math.random( 0, 360 )
 transition.to( box, {x=new_x, y=new_y, rotation=new_rotation, time=1000} )
 end
for i = 1, 10 do
local box = display.newRect( 0, 0, 30, 30 )
box.x = math.random( 40, 280 )
box.y = math.random( 40, 440 )
box:addEventListener( "tap", move_box )
end

Add the text in red to the loop. This still won’t work. Box is not accessible remember? We’re talking about this line in move box:

transition.to( box, {x=new_x, y=new_y, rotation=new_rotation, time=1000} )

The event object has a reference to the box that generates the event. Each box has been assigned an event listener. When tapping a box, that box will generate the event. In this way move_box will know which box to move. Edit the line above:

transition.to( event.target, {x=new_x, y=new_y, rotation=new_rotation, time=1000} )

The event variable is a table containing properties describing the event that just occurred. One of those properties, target, contains a reference to the object that generated the event. Try it now.

Sidescrolling endless runners

If you haven’t played Canabalt, you should give it a try. This is one of the games to define the single button endless runner type games. the original was made in Flash. There’s also an IOS and Android version. I hear the Android version is better with different worlds and things.

Essentially the gist of the genre is that you are running forward avoiding obstacles. things get tougher as the game progresses. There’s lots of variation. I’m linking to an article here by the author of Canabalt talking about what went into making Canabalt and the decisions for different screen sizes, and game mechanics. Very informative if you wanted to make a similar game.

http://blog.semisecretsoftware.com/post/44317538718/tuning-canabalt

Corona SDK – Physics – chains

Playing with physics joints today. A common physics effect is to create chain. A chain in Corona SDK is a group of physics objects joined together with a Pivot joint. Create a chain by creating a series of display objects, use physics.addBody() to turn them into physics bodies, and last create a joint between each object connecting them in series.

A chain will often contain many links. This means that you will end up creating many physics bodies, and a joint a between pair. This is a lot of objects. Best to use a Loop here.

Create a joint between two physics objects with physics.newJoint(). The method takes 5 parameters:

physics.newJoint( "pivot", object1, object2, anchorX, anchorY )
  •  “pivot” – Sets the type of joint to pivot. 
  • object1 – first object in the joint.
  • object2 – second object in the joint.
  • anchorX – X position of of the joint between the two objects.
  • anchorY – Y position of the joint between the to objects.

The anchorX and anchorY set a common point where object1 and object2 are connected.

Here’s a simple function that makes a chain made of any number of rectangular links.

local function make_chain( x, y, w, h, c )
	local prev_link
	for i = 1, c do 
		local link = display.newRect( x, y+(i*(h+1)), w, h )
		if i == 1 then 
			physics.addBody( link, "static" )	
		else 
			physics.addBody( link, "dynamic" )	
			link.linearDamping = 1
			link.angularDamping = 11
		end 
		if i > 1 then 
			print( i )
			physics.newJoint( "pivot", prev_link, link, x, prev_link.y + (h*0.5) )
		end 
		prev_link = link
	end 
end 

This function takes 5 parameters

  • x – The x position of the first link.
  • y – The y position of the first link.
  • w – Width of each link.
  • h – Height of each link.
  • c – (Count) the number of links in the chain.

The first chain link is a static and so supports the chain.

For testing try the code below. Make a new default project in Corona and paste the following into main.lua. This example creates a chain, and a circle. Swipe to shoot the ball. The ball helps give you an idea how the chain reacts. 

local physics = require( "physics" )
physics.start()
physics.setDrawMode("hybrid")
-- physics.setContinuous( false )
physics.setVelocityIterations( 16 )

local function make_chain( x, y, w, h, c )
	local prev_link
	for i = 1, c do 
		local link = display.newRect( x, y+(i*(h+1)), w, h )
		if i == 1 then 
			physics.addBody( link, "static" )	
		else 
			physics.addBody( link, "dynamic" )	
			link.linearDamping = 1
			link.angularDamping = 11
		end 
		if i > 1 then 
			print( i )
			physics.newJoint( "pivot", prev_link, link, x, prev_link.y + (h*0.5) )
		end 
		prev_link = link
	end 
end 

make_chain( 160, 10, 20, 20, 10 )
-- make_chain( 160, 10, 20, 100, 3 )
-- make_chain( 160, 10, 10, 30, 5 )
-- make_chain( 160, 10, 5, 10, 20 )
-- make_chain( 80, 10, 5, 10, 20 )
-- make_chain( 240, 10, 5, 10, 20 )


local floor = display.newRect( 160, 480, 320, 10 )
physics.addBody( floor, "static" )
local left = display.newRect( 0, 240, 10, 480 )
physics.addBody( left, "static" )
local right = display.newRect( 320, 240, 10, 480 )
physics.addBody( right, "static" )
local top = display.newRect( 160, 0, 320, 10 )
physics.addBody( top, "static" )

local ball = display.newCircle( 160, 300, 30 )
physics.addBody( ball, "dynamic", {radius=30} )

local function shoot( event ) 
	if event.phase == "ended" then 
		local dx = event.x - event.xStart
		local dy = event.y - event.yStart
		ball:applyLinearImpulse( -dx * 0.01, -dy * 0.01, ball.x, ball.y )
	end 
end 

Runtime:addEventListener( "touch", shoot )

 

Ceramic Tile Engine and Tiled

Tiled is a desktop application that helps create tile maps from sprite sheets. Ceramic Tile Engine is a library for use with Corona that displays the data from Tiled. Two great tools that work great together. The demo provided with Ceramic has a really nice platform game example.

Tile maps are larger images created from smaller tiles. By using, and reusing, small tiles large environments can be created. Since a single image containing a few small tiles takes up much less memory than the image created with the tiles tile maps are more efficient.

Tiled is an application you can use to create tile maps. Tiled is generic and not tied to any other application or programming language. You’ll use it to build maps and export a text file describing your map. Usually this will be in the Json format.

Here are a few links:

Discussion on the Corona SDK forum

Ceramic documentation on GitHub

Ceramic Tiled Engine on Github

Video demo using Corona SDK and Tiled together

Corona SDK – Scrolling landscape

Here are a few ideas to get started creating a scrolling background. Create a background image that repeats, where the left edge would tile seamlessly when connected to the right edge. Copy a section the size of the visible area of the screen and add it to the right side of the image.

Here are a couple images for example. Look at the images carefully and you will see the the 480 pixels on the right side match the first 480 pixels on the left.

Landscape-1

 

Landscape-2 Landscape-3
These images link to the originals at full size. You can download them to use with the example code which follows.

 

Here’s a simple example that works with a single image.

 

local landscape = display.newImageRect( "landscape-1.png", 1440, 320 )

-- landscape:setReferencePoint( display.TopLeftReferencePoint )
landscape_1.anchorX = 0
landscape_1.anchorY = 0
landscape_1.x = 0
landscape_1.y = 0

local function reset_landscape( landscape )
	landscape.x = 0
	transition.to( landscape, {x=0-1440+480, time=30000, onComplete=reset_landscape} )
end

reset_landscape( landscape_1 )

Here’s an example that takes the code above and turns it into a function allowing you to create more animated landscapes without having to duplicate the code.


local function make_landscape( image, width, height, time )
	local landscape = display.newImageRect( image, width, height )

	-- landscape:setReferencePoint( display.TopLeftReferencePoint )
	landscape.anchorX = 0
	landscape.anchorY = 0	
	landscape.x = 0
	landscape.y = 320 - height
	landscape.time = time
	
	local function reset_landscape( landscape )
		landscape.x = 0
		transition.to( landscape, {x=0-landscape.width+480, time=landscape.time, onComplete=reset_landscape} )
	end
	
	reset_landscape( landscape )
	
	return landscape
end 

local landscape_group = display.newGroup()

local landscape_1 = make_landscape( "Landscape-1.png", 1440, 86, 10000 )
local landscape_2 = make_landscape( "Landscape-2.png", 1440, 168, 20000 )
local landscape_3 = make_landscape( "Landscape-3.png", 1440, 215, 30000 )

landscape_group:insert( landscape_3 )
landscape_group:insert( landscape_2 )
landscape_group:insert( landscape_1 )

Corona – config.lua and making universal apps

Here’s a link to a couple articles on the Corona web site about making apps to fit a wide range of screen sizes. Be sure to comments there’s a lot of good questions and answers there. The second articles takes the whole concept to a very elegant solution.

  1. http://www.coronalabs.com/blog/2012/12/04/the-ultimate-config-lua-file/
  2. http://coronalabs.com/blog/2013/09/10/modernizing-the-config-lua/