Tải bản đầy đủ - 0 (trang)
Chapter 13. Moving into Real Game Development

Chapter 13. Moving into Real Game Development

Tải bản đầy đủ - 0trang

SpritesthatComeAlive

Spritesmovearoundthescreen,andastheydotheytypically

changeappearance.Imagineyou'remakingagamecalledMole

Thumper.Theobjectofthegameistoguideafarmeraround

thescreenandhavehimthumpmolesontheheadsothey

don'teathiscorn.Asthefarmermoves,hemustappearto

walk.Whenhethumpsthemoles,hemustswinghismallet

downontheirpeskylittleheads.Themolesmustreacttobeing

thumped.Allofthismeansthatthefarmerandthemolesmust

changeappearanceasthegameprogresses.That'sprecisely

thepurposeofanimatedsprites.



SpritesandAnimationFrames

Tocreateananimatedsprite,youmustimagineaspriteasa

rectangularmoviescreenthatmovesaroundthecomputer's

display.Becausethespriteislikeaminiaturemoviescreen,

yourgamecandisplaysuccessiveimagesonthesprite's

"screen"togivetheappearanceofmovementandchange.

Forexample,supposeyouwanttodisplayafarmerwalking

acrossthescreen.Todoso,youdisplayasuccessionofimages

ofthefarmerwithhislegsandarmsinaslightlydifferent

position.Eachsuccessiveimageisoneframeofthesprite's

animation.Everyframeofspriteanimationhastofitintothe

animationframesofthescreenasawhole.Inotherwords,to

getthefarmertowalkacrossthescreen,youranimatedsprite

mustdisplaythefirstframeofitsanimationinaframeof

screenanimation.Thespritethendrawsthenextframeofits

animationintothenextscreenframe.Thespritecontinuesin

thiswayuntilitreachestheendofitsanimationframes.Itthen

repeatstheanimationtocontinuetheappearanceofthefarmer

walking.



Inprofessionalgames,therearetypicallymanysprites

displayedonthescreenatonce.Duringeachframeofscreen

animation,eachspritebusilydisplaysoneframeofits

animation.Theresultisthat,duringeachframeofscreen

animation,allofthespriteschangeappearance.Themovement

andthevariationiswhathelpsmakethegamecomealive.



AnimatedSpritesinLlamaWorks2D

LlamaWorks2Dprovidestwoclassesthatenableyoutoeasily

addanimatedspritestoyourgames.Thefirstisthe

animated_spriteclass.Theanimated_spriteclassactslikearegular

spriteinthatitmovesaroundthescreen.Inaddition,each

animated_spriteobjectcancontainoneormoreanimation.An

animationisimplementedinaclasscalledanimation.Ananimation

objectholdsthebitmapimagesthatitusesastheframesofits

animation.

Objectsoftypeanimated_spritecanhavemultipleanimations.In

ourmolethumpinggame,theanimated_spriteobjectthegame

usestorepresentthefarmerneedsanimationsofthefarmer

walkingleftandright.Italsoneedsanimationsofthefarmer

swinginghismallet.Itmayhaveananimationofthefarmer

cryingwhenthemolesgetallhiscorn,oroneofhimdancing

whenhethumpsthelastmoleonthelevel.Theabilitytohold

multipleanimationsinananimated_spriteobjectenablesyouto

createawiderangeofbehaviorsforyourgame'scharacters.

Tobuildananimatedsprite,yourgamebeginsbycreatingat

leastoneanimationobject.Itloadsframesintotheanimation.

Next,yourprogramcreatesananimated_spriteobjectandadds

theanimationobjecttoit.Itcanaddmoreanimationsas

necessary.Onlyoneanimationcanbedisplayedatatime.

Therefore,oneoftheanimationsintheanimatedspriteis

alwaysconsideredthecurrentanimation.Bydefault,thelast

animationyouaddtothespriteisthecurrentanimation.



However,youcanselectanyanimationthattheanimated_sprite

objectcontainstobethecurrentanimation.

AnimationsinLlamaWorks2Dcanloop.Thisenablesyourgame

todisplaymotionthatlookscontinuous.Thewalkingfarmeris

