Category Archives: Corona SDK

How to find your Google Plus ID

This is so simple

1. Go to your Google + account (https://plus.google.com/).

2. Click on the Profile icon on the Left.

3. If you look at the URL in the address bar, it should look something like this:

https://plus.google.com/104653270154306099169/posts

4. The long numerical string in the URL is your Google+ ID. Here is CoderzHeaven’s from the URL above:

104653270154306099169/

Google + CoderzHeaven

How to Play Audio using Corona SDK ?

Hi,

For playing audio – background music or sound effects – using Corona SDK, do the following,

1. Load the audio stream (background music or sound effects)

 backgroundMusic = audio.loadStream("bgm.mp3") 

2. Play the audio

backgroundMusicChannel = audio.play( backgroundMusic, { channel=1, loops=-1, fadein=5000 }  )  

It will play the background music on channel 1, loop infinitely, and fadein over 5 seconds. Loop 1 will set it to play once!

:)

How to enable retina Mode in Corona SDK? or How to work with images in retina Mode in Corona?

To enable retina mode in your application you have to first find the config.lua file in your project folder.

Then edit this file to include the contents like this.

application =
{
	content =
	{
		width = 320,
		height = 480,
		scale = "letterbox",
		imageSuffix =
			{
				["-x15"] = 1.5,		-- A good scale for Droid, Nexus One, etc.
				["-x2"] = 2,		-- A good scale for iPhone 4 and iPad
			},
	}
}

You have to include images twice the size(["-x2"] = 2) and about 1.5 the size (["-x15"] = 1.5) in your project folder. These images should have correspondingly these suffixes at the end.
your_image_name-x2.png or jpg for x2(double size) images and
your_image_name-x15.png or jpg for x15 (1.5 size images) images

Corona SDK will automatically detect the right images for retina display according to the device. For example if the device has no retina display then it will take images with no x2 suffix and like that.

Please leave your valuable comments if this post was useful.

How to get the elapsed time after app launch in Corona ?

In order to get the elapsed time after the application launch in Corona, use the following lines of code,

function elapsedTimeCalc( event )
  print ("Time elapsed since app launch---"..event.time/1000 )
end

Runtime:addEventListener("enterFrame", elapsedTimeCalc)

Thus we will get the elapsed time after the app launch in milliseconds.

:)

How to download an image in corona SDK?

Downloading an image in corona is really easy.
Check out the example.


	module(..., package.seeall)

	_W = display.contentWidth;
	_H = display.contentHeight;

	function new()
		local grp = display.newGroup();
		local myImage;

		local function networkListener( event )
			if ( event.isError ) then
					print ( "Network error - download failed" )
			else
					myImage = display.newImage( "helloCopy.png", system.TemporaryDirectory, 60, 40 )
					myImage.alpha = 0
					transition.to( myImage, { alpha = 1.0 } )

			end

			print ( "RESPONSE: " .. event.response )
				grp:insert(myImage)
	end

	network.download( "http://developer.anscamobile.com/demo/hello.png", "GET", networkListener, "helloCopy.png", system.TemporaryDirectory )

	return grp;

	end

Check the console to see where the downloaded file is saved.

Download the complete source code from here.

Gradient Text in Corona

To create gradient text in corona, you have to download ‘Corona daily build 612′ which has functions like setFillColor() etc.
You create a new gradient object by calling graphics.newGradient().
You can pass (and reuse) the object in calls to text:setTextColor() and rect:setFillColor().

Here is an example.

local myText =
    display.newText( "Hello, World!", 0, 0, native.systemFont, 40 )
myText.x = display.contentWidth * 0.5
myText.y = display.contentWidth * 0.25
local g = graphics.newGradient( { 180, 180, 0 }, { 255 }, "down" )
myText:setTextColor( g )

Problem with touch in Corona on multiple views solved.

Hello everyone..
There has been a problem with corona that when you place one view over the other and when you touch the object in front of the other, touch will be migrated to the object below it. To prevent this there is a mechanism in corona.
Here is how we solve this in corona.

display.getCurrentStage():setFocus( your_touched_obj)

here is a sample code.


local img1 = display.newImage("android_1.png")
local img2 = display.newImage("android_2.png")

function touchedImageOne()
	print ("touched Image One")
end

function touchedImageTwo()
	print ("touched Image two")
end

