Android Game Development Tutorials

download Android Game Development Tutorials

of 201

Transcript of Android Game Development Tutorials

  • 8/9/2019 Android Game Development Tutorials

    1/201

    Android Game Development TutorialsPublished on June 15, 2011 |171,043 views |Filed in:Android GamesTags:featured

    ome months a!o we re"eived an email from a fellow Java develo#er, Tamas Jano, as$in! to be

    #art of our J%G#artners #ro!ram& 'o our sur#rise he maintains a blo! named (A!ainst 'he

    Grain) debatin! about !ame develo#ment for the Android #latform& * have been readin! all of hisarti"les sin"e then and * must admit that his writin!s have been an ins#iration and a motivation

    for me and m+ "ollea!ues here atJava Code Geeksso as to start develo#in! our first !ame for

    the Android #latform&

    ith this #ost * would li$e to #resent Tamas-s wor$ to our "ommunit+ ho#in! that +ou will be

    ins#ired and motivated .ust li$e we did/

    hat follows is a #ortion of Tamas-s introdu"tor+ arti"letitled as (A little motivation and

    whats the idea behind all this.) * am "ertain that after readin! it +ou will realie .ust li$e * didthat +ou have man+ man+ thin!s in "ommon with this !u+/

    irst of all * $now no !reat "oder who is not interested in !ames& ome love slow #a"ed ones

    while outdoors+ !ee$s +es the+ do eist will have a !o with an+ t+#e that reuires all those

    reflees some .ust won6t develo#& At some #oint in their lives the+ mi!ht have wondered how thehell is this done ouldn6t it be "ool to ma$e su"h a thin! *6d love to do that&

    And so the+ went, !ettin! into "om#utin! fueled b+ a #assion for "reatin! worlds the+ own and

    "ommand& 8a"$ in the da+s +ou would see these !u+s at the ar"ades, han!in! around "om#uter

    labs and dreamin! of ownin! one of those ma!nifi"ent ma"hines the+ "an "reate their universeon& *6m tal$in! about the 90s&

    :an+ too$ the "lasses, went throu!h all that ne"essar+ "ra# that "omes with !ettin! a de!ree onewould not "are about in the future and here the+ are& ome !raduated and have de"ent #a+in!

    (software en!ineer) #ositions wor$in! for a multinational "or#oration doin! who $nows what&8ut a #er"enta!e of these so "alled en!ineers dream of !ames& 'he+ own the latest !ad!ets but

    the+ do not have the one thin! that would enable them to ma$e !ames; 'ime& or$in! nfortunatel+ man+ never even !et started&

    ?ow man+ thou!ht; man@*6ll be buildin! the !reatest !ame of all, *6ll be ri"h and famous& 'hen

    the+ meet someone, have to !et a .ob to #a+ for (settlin!) down and #a+ the bills for a #la"e

    where the+ !o in the evenin!s to "rash .ust to start it over the net da+& All this b+ doin! borin!

    web stuff or wor$in! on a small #art of a monstrous multi=threaded distributed enter#risea##li"ation ar"hite"ted b+ an ine#erien"ed halfwit ar"hite"t wannabe who !ot the .ob b+

    sti"$in! with the "om#an+ sin"e he was an intern&

    here is the !ame +ou dreamed of doin! 10 +ears a!o

    'o be #re"ise * am in a similar situation and while * had a short !i! with a !ame "om#an+ * am

    well in the rat ra"e leadin! nowhere& * have de"ided to tr+ one more time and * will !ive it a !o&

    http://www.javacodegeeks.com/android/android-gameshttp://www.javacodegeeks.com/android/android-gameshttp://www.javacodegeeks.com/android/android-gameshttp://www.javacodegeeks.com/tag/featuredhttp://www.javacodegeeks.com/tag/featuredhttp://www.javacodegeeks.com/tag/featuredhttp://www.javacodegeeks.com/p/jcg.htmlhttp://obviam.net/http://obviam.net/http://obviam.net/index.php/a-little-motivation/http://obviam.net/index.php/a-little-motivation/http://www.javacodegeeks.com/tag/featuredhttp://www.javacodegeeks.com/p/jcg.htmlhttp://obviam.net/http://obviam.net/http://obviam.net/index.php/a-little-motivation/http://www.javacodegeeks.com/android/android-games
  • 8/9/2019 Android Game Development Tutorials

    2/201

    h+ Just for the hell of it, to demonstrate that !ames are sim#le to build and +ou "an sit at +our

    "om#uter and have some fun too& A"tuall+ this is wh+ * ended u# a "oder, to ma$e !ames not to

    "onfi!ure some framewor$s +es, that is not #ro!rammin!, it is mostl+ "onfi!uration&

    ell was * ri!ht * ho#e * was/

    As * told +ou beforeJava Code Geekshave been bus+ enou!h develo#in! our first !ame for the

    Android #latform& A new "ate!or+ named (Android Games) has been "reated in order to "ontain

    all !ame related arti"les from now on&

    ?ere is the list of all Android Game evelo#ment tutorials u# until now for +our referen"e;

    1& 'he Game *dea

    2& %reate the Pro.e"t

    3& A 8asi" Game Ar"hite"ture

    4& A 8asi" Game Boo#

    5& is#la+in! *ma!es

    C& :ovin! *ma!es

    7& 'he Game Boo#

    9& :easurin! P

  • 8/9/2019 Android Game Development Tutorials

    3/201

    19& Android Game evelo#ment with lib!d E Protot+#e in a da+, Part 1a

    1

  • 8/9/2019 Android Game Development Tutorials

    4/201

    e have one !u+& ?e6s !ot 3 lives and a !un& ?e6ll be dro##ed in the middle of a room and some

    baddies are tr+in! to $ill him alread+&

    e have the basi" information to s$et"h out our !ame stru"ture&8ut, we don6t have a name& Bet6s see, droids ta$in! over the #lanet@"he"$ed !oo!le for

    (droid) and (droid !ame) !uess what Ho droid !ame found& * will name this; (droid)&

    * find it a "ool name for the first !ame usin! android&

    Above +ou have a rou!h mo"$=u# of what the !ame will loo$ and feel li$e& 'he 2 !re+ "ir"les are

    the "ontrollers& *ma!ine the devi"e bein! held horiontall+ and +ou have +our thumbs on the"ir"les& our left thumb will move our hero while the ri!ht thumb will fire the wea#on& 'he

    dire"tion is bein! "ontrolled b+ the #osition of +our thumb relative to the "ir"le6s "entre&

    How that we have the idea let6s identif+ what we need to !et the !ame done&

    e need the !ame ob.e"ts& %urrentl+ there are 2 t+#es of a"tors in this& Fur !u+ and the droids&

    'o "ontrol our !u+ we need to re"eive user in#ut& 'he user in#ut will be the tou"h s"reen& 'o bemore #re"ise the 2 "ir"les defined on the s"reen& Fne "ontrols the !u+6s #osition and the other his

    wea#on&

    A t+#i"al !ame ar"hite"ture loo$s li$e this;

    1& Pro"ess in#ut

    2& >#date state of !ame ob.e"ts& 'his means "al"ulate new #ositions for ever+ item, "he"$!ame lo!i", "ollisions et"

    3& Produ"e sounds

    4& Kender state to s"reen

    5& *f !ame is not over re#eat from ste# 1

    or eam#le; Fur !u+ is in the middle& roids move ever+ 1L10 of the se"ond towards him&Dver+ tenth of a se"ond we "he"$ if the s"reen was tou"hed and if it was tou"hed we move our

  • 8/9/2019 Android Game Development Tutorials

    5/201

    !u+ or fire his wea#on& *f the wea#on was fired we "he"$ ever+ ti"$ that6s 1L10 s if the bullett

    "ollided with an+ droid to destro+ him& *f "ollided then droid is destro+ed and the bullett is also

    destro+ed& *f no "ollision then both droid6s and bullett6s new #ositions are "al"ulated a""ordin! totheir s#eed droid moves 5 #iels ever+ 1L10 s for e and the bullett moves 50& e also "he"$ if

    the droid "ollided rea"hed our !u+ and if so our hero is dead and !ame over&

    'his is an overview of how this !ame will wor$ but will etend it as we !o&

    Reference:'he Game *deafrom our J%G#artner 'amas Jano from (A!ainst 'he Grain) blo!&

    o not for!et to "he"$ out our new Android GameArkDroids"reenshots below& ou feedba"$will be more than hel#ful/

    http://obviam.net/index.php/step-1-the-game-idea/http://www.javacodegeeks.com/p/jcg.htmlhttp://obviam.net/http://www.javacodegeeks.com/2011/06/jcg-studios-arkdroid-official-launch.htmlhttp://obviam.net/index.php/step-1-the-game-idea/http://www.javacodegeeks.com/p/jcg.htmlhttp://obviam.net/http://www.javacodegeeks.com/2011/06/jcg-studios-arkdroid-official-launch.html
  • 8/9/2019 Android Game Development Tutorials

    6/201

    Android Game Development Create TheProjectPublished on Jul+ 3, 2011 |99,912 views |Filed in: Android Games

    How that we have our idealet6s !et the environment u# and start "odin!&

    'o install Android follow the ste#s found on the offi"ial do"umentation#a!e& * use e"li#se so if

    +ou are a Java !u+ it should be #rett+ familiar& *f +ou have never develo#ed in Java but did some

    other "odin! in %MM or %N for eam#le it should be #rett+ sim#le to "at"h u#& * would

    re"ommend startin! with some Java tutorials and then swit"h to Android& *f +ou haven6t#ro!rammed before@well that6s thou!h but it6s solvable& Goo!le for some #ro!rammin!

    tutorials and don6t !et dis"oura!ed/ 'hen "he"$ ba"$ here&

    * will use Android 2&2 as it is the latest at the time of this writin! and * sus#e"t it will ta$e a lon!time till * finish this #ro.e"t so it .ust mi!ht be uite used& Also be"ause we #lan to use multi=

    tou"h we need version 2&&

    irst let6s "reate the A Android irtual evi"e& %li"$ on the little Android i"on or "hoose

    indow =O Android and A :ana!er and "li"$ on the Hew@ button&

    et the name to :+evi"e, the tar!et to Android 2&2 E AP* Bevel 9& et 129 :i8 for the %ard& et the $in to 8uilt=in ?GA and the ?ardware to Abstra"ted B% densit+ to 1C0& 'hese

    are the "urrent default settin!s&

    http://www.javacodegeeks.com/android/android-gameshttp://www.javacodegeeks.com/android/android-gameshttp://www.javacodegeeks.com/2011/07/android-game-development-game-idea.htmlhttp://developer.android.com/sdk/index.htmlhttp://www.javacodegeeks.com/android/android-gameshttp://www.javacodegeeks.com/2011/07/android-game-development-game-idea.htmlhttp://developer.android.com/sdk/index.html
  • 8/9/2019 Android Game Development Tutorials

    7/201

    %li"$ %reate A and the virtual devi"e should be "reated&

    How let6s "reate the #ro.e"t&

    ele"t from the menu; Hew =O Pro.e"t and "hoose Android Pro.e"t&

    ill in as #er the s"reen=shot and "li"$ inish&

    'he A##li"ation name is the name !iven to our !ame& 'he #a"$a!e name is .ust the name s#a"e

    to !rou# our "lasses&

    ele"t Android 2&2 for 8uild 'ar!et&

    'he most im#ortant is the %reate A"tivit+& 'he A"tivit+ is the "lass instantiated when the

    a##li"ation is started& on6t have to worr+ about it ri!ht now .ust remember that is the first thin!bein! "alled&

  • 8/9/2019 Android Game Development Tutorials

    8/201

    *n a nutshell the Activityhandles our in#ut !ets the tou"hes on the s"reen, "reates the window

    where we will dis#la+ our !ame and so on& 'his usuall+ is a full s"reen window and we will useone as su"h&

    Bet6s run the "reated a##li"ation& Ki!ht "li"$ on the #ro.e"t and "hoose Kun As =O Android

    A##li"ation& %hoose the "onfi!ured devi"e and wait for it to load& Kemember not to "lose the

    irtual evi"e on"e it has started as ever+ time +ou will run +our #ro.e"t, e"li#se will rede#lo+ itto the "urrentl+ runnin! devi"e and will save +ou a lot of time if it6s alread+ started&

    ou should see a s"reen li$e the one below& *f the devi"e as$s +ou to unlo"$ the s"reen do it b+dra!!in! the unlo"$ button with +our mouse&

  • 8/9/2019 Android Game Development Tutorials

    9/201

    How let6s eamine what has .ust ha##ened& F#en theDroidzActivity.javafile&

    view source

    print?

    package net.obviam.droidz;

    import android.app.Activity;

    import android.os.Bundle;

    public class DroidzActivity extends Activity {

    / !alled w"en t"e activity is #rst created. /

    $%verride

    public void on!reate&Bundle saved'nstance(tate) {

    super.on!reate&saved'nstance(tate);

    set!ontent*iew&+.layout.main);

    ,

    ,

    http://www.javacodegeeks.com/2011/07/android-game-development-create-project.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-create-project.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-create-project.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-create-project.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-create-project.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-create-project.html#about
  • 8/9/2019 Android Game Development Tutorials

    10/201

    01 packagenet.obviam.droidz;

    02

    03 importandroid.app.Activity;04 importandroid.os.Bundle;

    05

    06 publicclassroidzActivity e"tendsActivity #0$ %&& 'alled ()en t)e activity is *irst created. &%0+ ,-verride

    0 publicvoidon'reate/Bundle savednstancetate #10 super.on'reate/savednstancetate;

    11 set'ontentie(/.layout.main;

    12

    13

    ou6ll noti"e one method& 'he onCreate(method on line 0

  • 8/9/2019 Android Game Development Tutorials

    11/201

    view source

    print?

    017"mlversion891.09encoding89ut*:+9702 (idt)89*ill>parent9

    0 android=layout>)eig)t89(rap>content9

    10 android=te"t89,string%)ello9

    11 %

    12 %

  • 8/9/2019 Android Game Development Tutorials

    12/201

    print?

    017"mlversion891.09encoding89ut*:+9702 (idt)89*ill>parent9

    0 android=layout>)eig)t89(rap>content9

    10 android=te"t89,string%)ello9

    11 %

    12 ?e"tie(

    13 android=layout>(idt)89*ill>parent9

    14 android=layout>)eig)t89(rap>content9

    15 android=te"t89,string%(arning9

    16 %1$ %

  • 8/9/2019 Android Game Development Tutorials

    13/201

    Het we will a"tuall+ load some ima!es and draw them onto the s"reen&

    Reference:%reatin! the Android Pro.e"tfrom our J%G#artner 'amas Jano from (A!ainst 'he

    Grain) blo!&

    Android Game Development A BasicGame ArchitecturePublished on Jul+ 4, 2011 |59,341 views |Filed in: Android Games

    o we !ot our Android a##li"ation u# and runnin!but +ou mi!ht be wonderin! what t+#e of

    a##li"ation is ea"tl+ a !ame& * will tr+ to !ive +ou m+ understandin! of it& 'he followin!dia!ram re#resents a !ame ar"hite"ture&

    Game ar"hite"ture on an Android #hone

    *n the s"hema above +ou see the Android F runnin! on the Phone and ever+thin! on to# of that&

    'he in#ut is the tou"h=s"reen in our "ase but it "an be a #h+si"al $e+board if the #hone has one,

    the mi"ro#hone, the "amera, the a""elerometers or even the GP re"eiver if eui##ed& 'heframewor$ e#oses the events when tou"hin! the s"reen throu!h the iew used in our A"tivit+

    from the #revious arti"le&

    The ser "nput

    *n our !ame this is the event !enerated b+ tou"hin! the s"reen in one of the 2 defined "ontrolareas& see te# 1E the "oloured "ir"les& Fur !ame en!ine monitors the on'ou"h event and at

    ever+ tou"h we re"ord the "oordinates& *f the "oordinates are inside our defined "ontrol areas on

    the s"reen we will instru"t the !ame en!ine to ta$e a"tion& or eam#le if the tou"h o""urs in the"ir"le desi!nated to move our !u+ the en!ine !ets notified and our !u+ is instru"ted to move& *f

    the wea#on "ontroller "ir"le is tou"hed the eui##ed wea#on will be instru"ted to fire its bullets&

    All this translates to "han!in! the a"tors6 states that are affe"ted b+ our !estures a$a in#ut&

    http://obviam.net/index.php/step-2-creating-the-android-project/http://www.javacodegeeks.com/p/jcg.htmlhttp://obviam.net/http://obviam.net/http://www.javacodegeeks.com/android/android-gameshttp://www.javacodegeeks.com/android/android-gameshttp://www.javacodegeeks.com/2011/07/android-game-development-create-project.htmlhttp://www.javacodegeeks.com/2011/07/android-game-development-create-project.htmlhttp://www.javacodegeeks.com/2011/07/android-game-development-game-idea.htmlhttp://www.javacodegeeks.com/2011/07/android-game-development-game-idea.htmlhttp://obviam.net/index.php/step-2-creating-the-android-project/http://www.javacodegeeks.com/p/jcg.htmlhttp://obviam.net/http://obviam.net/http://www.javacodegeeks.com/android/android-gameshttp://www.javacodegeeks.com/2011/07/android-game-development-create-project.htmlhttp://www.javacodegeeks.com/2011/07/android-game-development-game-idea.html
  • 8/9/2019 Android Game Development Tutorials

    14/201

    * have .ust des"ribed the Game Bo!i" #art whi"h follows&

    #ame Logic

    'he !ame lo!i" module is res#onsible for "han!in! the states of the a"tors in the !ame& 8+ a"tors

    * mean ever+ ob.e"t that has a state& Fur hero, droids, terrain, bullets, laser beams et"& oream#le we tou"h the u##er half of the hero "ontrol area li$e in the drawin! and this translates

    to; "al"ulate the movement s#eed of our !u+ a""ordin! to the #osition of our movement

    "ontroller our fin!er&

    *n the ima!e above the li!ht !reen "ir"le re#resents our fin!er tou"hin! the "ontrol area& 'he>ser *n#ut module notifies the Game Dn!ine Game Bo!i" and also #rovides the "oordinates& d$and dyare the distan"es in #iels relative to the "ontroller "ir"le "entre& 'he !ame en!ine

    "al"ulates the new s#eed it has to set for our hero and the dire"tion he will move& *f d$is #ositivethat means he will !o ri!ht and if dyis #ositive he will also move u#ward&

    Audio

    'his module will #rodu"e sounds "onsiderin! the "urrent state& As almost ever+ a"torLob.e"t will

    #rodu"e sounds in their different states and be"ause the devi"es we6ll run our !ame on arelimited to .ust a few "hannels that means briefl+ how man+ sounds "an the devi"e #la+ at on"e

    it has to de"ide whi"h sounds to #la+& or eam#le the droid #osin! the bi!!est threat to our hero

    will be heard as we want to draw attention to it and of "ourse we will need to reserve a "hannel

    for the awesome shootin! sound of our wea#on as it is mu"h fun listenin! to our blaster sin!in!&

    o this is the audio in a nutshell&

    #raphics

    'his is the module res#onsible for renderin! the !ame state onto the dis#la+& 'his "an be assim#le as drawin! dire"tl+ onto the "anvas obtained from the view or havin! a se#arate !ra#hi"s

    buffer drawn into and then #assed to the view whi"h "an be a "ustom view or an F#enGB view&

  • 8/9/2019 Android Game Development Tutorials

    15/201

    e measure the renderin! in P whi"h stands for frames #er se"ond& *f we have 30P that

    means that we dis#la+ 30 ima!es ever+ se"ond& or a mobile devi"e 30 P is !reat so we will

    aim for that& :ore on this later&

    'he onl+ thin! +ou want to $now now that the hi!her the P the smoother the animation& Just

    ima!ine someone wal$in! and "lose +our e+es for ea"tl+ one se"ond& After o#enin! +our e+es+ou will see the #erson in the #osition after one se"ond& 'his is a 2P& at"h them wal$ but

    $ee#in! +our e+es o#en and +ou6ll see a fluid motion& 'his is !uaranteed to be a minimum of30P but it is li$el+ to be more, de#endin! on +our e+es& *f +ou have awesome re"e#tors in

    #ristine "ondition this "ould be 90=100 or more&

    %utput

    'he out#ut is the result of both sound and ima!e and ma+be vibration if we de"ide to #rodu"e

    some&

    Het we will set u# our view and will tr+ to ma$e our first !ame loo# whi"h will ta$e in#ut fromthe tou"h s"reen& e6ll have our first !ame en!ine&

    Reference:A 8asi" Game Ar"hite"turefrom our J%G#artner 'amas Jano from (A!ainst 'heGrain) blo!&

    Android Game Development A BasicGame LoopPublished on Jul+ 5, 2011 |92,527 views |Filed in: Android Games

    ollowin! the series so far +ou we have an understandin! of the !ame ar"hite"ture& Dven if .ustbriefl+ but we $now that we need to ta$e in#ut in some form, u#date the internal state of the

    !ame and finall+ render it to the s"reen and also #rodu"e some sounds andLor vibrations&

    urthermore we have "reated an eam#le Android #ro.e"t for our first !ame& *n this arti"le weare !oin! to dis"uss and im#lement the basi" !ame loo#&

    Bet6s $ee# it sim#le& %he"$ the followin! dia!ram&

    http://obviam.net/index.php/2-1-a-little-about-game-architecture/http://www.javacodegeeks.com/p/jcg.htmlhttp://obviam.net/http://obviam.net/http://www.javacodegeeks.com/android/android-gameshttp://www.javacodegeeks.com/android/android-gameshttp://obviam.net/index.php/2-1-a-little-about-game-architecture/http://www.javacodegeeks.com/p/jcg.htmlhttp://obviam.net/http://obviam.net/http://www.javacodegeeks.com/android/android-games
  • 8/9/2019 Android Game Development Tutorials

    16/201

    A 8asi" Game Boo#

    e handle in#ut, u#date the state of our internal ob.e"ts and render the "urrent state& 'he Update

    andRenderare !rou#ed lo!i"all+& 'he+ are tied to!ether and tend to be ee"uted one after the

    other&

    An+thin! in Android ha##ens inside anActivity& 'heActivitywill "reate a View& 'he Viewiswhere ever+thin! ha##ens& *t is where the tou"h ta$es #la"e and the resultin! ima!e !ets

    dis#la+ed& 'hin$ of theActivityas a table that holds a sheet of #a#er the View enablin! us to

    draw somethin!& e will use our #en"il to draw somethin! onto the #a#er& 'hat will be our tou"h

    and the a"tual "hemistr+ ha##ens on the #a#er so the result of our intera"tion with the View#rodu"es an ima!e& 'he same is withActivityand View& omethin! li$e the followin! dia!ram;

    Android Game Boo#

    Bet6s o#en u#DroidzActivity.javafrom our #ro.e"t& e see the line

  • 8/9/2019 Android Game Development Tutorials

    17/201

  • 8/9/2019 Android Game Development Tutorials

    18/201

    LL ma$e the GamePanel fo"usable so it "an handle events

    seto"usabletrueV

    X

    UFverride

    #ubli" void surfa"e%han!edurfa"e?older holder, int format, int width, int hei!ht W

    X

    UFverride

    #ubli" void surfa"e%reatedurfa"e?older holder W

    X

    UFverride

    #ubli" void surfa"eestro+edurfa"e?older holder W

    X

    UFverride

    #ubli" boolean on'ou"hDvent:otionDvent event W

    return su#er&on'ou"hDventeventV

    X

    UFverride

    #rote"ted void onraw%anvas "anvas W

  • 8/9/2019 Android Game Development Tutorials

    19/201

  • 8/9/2019 Android Game Development Tutorials

    20/201

    3

    40

    'he above "ode is a #lain "lass that overrides the methods we are interested in&Hothin! s#e"ial a#art from lines 15 and 17&

    view source

    print?

    1 get@older/.add'allback/t)is;

    'his line sets the "urrent "lass #ainGame$anel as the handler for the events ha##enin! on the

    a"tual surfa"e&

    view source

    print?

    1 setHocusable/true;

    'he above line ma$es our Game Panel fo"usable, whi"h means it "an re"eive fo"us so it "an

    handle events& e added the "allba"$ and made it fo"usable in the "onstru"tor so we won6t miss&

    'he over=riden methods line 20 onwards will all be used but "urrentl+ $ee# them em#t+&

    Bet6s "reate the thread that will be our a"tual !ame loo#&

    #ainThread.java

    #a"$a!e net&obviam&droidV

    #ubli" "lass :ain'hread etends 'hread W

    LL fla! to hold !ame state

    #rivate boolean runnin!V

    #ubli" void setKunnin!boolean runnin! W

    this&runnin! R runnin!V

    X

    http://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#about
  • 8/9/2019 Android Game Development Tutorials

    21/201

    UFverride

    #ubli" void run W

    while runnin! W

    LL u#date !ame state

    LL render state to the s"reen

    X

    X

    X

    view source

    print?

    01 packagenet.obviam.droidz;

    02

    03 publicclassDain?)read e"tends?)read #

    04

    05 %% *lag to )old game state

    06 privatebooleanrunning;0$ publicvoidsetunning/booleanrunning #0+ t)is.running 8 running;

    0

    10

    11 ,-verride

    12 publicvoidrun/ #13 ()ile/running #14 %% update game state

    15 %% render state to t)e screen

    16

    1$

    1+

    As +ou "an see this does not do mu"h& *t overrides the run%&method and while the runnin"fla!

    is set to trueit does an infinite loo#&

    %urrentl+ the thread is not instantiated so let6s start it u# when the s"reen loads&

    Bet6s ta$e a loo$ at the modified#ainGame$anel"lass&

    http://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#about
  • 8/9/2019 Android Game Development Tutorials

    22/201

    #a"$a!e net&obviam&droidV

    im#ort android&"ontent&%ontetV

    im#ort android&!ra#hi"s&%anvasV

    im#ort android&view&:otionDventV

    im#ort android&view&urfa"e?olderV

    im#ort android&view&urfa"eiewV

    #ubli" "lass :ainGamePanel etends urfa"eiew im#lements

    urfa"e?older&%allba"$ W

    #rivate :ain'hread threadV

    #ubli" :ainGamePanel%ontet "ontet W

    su#er"ontetV

    !et?older&add%allba"$thisV

    LL "reate the !ame loo# thread

    thread R new :ain'hreadV

    seto"usabletrueV

    X

  • 8/9/2019 Android Game Development Tutorials

    23/201

    UFverride

    #ubli" void surfa"e%han!edurfa"e?older holder, int format, int width, int hei!ht W

    X

    UFverride

    #ubli" void surfa"e%reatedurfa"e?older holder W

    thread&setKunnin!trueV

    thread&startV

    X

    UFverride

    #ubli" void surfa"eestro+edurfa"e?older holder W

    boolean retr+ R trueV

    while retr+ W

    tr+ W

    thread&.oinV

    retr+ R falseV

    X "at"h *nterru#tedD"e#tion e W

    LL tr+ a!ain shuttin! down the thread

    X

    X

    X

  • 8/9/2019 Android Game Development Tutorials

    24/201

    UFverride

    #ubli" boolean on'ou"hDvent:otionDvent event W

    return su#er&on'ou"hDventeventV

    X

    UFverride

    #rote"ted void onraw%anvas "anvas W

    X

    X

    view source

    print?

    01 packagenet.obviam.droidz;

    02

    03 importandroid.content.'onte"t;04 importandroid.grap)ics.'anvas;05 importandroid.vie(.DotionEvent;06 importandroid.vie(.ur*ace@older;

    0$ importandroid.vie(.ur*aceie(;0+

    0 publicclassDainFameGanel e"tendsur*aceie( implements10 ur*ace@older.'allback #

    11

    12 privateDain?)read t)read;

    13

    14 publicDainFameGanel/'onte"t conte"t #15 super/conte"t;

    16 get@older/.add'allback/t)is;

    1$

    1+ %% create t)e game loop t)read1 t)read 8 ne(Dain?)read/;

    20

    21 setHocusable/true;

    22

    23

    24 ,-verride

    2 publicvoidsur*ace')anged/ur*ace@older )older int*ormat int(idt) int

    http://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#about
  • 8/9/2019 Android Game Development Tutorials

    25/201

    5 )eig)t #

    26

    2$

    2+ ,-verride

    2 publicvoidsur*ace'reated/ur*ace@older )older #30 t)read.setunning/true;

    31 t)read.start/;

    32

    33

    34 ,-verride

    35 publicvoidsur*aceestroyed/ur*ace@older )older #36 booleanretry 8 true;3$ ()ile/retry #3+ try#3 t)read.Ioin/;

    40 retry 8 *alse;

    41 catc)/nterruptedE"ception e #42 %% try again s)utting do(n t)e t)read

    43

    44

    45

    46

    4$ ,-verride

    4+ publicbooleanon?ouc)Event/DotionEvent event #4 returnsuper.on?ouc)Event/event;50

    51

    52 ,-verride

    53 protectedvoidonra(/'anvas canvas #54

    55

    e added the followin! lines;Bine 12 de"lares the thread as a #rivate attribute&

    view source

    print?

    1 privateDain?)read t)read;

    *n line 1< we instantiate the thread&

    view source

    print?

    1 t)read 8 ne(Dain?)read/;

    http://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#about
  • 8/9/2019 Android Game Development Tutorials

    26/201

    *n the sur'aceCreatedmethod we set the runningfla! to trueand we start u# the thread lines 30

    and 31& 8+ the time the this method is "alled the surfa"e is alread+ "reated and the !ame loo#

    "an be safel+ started&

    'a$e a loo$ at the sur'aceDestroyedmethod&

    view source

    print?

    01 publicvoidsur*aceestroyed/ur*ace@older )older #02 %% tell t)e t)read to s)ut do(n and (ait *or it to *inis)

    03 %% t)is is a clean s)utdo(n

    04 booleanretry 8 true;05 ()ile/retry #06 try#0$ t)read.Ioin/;

    0+ retry 8 *alse;0 catc)/nterruptedE"ception e #10 %% try again s)utting do(n t)e t)read

    11

    12

    13

    'his method is "alled dire"tl+ before the surfa"e is destro+ed& *t is not the #la"e to set the runnin!

    fla! but the "ode we #ut in ensures that the thread shuts down "leanl+& e sim#l+ blo"$ the

    thread and wait for it to die&

    *f we now run our #ro.e"t in the emulator won6t be able to see mu"h but we6ll use some lo!!in!

    to test it& on6t worr+ about it as * will "over lo!!in! in a later "ha#ter&

    ou "an find more on the Android site&

    Add interaction with the screen

    e will eit the a##li"ation when we tou"h the lower #art of the s"reen& *f we tou"h it an+where

    else we6ll .ust lo! the "oordinates&

    *n the#ainThread"lass we add the followin! lines;

    view source

    print?

    1 privateur*ace@older sur*ace@older;2 privateDainFameGanel gameGanel;

    3

    4publicDain?)read/ur*ace@older sur*ace@older DainFameGanel gameGanel #

    http://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#abouthttp://developer.android.com/reference/android/util/Log.htmlhttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#abouthttp://developer.android.com/reference/android/util/Log.htmlhttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#about
  • 8/9/2019 Android Game Development Tutorials

    27/201

    5 super/;

    6 t)is.sur*ace@older 8 sur*ace@older;

    $ t)is.gameGanel 8 gameGanel;

    +

    e de"lared the"ame$aneland sur'ace(oldervariables and a "onstru"tor ta$in! the instan"es

    as #arameters&

    *t is im#ortant to have them both and not .ust the"ame$anelas we need to lo"$ the surfa"ewhen we draw and that "an be done throu!h the sur'ace(olderonl+&

    %han!e the line int the "onstru"tor of the#ainGame$anelthat instantiates the thread to

    view source

    print?

    1 t)read 8 ne(Dain?)read/get@older/ t)is;

    e are #assin! the "urrent holder and the #anel to its new "onstru"tor so the thread "an a""ess

    them& e will "reate the !ame u#date method in the !ame #anel and we6ll tri!!er it from the

    thread but "urrentl+ .ust leave it as it is&

    Add the TAG"onstant to the#ainThread"lass& Dver+ "lass will have its own trin! "onstant"alled TAG& 'he value of the "onstant will be the name of the "lass "ontainin! it& e are usin!

    Android6s own lo!!in! framewor$ and that ta$es two #arameters& 'he firs is the ta! whi"h is .ust

    a strin! to identif+ the sour"e of the lo! messa!e and the se"ond is the messa!e we want to lo!&

    *t6s a !ood #ra"ti"e to use the name of the "lass for the ta! as it ma$es it sim#le to loo$ u# thelo!s&

    A note on logging

    'o o#en the lo! viewer !o to Windows -> Show View -> Other@ and in the dialo! sele"t

    Android -> LogCat

    http://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.html#about
  • 8/9/2019 Android Game Development Tutorials

    28/201

    how iew =O Bo!%at

    How +ou should see the Bo!%at view& 'his is nothin! more than a "onsole where +ou "an followAndroid6s lo!& *t6s a !reat tool as +ou "an filter for lo!s "ontainin! a s#e"ifi" tet or lo!s with a

    "ertain ta! whi"h is uite useful&

    Bet6s !et ba"$ to our "ode& 'he#ainThread.java"lass loo$s li$e this;

    view source

    print?

    01 packagenet.obviam.droidz;

    02

    03 importandroid.util.

  • 8/9/2019 Android Game Development Tutorials

    29/201

    1 t)is.sur*ace@older 8 sur*ace@older;

    20 t)is.gameGanel 8 gameGanel;

    21

    22

    23 ,-verride

    24 publicvoidrun/ #25 longtick'ount 8 0

  • 8/9/2019 Android Game Development Tutorials

    30/201

    Hote; 'he s"reen is a re"tan!le with the u##er left "oordinates at 0,0 and the lower ri!ht

    "oordinates at "et1idth%&,"et(ei"ht%&&

    * have also modified theDroidzActivity.java"lass so we lo! its life"+"le&

    view source

    print?

    01 packagenet.obviam.droidz;

    02

    03 importandroid.app.Activity;04 importandroid.os.Bundle;05 importandroid.util.

  • 8/9/2019 Android Game Development Tutorials

    31/201

    Bine ,)ma$es the dis#la+ fulls"reen&

    'he onDestroy%&and onSto3%&methods were overridden .ust to lo! the a"tivit+6s life"+"le&

    Bet6s run the a##li"ation b+ ri!ht="li"$in! on the #ro.e"t and sele"tRun As -> Androidappication

    ou should see a bla"$ s"reen& *f +ou "li"$ around a few time on the u##er half and then +ou"li"$ on the bottom of +our emulator6s s"reen the a##li"ation should eit&

    At this sta!e it is worth "he"$in! the lo!s&

    Bo!%at

    'he hi!hli!hted lines are the most interestin! as if +ou mat"h loo$ the lo!s u# in the "ode +ou

    will see ea"tl+ the order of the method "alls& ou should also see how man+ times the thread6s

    while loo# ee"uted& *t is a ver+ hi!h number but net time we will be more "onsiderate about

    the "+"les as we will introdu"e P and >P& 'hat is Frames 'er *econdand pdates 'er

    *econd& e will "reate a !ame loo# that will a"tuall+ draw somethin! onto the s"reen and it will

    do it as man+ times #er se"ond as we s#e"if+ it&

    'hin!s we did so far;

    %reate a full s"reen a##li"ation

    ?ave a se#arate thread "ontrollin! the a##li"ation

    *nter"e#tin! basi" !estures li$e #ressed !esture

    huttin! down the a##li"ation !ra"iousl+

    ownload the sour"e "odehere&

    *m#ort it into e"li#se and it should wor$ ri!ht awa+&

    5

    http://obviam.net/source_code/droidz.android.02.2.tar.gzhttp://obviam.net/source_code/droidz.android.02.2.tar.gzhttp://obviam.net/source_code/droidz.android.02.2.tar.gzhttp://obviam.net/source_code/droidz.android.02.2.tar.gz
  • 8/9/2019 Android Game Development Tutorials

    32/201

    Android Game Development DisplayingImages with AndroidPublished on Jul+ 7, 2011 |19,47C views |Filed in: Android Games

    8efore movin! to the a"tual !ame loo# let6s dis#la+ some !ra#hi"s so we "an !et somemeasurements done& *f +ou haven6t "he"$ed it out #lease do as it is im#erative that +ou

    understand how a thread u#dates the s"reen& ou "an "he"$ it out here&

    is#la+in! an ima!e usin! Android is etremel+ sim#le&'o s"ale the #roblem down we will .ust dis#la+ the ima!e in the to# left "orner& e need an

    ima!e to dis#la+& * #refer n! formats and * have .ust "reated one named droidT1n!& 'he sie

    of the ima!e is 20I20 #iels& ou "an use whatever tool +ou li$e& * use Gim# or Photosho#&

    'o ma$e it available for +our a##li"ation .ust "o#+ the ima!e into theresdrawable4md3idire"tor+ the easiest wa+ is to dra! and dro# it there&

    * have "hosen md#i whi"h stands for normal s"reen medium densit+& 'o read on s"reen t+#es"he"$ the android do"umentation&

    :odif+ the#ainGame$anel.java"lass and "han!e the onDraw%Canvas canvas&method to loo$

    li$e this;

    view source

    print?

    1protectedvoidonra(/'anvas canvas #

    2canvas.dra(Bitmap/BitmapHactory.decodeesource/getesources/.dra(able.droid>1 10 10 null;

    3

    'he draw5itma3method draws the droid06ima!e to the "oordinates 10,10&

    e obtain the bitma# from the a##li"ation resour"es b+ #assin! the id of our ima!e resour"e,whi"h is droid06in our "ase& hen we "o#ied the droid06.3n"into the resour"e dire"tor+

    e"li#se dete"ted it and the #lu!in ee"uted the ne"essar+ s"ri#ts in the ba"$!round so we have

    the droid06identifier in the7.javafile& 'he K&.ava holds the resour"e identifiers&

    'he thread suffered some "han!es too& Damine the new run%&method&

    view source

    print?

    01 publicvoidrun/ #02 'anvas canvas;

    http://www.javacodegeeks.com/android/android-gameshttp://www.javacodegeeks.com/android/android-gameshttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.htmlhttp://developer.android.com/guide/practices/screens_support.htmlhttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#abouthttp://www.javacodegeeks.com/android/android-gameshttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.htmlhttp://developer.android.com/guide/practices/screens_support.htmlhttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#about
  • 8/9/2019 Android Game Development Tutorials

    33/201

    03

  • 8/9/2019 Android Game Development Tutorials

    34/201

    while our fin!er is on the s"reen we will u#date the ima!e6s "oordinates a""ordin!l+& Fn"e the

    tou"h is finished we leave the ima!e there where the last tou"h was re"orded&

    e need to "reate an ob.e"t that will hold our ima!e and the "oordinates&* have "reatedDroid.javafor this& Hote that * have #ut the "lass into the

    net.obviam.droidz.model#a"$a!e&

    view source

    print?

    01 packagenet.obviam.droidz.model;

    02

    03 importandroid.grap)ics.Bitmap;

    04

    05 publicclassroid #

    06

    0$ privateBitmap bitmap; %% t)e actual bitmap0+ privateint"; %% t)e M coordinate0 privateinty; %% t)e L coordinate

    10

    11 publicroid/Bitmap bitmap int" inty #12 t)is.bitmap 8 bitmap;

    13 t)is." 8 ";

    14 t)is.y 8 y;

    15

    16

    1$ publicBitmap getBitmap/ #

    1+ returnbitmap;1

    20 publicvoidsetBitmap/Bitmap bitmap #21 t)is.bitmap 8 bitmap;

    22

    23 publicintgetM/ #24 return";25

    26 publicvoidsetM/int" #2$ t)is." 8 ";

    2+

    2 publicintgetL/ #

    30 returny;31

    32 publicvoidsetL/inty #33 t)is.y 8 y;

    34

    35

    http://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#about
  • 8/9/2019 Android Game Development Tutorials

    35/201

    *t is a #lain "lass with some attributes and a "onstru"tor&

    'he $and yare the "oordinates of the droid& 'he bitma# holds the ima!e that will be dis#la+ed

    as the droid& *t is the !ra#hi"al re#resentation of it&

    o far nothin! s#e"ial& 8ut to #la+ around with it we need to add some state& 'o $ee# it sim#le,

    the droid has onl+ 2 states& Touchedand untouched& 8+ touched* mean when our fin!er tou"hedthe droid on the s"reen& e $ee# the tou"hed state truewhile we hold our fin!er down on the

    s"reen at the droid6s #osition& Ftherwise the droid remains untou"hed state set to!ase&

    %he"$ out the new droid "lass&

    view source

    print?

    01 packagenet.obviam.droidz.model;

    02

    03 importandroid.grap)ics.Bitmap;04 importandroid.grap)ics.'anvas;05 importandroid.vie(.DotionEvent;

    06

    0$ publicclassroid #

    0+

    0 privateBitmap bitmap; %% t)e actual bitmap10 privateint"; %% t)e M coordinate11 privateinty; %% t)e L coordinate12 privatebooleantouc)ed; %% i* droid is touc)ed%picked up

    13

    14 publicroid/Bitmap bitmap int" inty #15 t)is.bitmap 8 bitmap;

    16 t)is." 8 ";

    1$ t)is.y 8 y;

    1+

    1

    20 publicBitmap getBitmap/ #21 returnbitmap;22

    23 publicvoidsetBitmap/Bitmap bitmap #24 t)is.bitmap 8 bitmap;

    25

    26 publicintgetM/ #2$ return";2+

    2 publicvoidsetM/int" #30 t)is." 8 ";

    31

    32 publicintgetL/ #33 returny;

    http://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#about
  • 8/9/2019 Android Game Development Tutorials

    36/201

    34

    35 publicvoidsetL/inty #36 t)is.y 8 y;

    3$

    3+

    3 publicbooleanis?ouc)ed/ #40 returntouc)ed;41

    42

    43 publicvoidset?ouc)ed/booleantouc)ed #44 t)is.touc)ed 8 touc)ed;

    45

    46

    4$publicvoiddra(/'anvas canvas #

    4+

    canvas.dra(Bitmap/bitmap " : /bitmap.getidt)/ % 2 y :/bitmap.get@eig)t/ % 2 null;

    4 50

    51publicvoid)andleActiono(n/inteventM inteventL #

    52

    i*/eventM 8 /" : bitmap.getidt)/ % 2 PP /eventM 8 /" Kbitmap.getidt)/%2 #

    53

    i*/eventL 8 /y : bitmap.get@eig)t/ % 2 PP /y 8 /y Kbitmap.get@eig)t/ % 2 #

    54%% droid touc)ed

    55 set?ouc)ed/true;

    56 else#5$ set?ouc)ed/*alse;

    5+

    5 else#60 set?ouc)ed/*alse;

    61

    62

    63

    64

    e added the touchedfield to $ee# tra"$ of the state of our droid& ou will noti"e two more

    methods;3ublic void draw%Canvas canvas&and3ublic void handleActionDown%int event89 int

    event2&&

    'hese methods are dis"ussed later&How let6s have a loo$ at the#ainGame$anel.java& *t "han!ed uite a lot&

    view source

    print?

    001 packagenet.obviam.droidz;

    http://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.html#about
  • 8/9/2019 Android Game Development Tutorials

    37/201

    002

    003 importnet.obviam.droidz.model.roid;004 importandroid.app.Activity;005 importandroid.content.'onte"t;006 importandroid.grap)ics.BitmapHactory;00$ importandroid.grap)ics.'anvas;00+ importandroid.grap)ics.'olor;00 importandroid.util.

  • 8/9/2019 Android Game Development Tutorials

    38/201

    04+

    04

    050 ,-verride

    051 publicvoidsur*aceestroyed/ur*ace@older )older #052

  • 8/9/2019 Android Game Development Tutorials

    39/201

    0$ protectedvoidonra(/'anvas canvas #0+ %% *ills t)e canvas (it) black

    0 canvas.dra('olor/'olor.B

  • 8/9/2019 Android Game Development Tutorials

    40/201

    %he"$ the onDrawmethod& 'his is tri!!ered at ever+ ee"ution of the main loo# inside the

    thread remember

    *t "ontains 2 lines& Bine 11sim#l+ fills the "anvas with bla"$ and line .++tells the droid to drawitself on the "anvas #rovided& 8+ doin! this is li$e me !ivin! +ou a #a#er to draw +ourself onto

    it, and !ive the #a#er ba"$ to me so * "an "ontinue m+ drawin!&

    %he"$Droid.javafor the draw im#lementation& *t is dead sim#le& *t ta$es the bitma# it was

    instantiated with and draws it to the "anvas at the "oordinates the droid is at in that moment&Hote that the "oordinates of the droid are ea"tl+ in the "enter of the bitma# so we need to move

    the #ointer to the to# left "orner of the ima!e and draw it there& *6m sure +ou won6t find it hard to

    understand&

    'hat6s it& Kun it and have a #la+ with it&

    ownload he "ode for the #ro.e"t here droid&android&02&3=!ra#hi"s&tar&!

    Reference:is#la+in! *ma!es with Androidfrom ourJ%G#artner 'amas Jano from (A!ainst'he Grain) blo!&

    o not for!et to "he"$ out our new Android GameArkDroids"reenshots below& ou feedba"$will be more than hel#ful/

    6

    Android Game Development ovingImages on !creenPublished on Jul+

  • 8/9/2019 Android Game Development Tutorials

    41/201

    'he tas$ *6m settin! for this entr+ is sim#le; have the droid travel throu!h the s"reen& *t should

    never leave the surfa"e and it should boun"e ba"$ when it hits the wall whi"h is the ed!e of the

    s"reen&

    *f +ou remember the ima!e is .ust a re#resentation of the droid& o we will modif+ the droid

    ob.e"t and we6ll add some abilities& Just one for the time bein!& Fur droid is movable& *t "anmove& 'his im#lies that it hasspeed& e will vest it with the abilit+ of movement& 'o a"hieve this

    we will add a move%&method and this method will .ust u#date the 2and 3"oordinates based onits *peed& *peedwill be a "lass in itself and the 4roidwill "ontain it& * will do a "on"rete

    im#lementation now but later on * will be usin! the trate!+ Pattern&

    %reate theS3eed.java"lass&

    view source

    print?

    01 packagenet.obviam.droidz.model.components;

    02

    03 publicclasspeed #

    04

    05 publicstatic*inalintE'?-J>F@? 8 1;06 publicstatic*inalintE'?-J>-J 8 1;

    0

    10 private*loat"v 8 1; %% velocity value on t)e M a"is11 private*loatyv 8 1; %% velocity value on t)e L a"is

    1213 privateint"irection 8 E'?-J>F@?;14 privateintyirection 8 E'?-J>-J;

    15

    16 publicpeed/ #1$ t)is."v 8 1;

    1+ t)is.yv 8 1;

    1

    20

    21 publicpeed/*loat"v *loatyv #22 t)is."v 8 "v;

    23 t)is.yv 8 yv;24

    25

    26 public*loatgetMv/ #2$ return"v;2+

    2 publicvoidsetMv/*loat"v #30 t)is."v 8 "v;

    31

    http://en.wikipedia.org/wiki/Strategy_patternhttp://en.wikipedia.org/wiki/Strategy_patternhttp://www.javacodegeeks.com/2011/07/android-game-development-moving-images.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-moving-images.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-moving-images.html#abouthttp://en.wikipedia.org/wiki/Strategy_patternhttp://www.javacodegeeks.com/2011/07/android-game-development-moving-images.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-moving-images.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-moving-images.html#about
  • 8/9/2019 Android Game Development Tutorials

    42/201

    32 public*loatgetLv/ #33 returnyv;34

    35 publicvoidsetLv/*loatyv #36 t)is.yv 8 yv;

    3$

    3+

    3 publicintget"irection/ #40 return"irection;41

    42 publicvoidset"irection/int"irection #43 t)is."irection 8 "irection;

    44

    45 publicintgetyirection/ #46 returnyirection;4$

    4+ publicvoidsetyirection/intyirection #4 t)is.yirection 8 yirection;

    50

    51

    52 %% c)anges t)e direction on t)e M a"is

    53 publicvoidtoggleMirection/ #54 "irection 8 "irection & :1;

    55

    56

    5$ %% c)anges t)e direction on t)e L a"is

    5+ publicvoidtoggleLirection/ #5 yirection 8 yirection & :1;

    60

    61

    e6ll use dire"tion "onstants to determine the movement dire"tion on the ais& 'he droid has averti"al and a horiontal s#eed and at ea"h !ame u#date the "oordinates are set "onsiderin! the

    dire"tion of the movement&

    'he droid will be allowed to move onl+ on the area of the "anvas& 'hat is a re"tan!le and our 2

    "oordinate s+stem& >nli$e in the math "lasses the ori!in is in the to# left "orner& o for the droidto start from the to# left "orner of the s"reen its "oordinates will be 0,0& 'o move in a dia!onal

    line the s#eed will be .for both the 2and 3"om#onents of the s#eed ve"tor& 'o move towards

    the bottom ri!ht the dire"tions will be; . (rightfor the 2ais and . (downfor the 3ais&

  • 8/9/2019 Android Game Development Tutorials

    43/201

  • 8/9/2019 Android Game Development Tutorials

    44/201

    05 canvas 8 null;

    06 %% try locking t)e canvas *or e"clusive pi"el editing

    0$ %% in t)e sur*ace

    0+ try#0 canvas 8 t)is.sur*[email protected]'anvas/;

    10 sync)ronized/sur*ace@older #

    11 %% update game state12 t)is.gameGanel.update/;

    13 %% render state to t)e screen

    14 %% dra(s t)e canvas on t)e panel

    15 t)is.gameGanel.render/canvas;

    16

    1$ *inally#1+ %% in case o* an e"ception t)e sur*ace is not le*t in

    1 %% an inconsistent state

    20 i*/canvas C8 null #21 sur*[email protected]'anvasAndGost/canvas;

    22

    23 %% end *inally

    24

    25

    e will "reate the "orres#ondin! method in the#ainGame$anel& 'his method is in "har!e of

    u#datin! the state of all the ob.e"ts in the a##li"ation& %urrentl+ onl+ the droid& 8e"ause the droid

    is movin! we will introdu"e a basi" "ollision dete"tion with the walls& 'he lo!i" is sim#le& %he"$if the droid is movin! towards left then "he"$ if the droid6s #osition is at the wall and if it is then

    "han!e its dire"tion& 8ear in mind that the droid6s #osition is the "enter of the ima!e so we need

    to use the ima!e6s width and hei!ht to !et the a""ura"+ ri!ht&e also u#date the #osition of the droid& 'o $ee# the u#date method sim#le we dele!ate the

    u#date of the droid6s #osition to the droid itself& o the droid will !et an u#date method whi"hwill $ee# u#datin! its #osition if the droid is not bein! #i"$ed u# b+ a tou"h !esture& %he"$ the

    #revious #ost for this&

    %he"$ the "ode;#ainGame$anel.java

    view source

    print?

    01 publicvoidupdate/ #

    02 %% c)eck collision (it) rig)t (all i* )eading rig)t03 i*/droid.getpeed/.get"irection/ 88 peed.E'?-J>F@?04 PP droid.getM/ K droid.getBitmap/.getidt)/ % 28 getidt)/ #05 droid.getpeed/.toggleMirection/;

    06

    0$ %% c)eck collision (it) le*t (all i* )eading le*t

    0+ i*/droid.getpeed/.get"irection/ 88 peed.E'?-J>

  • 8/9/2019 Android Game Development Tutorials

    45/201

    11

    12 %% c)eck collision (it) bottom (all i* )eading do(n

    13 i*/droid.getpeed/.getyirection/ 88 peed.E'?-J>-J14 PP droid.getL/ K droid.getBitmap/.get@eig)t/ % 28 get@eig)t/ #15 droid.getpeed/.toggleLirection/;

    16

    1$ %% c)eck collision (it) top (all i* )eading up1+ i*/droid.getpeed/.getyirection/ 88 peed.E'?-J>OG1 PP droid.getL/ : droid.getBitmap/.get@eig)t/ % 28 0 #20 droid.getpeed/.toggleLirection/;

    21

    22 %% Opdate t)e lone droid

    23 droid.update/;

    24

    "et1idth%&and"et(ei"ht%&return the width and hei!ht of the view& 'he #anel is a view,

    remember

    'heDroid.javafile6s u3date%&method;

    view source

    print?

    1 publicvoidupdate/ #2 i*/Ctouc)ed #3 " K8 /speed.getMv/ & speed.get"irection/;

    4 y K8 /speed.getLv/ & speed.getyirection/;

    5

    6

    * also "han!ed the render6s name in the#ainThread.javaso now it is renderinstead if onDraw&

    Just that * li$e it better as it follows the u#date =O render namin!&

    Kun the a##li"ation and +ou should see a s"reen li$e the followin! one with the droid movin! ina 45 de!rees an!le and boun"in! off the walls as it hits them& ou "an also dra! the droid around&

    'o eit the a##li"ation "li"$ tou"h the lower #art of the s"reen&

    http://www.javacodegeeks.com/2011/07/android-game-development-moving-images.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-moving-images.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-moving-images.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-moving-images.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-moving-images.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-moving-images.html#about
  • 8/9/2019 Android Game Development Tutorials

    46/201

    :ovin! roid

    ownload the full sour"e "ode and e"li#se #ro.e"t here&

    Reference::ovin! *ma!es on the "reen with Androidfrom our J%G#artner 'amas Jano from

    (A!ainst 'he Grain) blo!&

    o not for!et to "he"$ out our new Android GameArkDroids"reenshots below& ou feedba"$

    will be more than hel#ful/

    7

    Android Game Development The GameLoop

    Published on Jul+ 12, 2011 |32,72C views |Filed in: Android Games'he !ame loo# is the heartbeat of ever+ !ame& e used a ver+ rudimentar+ one so far +ou "anfind it here without an+ "ontrol over how fast or slow we u#date our !ame state and whi"h

    frames to render&

    'o re"a#itulate, the most rudimentar+ !ame loo# is a while loo# that $ee#s ee"utin! some

    instru"tions until we si!nal it to finish, usuall+ b+ settin! a variable "alled runningto!ase

    view source

    print?

    1 booleanrunning 8 true;2 ()ile/Crunning3 #

    4 updateFametate/;

    5 displayFametate/;

    6

    'he above "ode runs blindl+ without a "are for timin! and resour"es& *f +ou have a fast devi"e

    then it will run ver+ fast and if +ou have a slow one it will run slower&

    'he u3dateGameState%&u#dates the state of ever+ ob.e"t in the !ame and the

    dis3layGameState%&renders the ob.e"ts into an ima!e whi"h is dis#la+ed onto the s"reen&

    'here are two thin!s we should "onsider here; P and >P&

    F'*E Frames per *econdE the number of times dis3layGameState%&is bein! "alled #er

    se"ond&

    '*E pdate per *econdE the number of times u3dateGameState%&is bein! "alled #er

    se"ond&

    http://www.obviam.net/source_code/droidz.android.image-move.tar.gzhttp://obviam.net/index.php/moving-images-on-the-screen-with-androi/http://www.javacodegeeks.com/p/jcg.htmlhttp://obviam.net/http://www.javacodegeeks.com/2011/06/jcg-studios-arkdroid-official-launch.htmlhttp://www.javacodegeeks.com/android/android-gameshttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.htmlhttp://www.javacodegeeks.com/2011/07/android-game-development-game-loop.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-game-loop.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-game-loop.html#abouthttp://www.obviam.net/source_code/droidz.android.image-move.tar.gzhttp://obviam.net/index.php/moving-images-on-the-screen-with-androi/http://www.javacodegeeks.com/p/jcg.htmlhttp://obviam.net/http://www.javacodegeeks.com/2011/06/jcg-studios-arkdroid-official-launch.htmlhttp://www.javacodegeeks.com/android/android-gameshttp://www.javacodegeeks.com/2011/07/android-game-development-basic-game_05.htmlhttp://www.javacodegeeks.com/2011/07/android-game-development-game-loop.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-game-loop.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-game-loop.html#about
  • 8/9/2019 Android Game Development Tutorials

    47/201

    *deall+ the updateand rendermethods will be "alled the same number of times #er se"ond

    #referabl+ not less than 20=25 times #er se"ond& 25 P is usuall+ enou!h on a #hone so us

    humans won6t noti"e the animation bein! slu!!ish&

    or eam#le if we tar!et 25 P then it means we have to "all the dis3layGameState%&method

    ever+ 40ms 1000 L 25 R 40ms, 1000ms R 1s& e need to bear in mind that u3dateGameState%&is also "alled before the dis#la+ method and for us to rea"h 25 P, we have to ma$e sure that

    the u#date E dispayseuen"e ee"utes in ea"tl+ 40ms& *f it ta$es less than 40ms, then we havea hi!her P& *f it ta$es more than that, then we have a slower runnin! !ame&

    Bet6s see some eam#les to understand the P better&

    'he followin! dia!ram shows ea"tl+ 1 P& *t ta$es the updateE render"+"le ea"tl+ one

    se"ond to ee"ute& 'his means that +ou will see the ima!e on the s"reen "han!e on"e ever+se"ond&

    1 Frame per Second

    'he followin! dia!ram shows 10P& An updateE render"+"le ta$es 100ms& 'his means ever+

    tenth of a se"ond the ima!e "han!es&

  • 8/9/2019 Android Game Development Tutorials

    48/201

    10 P

    8ut the above s"enario means that the update=render"+"le ee"utes in 1L10 of a se"ond DDKtime& 'hat is an assum#tion and we "an6t "ontrol the a"tual times on "+"le ee"utes, or "an we

    hat ha##ens if we have 200 enemies and ever+ enem+ is shootin! at us e need to u#date the

    state of ea"h enem+ and the states of their bullets and "he"$ for "ollisions in one sin!le u#date&*t6s different when we have .ust 2 enemies& 'he times will "learl+ differ& 'he same a##lies to the

    render method& Kenderin! 200 firin! droids will "learl+ ta$e more time than renderin! onl+ 2&

    o what are the s"enarios e "ould have an u#date=render "+"le that finishes in less than 100ms

    1L10 of a se"ond, finishes in ea"tl+ 100ms or finishes in more than that& Fn a #owerfulhardware it will be faster than on a wea$er one& Bet6s see the dia!rams&

    'he "+"le finishes before the desired timeframe so we have a small amount of free time before

    runnin! the net "+"le&

  • 8/9/2019 Android Game Development Tutorials

    49/201

    Frame with time to spare

    'he followin! dia!ram shows a "+"le whi"h falls behind& 'hat means that the time it ta$es for au#date=render "+"le to finish is !reater than the desired one& *f it ta$es 12ms that means we are

    2ms behind still "onsiderin! the 10P& 'his "an mount u# and ever+ "+"le we loose time andthe !ame will run slowl+&

    Overdue Frame

    'he first situation is the desired one& 'his !ives us some free time to do somethin! before we

    $i"$ off the net "+"le& e don6t need to do an+thin! so we .ust tell the !ame loo# to !o to slee#

    for the remainin! time #eriod and wa$e u# when the net "+"le is due& *f we won6t do this the

    !ame will run ui"$er than intended& 8+ introdu"in! the slee# time we a"hieved constant frame

    rate&

  • 8/9/2019 Android Game Development Tutorials

    50/201

    'he se"ond situation * s$i##ed the ideal one as it almost never ha##ens when the loo# is

    behind, reuires a different a##roa"h&

    'o a"hieve "onstant s#eed in a !ame we need to u#date the state of our ob.e"ts when reuired&*ma!ine a droid a##roa"hin! +ou at a "onstant s#eed& ou $now if it travelled half the s"reen in

    one se"ond, so it will ta$e another se"ond to rea"h the other side of the s"reen& 'o "al"ulate the#osition a""uratel+ we need to $now either the time delta sin"e the last #ostion, and the "urrent

    s#eed of the droid, or we u#date the #osition status of the droid at "onstant intervals& * will"hoose the se"ond one as #la+in! with deltas in the !ame u#date "an be tri"$+& 'o a"hieve a

    constant game speedwe will have to s6ipdis#la+in! frames& Game s#eed is HF' P/

    Damine the followin! dia!ram& *t is a s"enario in whi"h the update=render"+"le ta$es lon!erthan the desired time so we have to "at"h u#& 'o do that we will s$i# the renderin! of this frame

    and will do another u#date so the !ame s#eed won6t be affe"ted& e6ll do a normal "+"le in the

    net frame with even some time to !ive to the %P> to rest&

    Constant Game Speed with Variable FPS

    'he above s"enario has man+ variations& ou "an ima!ine the !ame u#date ta$in! more than one

    full frame& *n this "ase we "an do nothin! to $ee# the !ame s#eed "onstant and the !ame will runslower& e mi!ht have to s$i# multi#le renderin!s to $ee# the s#eed "onstant but we have to

    ma$e sure that we set the maimum number of frames allowed to be s$i##ed be"ause it "an ta$e

    uite a few u#dates to "at"h u# and in "ase we s$i##ed 15 frames that means we lost a lot fromthe !ame and it will .ust be un#la+able&

    'he &ainThread)ava-s run%&loo$s li$e this;

    view source

    print?

    01 %% desired *ps

    02 private*inalstaticintDAM>HG 8 50;03 %% ma"imum number o* *rames to be skipped

    http://www.javacodegeeks.com/2011/07/android-game-development-game-loop.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-game-loop.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-game-loop.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-game-loop.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-game-loop.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-game-loop.html#about
  • 8/9/2019 Android Game Development Tutorials

    51/201

    04 private*inalstaticintDAM>HADE>QG 8 5;05 %% t)e *rame period

    06 private*inalstaticintHADE>GE- 8 1000% DAM>HG;

    0$

    0+ ,-verride

    0 publicvoidrun/ #10 'anvas canvas;

    11 HADE>QG #4 %% (e need to catc) up

    50 %% update (it)out rendering

    51 t)is.gameGanel.update/;

    52 %% add *rame period to c)eck i* in ne"t *rame

  • 8/9/2019 Android Game Development Tutorials

    52/201

    53 sleep?ime K8 HADE>GE-;

    54 *rameskippedKK;

    55

    56

    5$ *inally#5+ %% in case o* an e"ception t)e sur*ace is not le*t in

    5 %% an inconsistent state60 i*/canvas C8 null #61 sur*[email protected]'anvasAndGost/canvas;

    62

    63 %% end *inally

    64

    65

    Damine the above "ode ver+ "arefull+ as it im#lements the lo!i" behind the dia!ram& ou "anfind the full "ode in the downloadable #ro.e"t&

    'here is another a##roa"h whi"h * li$e& *t is "onstant !ame s#eed with maimum number offrames #er se"ond& *t uses inter#olation to draw the state and it o""urs on fast hardwares when

    there is time left for another renderin! before the net !ame u#date& 'his "an enhan"e the visualsof a !ame as it enables smoother animation but be"ause we use mobile devi"es, !ivin! the %P>

    some rest will save the batter+ uite a lot&

    'here is an awesome arti"le on !ame loo#s here& * #ersonall+ understood the !ame loo#s readin!

    this arti"le so * hi!hl+ re"ommend it& 'he best * "ould find&

    Hote that * also modified the default values in the *peed)ava"lass& 'he s#eed is measured inunitsLse"ond& 8e"ause we are settin! our desired P to 50 that means that the s#eed will

    in"rease b+ 50Ys#eed&value ever+ u#date& 'o have the s#eed of let6s sa+ 40 #ielsLse"ond +ouwill need to set the s#eed delta for ever+ ti"$ to 2 40 L 1000 L 50 R 2& *n other words +ou needthe droid to advan"e 2 #iels ever+ !ame u#date when +ou have 50 !ame u#dates #er se"ond to

    "over 40 #iels #er se"ond&

    ownload the "ode hereand #la+ with it&

    Damine it and +ou have a "onstant !ame s#eed with variable frame rate&

    Reference:'he Game Boo#from our J%G#artner 'amas Jano from (A!ainst 'he Grain) blo!&

    o not for!et to "he"$ out our new Android GameArkDroids"reenshots below& ou feedba"$will be more than hel#ful/

    8

    Android Game Development easuring"P!

    http://www.koonsolo.com/news/dewitters-gameloop/http://www.obviam.net/source_code/droidz.android.constant-game-speed.tar.gzhttp://obviam.net/index.php/the-android-game-loop/http://www.javacodegeeks.com/p/jcg.htmlhttp://obviam.net/http://www.javacodegeeks.com/2011/06/jcg-studios-arkdroid-official-launch.htmlhttp://www.koonsolo.com/news/dewitters-gameloop/http://www.obviam.net/source_code/droidz.android.constant-game-speed.tar.gzhttp://obviam.net/index.php/the-android-game-loop/http://www.javacodegeeks.com/p/jcg.htmlhttp://obviam.net/http://www.javacodegeeks.com/2011/06/jcg-studios-arkdroid-official-launch.html
  • 8/9/2019 Android Game Development Tutorials

    53/201

    Published on Jul+ 19, 2011 |21,773 views |Filed in: Android Games

    *n the#revious entr+we have "reated a !ame loo# that runs at a "onstant s#eed and "onstantmore or less P&

    ?ow "an we measure it

    %he"$ the new#ainThread.java"lass&

    view source

    print?

    001 packagenet.obviam.droidz;

    002003 importIava.te"t.ecimalHormat;

    004

    005 importandroid.grap)ics.'anvas;006 importandroid.util.HADE>QG 8 5;

    023 %% t)e *rame period024 private*inalstaticintHADE>GE- 8 1000% DAM>HG;

    025

    026 %% tu** *or stats &%

    02$ privateecimalHormat d* 8 ne(ecimalHormat/90.SS9; %% 2 dp02+ %% (eRll be reading t)e stats every second

    02 private*inalstaticint?A?>J?EA< 8 1000; %%ms030 %% t)e average (ill be calculated by storing

    031 %% t)e last n HGs

    http://www.javacodegeeks.com/android/android-gameshttp://www.javacodegeeks.com/2011/07/android-game-development-game-loop.htmlhttp://www.javacodegeeks.com/2011/07/android-game-development-measuring-fps.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-measuring-fps.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-measuring-fps.html#abouthttp://www.javacodegeeks.com/android/android-gameshttp://www.javacodegeeks.com/2011/07/android-game-development-game-loop.htmlhttp://www.javacodegeeks.com/2011/07/android-game-development-measuring-fps.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-measuring-fps.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-measuring-fps.html#about
  • 8/9/2019 Android Game Development Tutorials

    54/201

    032 private*inalstaticintHG>@?-L>J 8 10;033 %% last time t)e status (as stored

    034 privatelonglasttatustore 8 0;035 %% t)e status time counter

    036 privatelongstatusnterval?imer 8 0l;03$ %% number o* *rames skipped since t)e game started

    03+ privatelongtotalHrameskipped 8 0l;03 %% number o* *rames skipped in a store cycle /1 sec

    040 privatelong*rameskippedGertat'ycle 8 0l;

    041

    042 %% number o* rendered *rames in an interval

    043 privateint*rame'ountGertat'ycle 8 0;044 privatelongtotalHrame'ount 8 0l;045 %% t)e last HG values

    046 privatedouble*pstoreTU;04$ %% t)e number o* times t)e stat )as been read

    04+ privatelongstats'ount 8 0;04 %% t)e average HG since t)e game started

    050 privatedoubleaverageHps 8 0.0;

    051

    052 %% ur*ace )older t)at can access t)e p)ysical sur*ace

    053 privateur*ace@older sur*ace@older;054 %% ?)e actual vie( t)at )andles inputs

    055 %% and dra(s to t)e sur*ace

    056 privateDainFameGanel gameGanel;

    05$

    05+ %% *lag to )old game state

    05 privatebooleanrunning;060 publicvoidsetunning/booleanrunning #

    061 t)is.running 8 running;062

    063

    064publicDain?)read/ur*ace@older sur*ace@older DainFameGanel gameGanel #065 super/;

    066 t)is.sur*ace@older 8 sur*ace@older;

    06$ t)is.gameGanel 8 gameGanel;

    06+

    06

    0$0 ,-verride

    0$1 publicvoidrun/ #0$2 'anvas canvas;

    0$3

  • 8/9/2019 Android Game Development Tutorials

    55/201

  • 8/9/2019 Android Game Development Tutorials

    56/201

    130 i*/canvas C8 null #131 sur*[email protected]'anvasAndGost/canvas;

    132

    133 %% end *inally

    134

    135

    136

    13$%&&

    13+& ?)e statistics : it is called every cycle it c)ecks i* time since last

    13& store is greater t)an t)e statistics gat)ering period /1 sec and i* so

    140& it calculates t)e HG *or t)e last period and stores it.

    141 &

    142 & t tracks t)e number o* *rames per period. ?)e number o* *rames since

    143 & t)e start o* t)e period are summed up and t)e calculation takes part

    144 & only i* t)e ne"t period and t)e *rame count is reset to 0.

    145 &%

    146 privatevoidstoretats/ #14$ *rame'ountGertat'ycleKK;

    14+ totalHrame'ountKK;

    14

    150 %% c)eck t)e actual time

    151statusnterval?imer K8 /ystem.current?imeDillis/ : statusnterval?imer;

    152

    153 i*/statusnterval?imer 8 lasttatustore K ?A?>J?EAJ?EA< %1000;

    156

    15$ %%stores t)e latest *ps in t)e array15+ *pstoreT/int stats'ount V HG>@?-L>JU 8 actualHps;

    15

    160 %% increase t)e number o* times statistics (as calculated

    161 stats'ountKK;

    162

    163 doubletotalHps 8 0.0;164 %% sum up t)e stored *ps values

    165 *or/inti 8 0; i HG>@?-L>J; iKK #166 totalHps K8 *pstoreTiU;

    16$

    16+

    16 %% obtain t)e average

    1$0 i*/stats'ount HG>@?-L>J #1$1 %% in case o* t)e *irst 10 triggers

    1$2 averageHps 8 totalHps % stats'ount;

    1$3 else#1$4 averageHps 8 totalHps % HG>@?-L>J;

    1$5

    1$6 %% saving t)e number o* total *rames skipped

  • 8/9/2019 Android Game Development Tutorials

    57/201

  • 8/9/2019 Android Game Development Tutorials

    58/201

    05

    06

    0$ publicvoidrender/'anvas canvas #0+ canvas.dra('olor/'olor.B

  • 8/9/2019 Android Game Development Tutorials

    59/201

    8ut a movin! ima!e it6s a #rett+ dull si!ht as it loo$s reall+ fa$e and amateurish& 'o !ive the

    "hara"ters some life we will need to do more than that& 'hat is what animation is all about& A

    ro"$ is an inanimate ob.e"t and even if it is thrown, it doesn6t "han!e its sha#e& A human on theother hand, is ver+ animated& 'r+ throwin! one and +ou6ll see twit"hin! limbs and even s"reams

    in the air&

    Bet6s .ust resort to eaminin! wal$in! whi"h is #rett+ "om#le in its own& *ma!ine a human

    "rossin! +our wa+ .ust in 2& ou6ll noti"e different dis#la+s of the bod+& Beft foot in front,ri!ht hand in front while the o#osite limbs are behind& 'his slowl+ "han!es so the left foot

    remains behind while the ri!ht #ro!resses alon! with the bod+& 8ut at one #oint the "+"le re#eats&

    *f +ou don6t "lose +our e+es +ou see the #erson #ro!ressin! smoothl+& *f +ou "lose +our e+es and$ee# them "losed for a bit and o#en them a!ain the #erson alread+ went on and is in a different

    #osition& 'r+ blin$in! uite ra#idl+ and +ou will see somethin! li$e the old bla"$ and white

    "omedies& 'hat is low frame rate& :ore on P here&

    A"tuall+ we do want a low frame rate wal$in! for this tutorial, .ust li$e this&

    'he wal$in! #resented above is a bit dod!+ but it6s a ri##ed off version of the s#rites from:on$e+ *sland& he6s Dlaine :arle+&

    'his is "alled a *prite& *t is a sim#le 2 dimensional ima!e or animation&

    'o be able to re="reate the above animation, we need ever+ frame from the wal$in! "+"le&

    *t is a 150 #iels wide ima!e and ea"h frame is 30 #iels wide&

    'o illustrate it better "he"$ the followin! ima!e&

    'o !et the above animation in android or iPhone or in an+ other #ro!ram for that matter, we

    need to load u# ea"h frame as a se#arate ima!e and dis#la+ them at re!ular intervals one after

    ea"h other& FK we "an load u# the bi! ima!e "ontainin! all the frames and use the methods

    #rovided b+ android do sli"e and di"e them on the fl+ and to dis#la+ onl+ the relevant frame&'o do that is trivial& e $now that we have 5 frames and ea"h frame is 30 #iels wide& e define

    a re"tan!le that will be our sele"tion whi"h has the width of one frame and the hei!ht of theima!e&

    'he followin! ima!e shows how * "ut out the first two frames& 'he rest +ou should fill in&

    http://www.javacodegeeks.com/2011/07/android-game-development-game-loop.htmlhttp://www.javacodegeeks.com/2011/07/android-game-development-game-loop.html
  • 8/9/2019 Android Game Development Tutorials

    60/201

    nowin! all this let6s !o "reate the #ro.e"t& e will use the $nowled!e from some #revious

    "ha#ters, most notabl+ about the!ame loo#and the one about theima!e dis#la+here we set u#the thread that tri!!ers the drawin! of the !ra#hi"s item ever+ frame&

    e will need an ob.e"t to animate& e use Dlaine from :on$e+ *sland so * will the "lass

    +laineAnimated.java&

    view source

    print?

    01 publicclassElaineAnimated #

    02

    03 privatestatic*inaltring ?AF 8 ElaineAnimated.class.getimpleJame/;

    04

    05privateBitmap bitmap; %% t)e animation seNuence

    06

    privateect sourceect; %% t)e rectangle to be dra(n *rom t)e animationbitmap

    0$ privateint*rameJr; %% number o* *rames in animation0+ privateintcurrentHrame; %% t)e current *rame0 privatelong*rame?icker; %% t)e time o* t)e last *rame update

    10 privateint*rameGeriod; %% milliseconds bet(een eac) *rame /1000%*ps11

    12

    privateintspriteidt); %% t)e (idt) o* t)e sprite to calculate t)e cut outrectangle

    13 privateintsprite@eig)t; %% t)e )eig)t o* t)e sprite

    14

    15 privateint"; %% t)e M coordinate o* t)e obIect /top le*t o* t)e image16 privateinty; %% t)e L coordinate o* t)e obIect /top le*t o* t)e image

    1$

    1+

    'he #rivate attributes are "ommented but worth mentionin! a few&

    bitma3is the #n! file "ontainin! all the frames& 'he se"ond ima!e in this arti"le&

    source7ectis the sele"tion re"tan!le& *t is the blue window in the ima!e above& 'he

    re"tan!le moves ever+ frame onto the net&

    http://www.javacodegeeks.com/2011/07/android-game-development-game-loop.htmlhttp://www.javacodegeeks.com/2011/07/android-game-development-game-loop.htmlhttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.htmlhttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.htmlhttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-game-loop.htmlhttp://www.javacodegeeks.com/2011/07/android-game-development-displaying.htmlhttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#about
  • 8/9/2019 Android Game Development Tutorials

    61/201

  • 8/9/2019 Android Game Development Tutorials

    62/201

    01 publicvoidupdate/longgame?ime #02 i*/game?ime *rame?icker K *rameGeriod #03 *rame?icker 8 game?ime;

    04 %% increment t)e *rame

    05 currentHrameKK;

    06 i*/currentHrame 8 *rameJr #

    0$ currentHrame 8 0;0+

    0

    10 %% de*ine t)e rectangle to cut out sprite

    11 t)is.sourceect.le*t 8 currentHrame & spriteidt);

    12 t)is.sourceect.rig)t 8 t)is.sourceect.le*t K spriteidt);

    13

    'he u#date is "alled from the main !ame #anel "he"$ #revious entries how that wor$s& 'his isthe u#date method of the#ainGame$anel"lass&

    view source

    print?

    1 publicvoidupdate/ #2 elaine.update/ystem.current?imeDillis/;

    3

    'he u3datemethod is sim#le Dlaine6s& *t in"rements the frame if the #assed in time whi"h isthe s+stem time when the u#date method was "alled is !reater than the last time 'rameTicker

    the frame was u#dated #lus the #eriod of the net u#date&

    *f the net frame is be+ond the last, we reset the "+"le&

    After all that area from whi"h the ima!e will be "ut out is defined as the source7ect&

    'hat6s it& How let6s !o on to dis#la+ it&

    view source

    print?

    1 publicvoiddra(/'anvas canvas #2 %% ()ere to dra( t)e sprite

    3ect destect 8 ne(ect/getM/ getL/ getM/ K spriteidt) getL/ Ksprite@eig)t;

    4canvas.dra(Bitmap/bitmap sourceect destect null;

    5

    'hat is all& e set the destination re"tan!le as to where to draw the "ut out ima!e& *t is at Dlaine6s#osition Z and set in the "onstru"tor&

    view source

    http://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#viewSource
  • 8/9/2019 Android Game Development Tutorials

    63/201

    print?

    1 canvas.dra(Bitmap/bitmap sourceect destect null;

    tells android to "ut out the ima!e defined b+ source7ectfrom the ima!e "ontained in bitma3and

    draw it into the re"tan!le on the "anvas defined b+ dest7ect&

    'he drawis "alled from the !ame #anel6s render method tri!!ered b+ the !ame loo# "he"$

    #revious entries&

    'he#ainGame$anel.javadiffers sli!htl+ from the one from #revious "ha#ters& * !ot rid of all

    the droid and added .ust Dlaine&

    view source

    print?

    01 privateElaineAnimated elaine;02

    03 publicDainFameGanel/'onte"t conte"t #04 %%& ... removed ... &%

    05

    06 %% create Elaine and load bitmap

    0$ elaine 8 ne(ElaineAnimated/0+ BitmapHactory.decodeesource/getesources/ .dra(able.(alk>elaine

    0 10 50%% initial position10 30 4$%% (idt) and )eig)t o* sprite11 5 5; %% HG and number o* *rames in t)e animation

    12

    13 %% create t)e game loop t)read

    14 t)read 8 ne(Dain?)read/get@older/ t)is;

    15

    16 %%& ... removed ... &%

    1$

    Dlaine is instantiated in the #anel6s "onstru"tor and is !iven an initial #ositon of ZR10, R50& *

    #ass in the width and the hei!ht of the s#rite too but that is i!nored an+wa+, but +ou "an modif+

    the "ode&'he P is ver+ im#ortant and the number of frames too& P sa+s how man+ frames are to be

    shown in one se"ond& 'he last #arameter is the number of frames in the "+"le&

    'he thread and a"tivit+ "lasses haven6t "han!ed at all& ou "an find them in the download as the+are uite lon! to be #asted& 'he ima!e is named walk0elaine.3n"and it was "o#ied to

    resdrawable4md3iso android "an #i"$ it u# automati"all+&

    *f +ou run the a##li"ation +ou should be seein! Dlaine #erformin! wal$in! "+"les in one #la"e&

    e should have used .um#in! as that "an be #erformed in one #la"e but +ou !et the idea&

    http://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#about
  • 8/9/2019 Android Game Development Tutorials

    64/201

    Elaine Walkin

    ;nhancement

    'o ma$e some neat additions modif+ Dlaine6s drawmethod so it dis#la+s the ori!inal ima!e

    "ontainin! the s#rites from whi"h the frames are etra"ted&

    view source

    print?

    1 publicvoiddra(/'anvas canvas #2 %% ()ere to dra( t)e sprite

    3ect destect 8 ne(ect/getM/ getL/ getM/ K spriteidt) getL/ Ksprite@eig)t;

    4canvas.dra(Bitmap/bitmap sourceect destect null;

    5 canvas.dra(Bitmap/bitmap 20 150 null;

    6 Gaint paint 8 ne(Gaint/;$paint.setAFB/50 0 255 0;

    +canvas.dra(ect/20K /currentHrame & destect.(idt)/ 150 20K/currentHrame & destect.(idt)/ K destect.(idt)/ 150K

    destect.)eig)t/ paint;

    'his .ust dis#la+s the ima!e at 20, 150 and "reates a new #aint ob.e"t so we "an #aint over the

    "urrent frame on the ori!inal ima!e&

    'he method setA7G5"reates a semi=trans#arent !reen #aint& 'he first value is 5+whi"h means

    it6s 75[ trans#arent& +is "om#letel+ trans#arent while ,55is full+ o#aue&After ever+thin! was drawn we #aint a re"tan!le of the sie of a frame onto the ori!inal ima!e so

    +ou see whi"h frame is bein! dis#la+ed in the motion&

    http://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#abouthttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#viewSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#printSourcehttp://www.javacodegeeks.com/2011/07/android-game-development-sprite.html#about
  • 8/9/2019 Android Game Development Tutorials

    65/201

    Walkin with Current Frame Painted

    'hat6s it& Kun it and +ou have +our first s#rite animation&

    ownload the sour"e "odehere animationTwal$&tar&!

    Reference:#rite Animation with Androidfrom ourJ%G#artner 'amas Jano from (A!ainst 'he

    Grain) blo!&

    o not for!et to "he"$ out our new Android GameArkDroids"reenshots below& ou feedba"$

    will be more than hel#ful/

    10

    Android Game Development Particle#$plosionPublished on Au!ust 2, 2011 |1

  • 8/9/2019 Android Game Development Tutorials

    66/201

    dire"tion& 'he ma!nitude will determine its s#eed and its dire"tion will tell the #arti"le whi"h

    wa+ to !o&

    The 'article

    'he "lass file;

    view source

    print?

    01 publicclassGarticle #

    0203 publicstatic*inalint?A?E>AEA 8 1; %% particle is dead