anexample.Asthefarmerwalksacrossthescreen,his

animationloopsoverandoveruntilhechangesdirectionor

thumpsamole.Thenadifferentanimationplays.



Note

Loopingframesinforwardandthenreverseorderis

verycommon.Whenyourgamedoesthis,itdisplays

eachframeofthespritefromfirsttolast.Itthen

displaysthemfromlasttofirst.Thisstyleoflooping

isusuallywhatisusedtomakecharacterswalk.



Yourgamecandisplayanimationsthatloopforward,reverse,or

forwardandthenreverse.Forwardloopingmeansthatthe

animationisdisplayedfromthefirstframetothelastframe.

Theanimationthenstartsoverwiththefirstframe.Reverse

animationisjusttheopposite.Theanimationstartswiththe

lastframeandthendisplayseachframeinreverseorderuntilit

getstothefirstframe.Itthenstartsover.Thisenablesyour

gametodosomeniceeffectsverysimply.



CannonshootRevisited

Let'sdiveintoasampleprogramtoseehowanimatedsprites

work.We'llusearevisedversionofthecannonsimulator

programfromchapter9.Inthisrevisedversion,theprogram

displaysananimationofanexplosionwhenthecannonballhits



theground.

IfyoulookatthefilesthatmakeuptheCannonShootprogram,

you'llseethatinadditiontotheLlamaWorks2Dfiles,

CannonShootincludesthefilesCannonShoot.hand

CannonShoot.cpp.Thesefilescontainthelogicofhowthegame

works.However,CannonShoot.handCannonShoot.cppdonot

needtobechangedinordertoaddanimatedsprites.Instead,

theanimatedspriteisaddedtothecannonballobject,whichisin

thefilesCannonball.handCannonball.cpp.Let'sbeginby

lookingatthenewversionofCannonball.hinListing13.1.

Listing13.1presentspartofthefileCannonball.h.Tosave

space,I'veomittedthepartsthathavenotchangedsince

chapter9.Online48,youcanseethatthere'sanewdata

memberoftypeanimated_sprite.Thisisinadditiontothesprite

objectdeclaredonline47.Whilethecannonballisinflight,the

cannonballobjectdisplaysthespriteobjectthatcontainsthe

imageoftheball.Whenthecannonballhitstheground,the

cannonballobjectdisplaystheanimated_spriteobject.Thiscauses

theanimationoftheexplosiontobeplayed,asshowninFigure

13.1.



Figure13.1.Whenthecannonballisinflight(left

frame),theprogramusesaspriteobjectbecause

itdoesn'tchangeappearance.Afterthe

cannonballhitstheground(rightframe),the

programusesananimatedspritetodisplaythe

explosion.



Note

YoucanfindCannonball.hontheCDinthefolder

Source\Chapter13\Prog_13_01.



Listing13.1.Addingananimatedspritetothe

cannonballclass



1classcannonball

2{

3public:

4cannonball();

5

6boolLoadImage(

7std::stringfileName,

8image_file_base::image_file_formatfileFormat);

9

10boolLoadExplosionAnimation();

11

12boolLoadHitSound(

13std::stringfileName);

14

15voidBallHit();

16boolDidBallHit();

17

18boolMove();

19boolRender();

20

21voidX(

22floatupLeftX);

23floatX();

24

25voidY(

26floatupLeftY);

27floatY();

28

29intBitmapHeight();

30intBitmapWidth();

31



32voidBoundingRectangle(

33bitmap_regionrectangle);

34bitmap_regionBoundingRectangle();

35

36voidBitmapTransparentColor(

37color_rgbtheColor);

38color_rgbBitmapTransparentColor();

39

40voidVelocity(

41vectorfdirection);

42vectorfVelocity();

43

44boolBallInFlight();

45

46private:

47spritetheBall;

48animated_spriteballExplosion;

49vectorfvelocity;

50floatx,y;

51boolballInFlight;

52boolballHit;

53soundballHitSound;

54};



Inaddition,there'sanewdatamemberonline52thatkeeps

trackofwhenthecannonballhitssomething.Thereisalsoa

newmemberfunctioninthecannonballclassonline16ofListing