display.getCurrentStage():setFocus( img2 )
img1:addEventListener("tap",touchedImageOne);
img2:addEventListener("tap",touchedImageTwo);

Check the console for the output
Here is a source code example for this project.

Most Common and most important String functions in Corona.

Here are some of the string functions that are most commonly used in Corona SDK.
In this example you can find all the common string functions with a wroking example for each.
This example contains functions to

1. Check the first character in a string
2. Check the last character in a string.
3. Changing the first character in a string to uppercase.
4. Toggling the case.
5. Splitting a string.
6. Email validation.
7. Getting the character from it’s ASCII value.
8. Finding a pattern in a string.
9. Splitting a sentence into words.
10. Changing to lowercase, uppercase and reversing a string.


print ("String functions in Corona");

-- Function to check whether the first character is the given character. --
function startWith(String, search_char)
	return(string.sub(String,1,string.len(search_char)) == search_char);
end

-- Function to check whether the last character is the given character. --
function endsWith(String, search_char)
	return(string.sub(String,-string.len(search_char)) == search_char);
end

--Function to change the first character of a string to upper case --
function changeFirstCharToUpperCase(String)
	return String:gsub("^%l", string.upper)
end

function ToggleCase(String)
	return string.gsub (String, "%f[%a]%u+%f[%A]", string.lower)
end

-- Iterating through words in a string.
function getWords(String)
	local i = 1;
	for word in String:gmatch("%w+") do
		print("word "..i.." : "..word);
		i = i+ 1;
	end
end

local str = "CoderzHeaven";
local search_first_char = "C";
local search_end_char = "n"

if(startWith(str,search_first_char)) then
    print("startWith : "..search_first_char);
else
	print ("Doesnot start with "..search_first_char);
end

if(endsWith(str,search_end_char)) then
    print("endsWith : "..search_end_char);
else
	print ("Doesnot end with "..search_end_char);
end

str = "coderzHeaven";
print ("changeFirstCharToUpperCase : "..changeFirstCharToUpperCase(str))

str = "CoderzHeaven Heaven of all working codes";
print("ToggleCase : "..ToggleCase(str));

getWords(str);

--- Check whether this is a correct format of email address....
email="coderzheaven@gmail.com"
if (email:match("[A-Za-z0-9%.%%%+%-]+@[A-Za-z0-9%.%%%+%-]+%.%w%w%w?%w?")) then
  print(email .. " is a valid email address")
else
	print('Invalid email address')
end

-- Get the charater from it's ASCII Value.....
print('ASCII Value of char : '..string.char (65))

--Looks for the first match of pattern in the string s.
--If it finds a match, then find returns the indices of s
--where this occurrence starts and ends; otherwise, it returns nil.
print(string.find (str, 'der',2,false ));

--Returns a formatted version of its variable number of arguments following
--the description given in its first argument (which must be a string)
print( string.format('%q', 'a string with "quotes" and n new line'));

local s = "hello world from CoderzHeaven"
 for w in string.gmatch(s, "%a+") do
   print(w)
 end

 --Find String Length
 print("length : "..string.len(s));

 -- Change to Lowercase
 print(string.lower (s));

 --Reverse a string
 print(string.reverse (s));

 --Change to Uppercase.....
 print(string.upper (s))

Different ways to trim a string in Corona SDK.

Here are the different ways to trim a string in Corona SDK.


-- CoderzHeaven String Trimming examples in Corona.
-- Here you can see different methods for trimming a string in corona.

function trim1(s)
  return (s:gsub("^%s*(.-)%s*$", "%1"))
end

function trim2(s)
  return s:match "^%s*(.-)%s*$"
end

function trim3(s)
  return s:gsub("^%s+", ""):gsub("%s+$", "")
end

function trim4(s)
  return s:match"^%s*(.*)":match"(.-)%s*$"
end

function trim5(s)
  return s:match'^%s*(.*%S)' or ''
end

-- has bad performance.. use at your own risk.
function trim6(s)
  return s:match'^()%s*$' and '' or s:match'^%s*(.*%S)'
end

local str = " CoderzHeaven ";
print("--------------Trimming a string in Corona SDK---------------");
print ('Str Original Length Length : '..string.len(str))

str = trim1(str);
print ('Str Length using First Function  : '..string.len(str))

-- reassigning to check trim function using other functions.
str = " CoderzHeaven ";
str = trim2(str);
print ('Str Length using second function : '..string.len(str))