13.1.Ittellsotherclasseswhenthecannonballhashit

something.Thecannonballclasscontainsanewmemberfunction

forloadingtheexplosionanimationonline10.

Mostofthememberfunctionsofthecannonballdonotneedto

change.However,thosethatdo,alongwiththenewmember

functions,areshowninListing13.2.



Listing13.2.Newandupdatedmemberfunctions

forthecannonballclass



1cannonball::cannonball():

2velocity(0.0f,0.0f)

3{

4ballInFlight=false;



5ballHit=false;

6}

7

8

9bool

10cannonball::LoadExplosionAnimation()

11{

12boolloadOK=true;

13animation*theAnimation=newanimation;

14

15if(theAnimation!=NULL)

16{

17theAnimation>BitmapTransparentColor(

18color_rgb(0.0f,1.0f,0.0f));

19

20loadOK=theAnimation>LoadImage(

21"Expl1.bmp",

22image_file_base::LWIFF_WINDOWS_BMP);

23}

24else

25{

26loadOK=false;

27theApp.AppError(LWES_OUT_OF_MEMORY);

28}

29

30if(loadOK)

31{

32loadOK=theAnimation>LoadImage(

33"Expl2.bmp",

34image_file_base::LWIFF_WINDOWS_BMP);

35}

36

37if(loadOK)

38{

39loadOK=theAnimation>LoadImage(

40"Expl3.bmp",

41image_file_base::LWIFF_WINDOWS_BMP);

42}

43

44if(loadOK)

45{

46loadOK=theAnimation>LoadImage(

47"Expl4.bmp",

48image_file_base::LWIFF_WINDOWS_BMP);

49}

50

51if(loadOK)

52{

53loadOK=theAnimation>LoadImage(

54"Expl5.bmp",

55image_file_base::LWIFF_WINDOWS_BMP);

56}

57

58if(loadOK)

59{

60loadOK=theAnimation>LoadImage(



61"Expl6.bmp",

62image_file_base::LWIFF_WINDOWS_BMP);

63}

64

65if(loadOK)

66{

67loadOK=theAnimation>LoadImage(

68"Expl7.bmp",

69image_file_base::LWIFF_WINDOWS_BMP);

70}

71

72if(loadOK)

73{

74theAnimation>LoopAnimation(

75true,

76animation::FORWARD_THEN_REVERSE);

77}

78

79if(loadOK)

80{

81//Addtheanimationtotheanimatedsprite.

82ballExplosion.Animation(theAnimation);

83}

84

85return(loadOK);

86}

87

88

89

90void

91cannonball::BallHit()

92{

93velocity.X(0.0f);

94velocity.Y(0.0f);

95ballHitSound.Play();

96ballInFlight=false;

97ballHit=true;

98}

99

100

101bool

102cannonball::DidBallHit()

103{

104return(ballHit);

105}

106

107

108bool

109cannonball::Render()

110{

111boolrenderOK=true;

112

113if(ballInFlight)

114{

115renderOK=theBall.Render();

116}



117elseif(ballHit)

118{

119animation::animation_statusexplosionStatus=

120ballExplosion.AnimationStatus();

121if((explosionStatus!=animation::ANIMATION_ERROR)&&

122(explosionStatus!=animation::AT_END_OF_LOOP))

123{

124ballExplosion.X(theBall.X());

125ballExplosion.Y(theBall.Y());

126renderOK=ballExplosion.Render();

127}

128elseif(explosionStatus==animation::AT_END_OF_LOOP)

129{

130ballHit=false;

131ballExplosion.ResetAnimation();

132}

133elseif(explosionStatus==animation::ANIMATION_ERROR)

134{

135renderOK=false;

136}

137}

138

139return(renderOK);

140}



Note

ThesememberfunctionsarefromCannonball.cppon

theCDinthefolderSource\Chapter13\Prog_13_01.



Listing13.2startswiththeupdatedconstructorfromthe

cannonballclass.Thedifferencebetweenthisversionandtheone

inchapter9isthatthisoneinitializesthenewballHitdata

member.Theconstructordoesnotneedtoinitializethe

cannonballclass'sspriteoranimated_spritemembers.Their

constructorsareautomaticallycalledwheneverthecannonball

classconstructoriscalled.Asaresult,thespriteand

animated_spritemembersareautomaticallyinitializedwhenever

theprogramcreatesacannonballobject.



Thecannonballclass'snewLoadExplosionAnimation()functionbegins

online9ofListing13.2.Online13,LoadExplosionAnimation()uses

theC++newkeywordtodynamicallyallocateananimationobject.

Liketheanimated_spriteclass,theanimationclassisprovidedby

LlamaWorks2D.

Iftheanimationobjectisallocatedsuccessfully,the

LoadExplosionAnimation()functionsetsitstransparentcolor.Setting

thetransparentcolorfortheanimationsetsthetransparent

colorforallofitsframes.

Next,bycallingtheanimationclass'sLoadImage()function

repeatedly,theLoadExplosionAnimation()functionloadsthe

individualframesoftheanimation.Theanimationclassletsa

programloadasmanyframesasneededintoananimation

object.TheprogramjustkeepscallingLoadImage()untilallofthe

framesareloaded.Theframesoftheanimationeachhavean

indexnumber.Numberingstartswith0,sothesevenframesof

theanimationinListing13.2arenumbered06.

Onlines7476,theLoadExplosionAnimation()functiontellsthe

animationobjectthatitsanimationshouldloop.Becausetheloop

directionissettoanimation::FORWARD_THEN_REVERSE,theanimation

objectfirstplaysframes06oftheanimation.Itthenplays

frames5,4,3,2,1,and0tocompletetheloop.Ifthe

animationisallowedtocontinuelooping,theanimationobject

playsframes1,2,3,4,5,and6onthenextloopcycle.

TheLoadExplosionAnimation()functionendsbystoringtheanimation

objectinthecannonballclass'sanimated_spriteobjectonline82.

ThenextfunctioninListing13.2iscalledBallHit().Itisalmost

thesameastheversioninchapter9.However,theversion

shownheresetstheballHitdatamembertotrue.Thisis

importantbecauseofthewayanimationsworkin

LlamaWorks2D.Whentheexplosionanimationbeginsplaying,it

displaysoneofitsanimationframesduringeachscreen

animationframe.Whilethecannonball'sexplosionanimationis



playing,theprogramshouldnotdoanythingelseexceptplay

theexplosionsound.That'sexactlyhowthisnewversionof

CannonHitworks.TheballHitmemberbecomesfalsewhenthe

explosionanimationisdone.Atthatpoint,theprogramletsthe

playershootthecannonagain.TheCannonShootprogramcalls

theDidBallHit()function,whichstartsonline102,todetermine

ifthecannonballclass'sballHitmemberistrueorfalse.



Note

Aslongasthecannonballclass'sballHitmemberis

true,theprogramdoesn'tdoanythingbutdisplay

successiveframesofanimationandplayan

explosionsound.



ThefinalfunctioninListing13.2isthecannonballclass'sRender()

function,whichstartsonline108.ThisversionoftheRender()

functionrendersthecannonballclass'sspriteobjectifthe

cannonballisinflight.That'sshownonlines113116.Ifthe

ballHitdatamemberistrue,theRender()functionrendersthe

cannonballclass'sanimated_spriteobjectinstead.Itdoesthisby

firstgettingthestatusoftheanimated_spriteobject'sanimation.

Iftheanimationiscurrentlyplayingorhasnotyetstarted,it

setsthexandypositionoftheanimated_sprite.Itthenrenders

oneframeofthecannonball'sexplosionanimation.

IntheCannonHitprogram,theideaistohavetheanimated_sprite

objectplayitsanimationonce,andthenlettheprogram

continue.Therefore,thecannonballclass'sRender()function

checkstoseewhethertheanimated_spriteobject'sanimationisat

theendofitslooponline128.Ifitis,theRender()functionsets

ballHittofalse.ThistellstheCannonHitprogramtostop

renderingtheexplosionanimationandcontinue.TheRender()

functionalsocallstheanimated_spriteclass'sReset()functionto



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 13. Moving into Real Game Development

Tải bản đầy đủ ngay(0 tr)

×