str = " CoderzHeaven ";
str = trim3(str);
print ('Str Length using third function  : '..string.len(str))

Please check the console for the output.

Download the source code from here

Getting started with Corona

In the previous post I told you about corona SDK and Today I will show you how to get started with Corona SDK.

1. First Go to http://www.anscamobile.com/corona/ and download the SDK for trial.
2. If you are a MAC user then download the dmg or if you are windows user then download the exe installer.
3. Open the file and install it in your system.
4. Now the Corona SDK comes with a lot of samples.
For that go to your corona installed directory and inside that a folder named samples is there.
Open a sample and locate main.lua file, right click on it and run in corona simulator.
5. Now the corona simulator will come up select continue trial and your sample code will run now.
6. Now go on and change the code as you like.
7. If you want to see the console then locate the “Corona.Debugger”( In windows) file and Run it-> it is your console.
8. Explore the rest of the sample code and have fun
.

Building games for android and iPhone

Today I will talk about building games for android and iPhone.
There are a lot of SDK’s available for building games over the internet and I am here to talk about the CORONA SDK.

Corona SDK is a software development kit created by Walter Luh, co-founder of Ansca Mobile. It allows software programmers to build mobile applications for the iPhone, iPad, and Android devices.
Corona lets developers use integrated Lua, layered on top of Objective-C, to build graphically rich applications that are also lightweight in size and quick in development time. The SDK does not charge per-app royalty or impose any branding requirement, and has a subscription-based purchase model that allows new features to be rolled out immediately to user

Check out this site for more information about corona

http://www.anscamobile.com/corona/

You can also some of our tutorials also here.
In the coming posts we will be adding more about coding in Corona.

Check out this link to get access to the corona documentation.

Destroying Box2D Physics Bodies in Corona SDK

Hi,

For destroying physics bodies in Corona SDK, use any of the following methods.

urBody:removeSelf()

OR

urBody.parent:remove( urBody )

Note :
While Box2D objects will be safely retained until the end of the current world step, their Lua references will be deleted immediately. Therefore, be careful not to accidentally delete the same Lua object more than once. This situation could occur when deleting objects involved in collisions, which can potentially have many event phases before the collision is fully resolved. The solution is simple:

local function onCollision( self, event )
        if ( event.phase == "began" ) then

                -- Check if body still exists before removing!
                if ( urBody ) then
                        urBody:removeSelf()
                        urBody = nil
                end

        end
end

:)

How to set a tilt based gravity using Corona accelerometer ?

Hi,

For setting a tilt based gravity using Corona Accelerometer, use the following sample of code.


local function urTiltFunc( event )
        physics.setGravity( 10 * event.xGravity, -10 * event.yGravity )
end

Runtime:addEventListener( "accelerometer", urTiltFunc )

:)

How to get touch location in Corona ?

Hi,

For getting touch location in Corona, use the following code,


--Your touch event listener
 local function myTouchListener( event )
        if event.phase == "began" then
        --Touch coordinates can be accessed by event.x/event.y properties of touch event
            print( "Touched!" )
            print ("Touch X = #"..event.x)
            print ("Touch Y = #"..event.y)
        end
    end

--Adding an event listener for touch
Runtime:addEventListener( "touch", myTouchListener )

How to get touch 'began', 'moved' & 'ended' in Corona ?

Hi,

For getting touch ‘began’, ‘moved’ & ‘ended’ in Corona, use the following code.

--Your touch event listener
 local function myTouchListener( event )
        if event.phase == "began" then
            print( "Touched!" )
        elseif event.phase == "moved" then
            print( "Touches Moved!" )
        elseif event.phase == "ended" then
            print( "Touches Ended!" )
        end
    end

--Adding an event listener for touch
Runtime:addEventListener( "touch", myTouchListener )

:)

How to add label/text to image in Corona ?

Hi,

For adding a label/text to an image in Corona, using Lua, use the following code,


local urGroup = display.newGroup()

local urImage = display.newImageRect('sample.png',70,70)
urImage.x = 150
urImage.y = 250

local urText = display.newText( "SampleText", 0, 0, "Helvetica", 22 )
urText:setTextColor( 0, 0, 0, 255 )

-- insert items into group, in the order you want them displayed:
urGroup:insert( urImage )
urGroup:insert( urText )

:)