没有合适的资源?快使用搜索试试~ 我知道了~
Gamebryo简单的入门材料1 使用状态机,CEGUI和gamebryo构造一个简单游戏框架,代码简洁易懂,步骤详细.
资源推荐
资源详情
资源评论
ImplementingGameplayElementsUsingGamebryo
Chapter2:ControllingCharactersandViewingtheGameLevel1
Chapter2–ControllingCharactersandViewingtheGameLevel
DoingSomething
InChapter1,youlearnedhowtocreateabasicapplicationframeworkfora gamebyusingafinite
statemachinetomanagehighlevelgamestates,includinggameconfigurationscreens,themain
gameplaystate,andapausedstate.Thecodeforthatchapterallowedtheplayertoselectthein
‐
game player character. The main gameplay state simply included a static camera looking at the
selected character, which stayed in one location running an idle animation. That idle behavior
wasn’t very interesting, was it? It certainly wasn’t gameplay. So, with this chapter, let us begin
enablingsomeinteractionwithcharacters.
Wearegoingtoenabletheplayertouse agamepadtoaffectcharacterlocomotion,andtocontrol
a thirdperson camera system.The chapteris subdivided intofour partsthatprogressively build
up the capability of our simple game, with each part introducing one or two important new
concepts.
Prerequisites
Startingwith thischapter, thesample gameapplication requiresthat youhave atleastonetwo‐
analog‐joystickgamepadinstalled onyour system.The codehas beentestedwith anXbox360™
Controller.
Part1:MakingthePlayer’sCharacterMove
The first thing we are going to do is to add the ability for the player to control whether the
characteris idle,walkingor runningforward alongaspecified worldspacedirection,or walking
backward. This part of the chapter introduces NiEntity Components, which are part of
Gamebryo,and
InputHandlers,asimplemethodofmappinguserinputtogameactions.
The code for this portion of the chapter is labeled Chapter2_Part1 in the solution file, and is
locatedintheChapter2/Part1_SourceWin32folderondisk.Thefollowinglistisasummaryofthe
features we are going to add
to the game appli cation, to accomplish our goal of enabling the
playertocontrolsimplecharacterlocomotionwithathirdpersonviewofthecharacter.
• We will create a CharacterComponent class, enabling us to transition between
characteranimationstatesviaindirectaccesstotheNiAnimationsystem.
• We will create
a CharacterControlInputHandler class to map input from a
gamepad to determine whether the player wishes the character to stay idle or to move
forwardorbackward.
• We will create a CommonInputHandler class to take over responsibility for processing
thekeyboardcontrolsintroducedinChapter1.
• Wewillcreate
aThirdPersonCameraComponentclass,whichwillimplementasimple
thirdpersoncamerathatisalwayslookingattheplayer’scharacter.
ImplementingGameplayElementsUsingGamebryo
Chapter2:ControllingCharactersandViewingtheGameLevel2
AbouttheNiEntityFramework
We will create our character and third person camera components using the NiEntity
framework inthischapter. The NiEntity frameworkenables game scenes tobe loaded, saved,
andmanipulated.Now,if
youhavestudiedotherGamebryotutorials,andhavereadthereference
manual, then you may be thinking, “I can do the very same thing using standard Gamebryo
objectsand NIFfiles.Why shouldIconsider usingthe NiEntityframeworkinstead?” Thisisa
goodquestion!Thisframeworkwon’tbethebest
solutionforallgames,butitdoesofferacouple
ofcompellingfeaturesforourpurposes.
Reason number one: the Gamebryo Scene Designer application, a Gamebryo level design and
editing tool, creates scenes that are based on NiEntity. The NiEntity framework is able to
loadlevelsbuiltusingSceneDesigner
andsaved as*.gsa files.SinceSceneDesignerisaconvenient
waytobuild completegame levels,whendevelopingcomplex gamesit onlymakessensetotake
advantage ofit. (In Chapter1, we tookadvantage ofNiEntity to enableus toload scenesthat
had been designed using the
Gamebryo SceneDesigner application, and we used some limited
featuresofNiEntitytospawntheplayer’sselectedcharacterintothechosengamelevel.)
Reasonnumbertwo:theNiEntityframeworkisbasedontheideaofexposingobjectproperties
andfunctionalityviareflection.Thatis,theframeworkprovidesgenericfunctionsfordiscoverin g
andmanipulatingpropertiesofobjectsatruntimeratherthanatcompiletime.ThisenablesScene
Designertoprovidegenericeditingofproperties,andtoalloweditingofobjectsimplementedin
custom, game‐specific libraries that are not linked directly into the standard binary builds of
Scene Designer. In later chapters,
we will exploit this generic runtime access to properties and
functionality to integrate a scripting language. It will enable us to minimize the amount of
specializedcoderequiredtoexposefunctionalitytothescriptingengine.
AddingaComponenttotheNiEntityFrameworktoEnableCharacterAnimationControl
Thefirstthingwe
aregoingtodoisaddabitofcodethatwillenableustochangethelocomotion
state of the player’s character. Recall from Chapter 1 (source code reference) that the
m_pkPlayableCharacter member of the MainGamePlay state class was a pointer to the
entityrepresentingthecharacterthatthe
playerchosepriortostartingthegame.Wearegoingto
addplayercontrolofthischaracter.
A game scene, represented by an NiScene object, contains both the current game level being
played and any actors that are participating in the level. The m_pkPlayableCharacter
member variableisa pointer tothe
virtualinterface class, NiEntityInterface; however, the
concreteobjectthatthemembervariablepointstoisaNiGeneralEntityobjectthatcontains
anNiActorComponent.Thiscombination istheNiEntityframework’swayofrepresentingan
animatedcharacterinthescene.
TheNiActorComponentprovidesaccess(viaintrospection)tocharacter‐specificpropertiesand
features,
includingtheabilitytochangetheanimationstateofthecorrespondingcharacterandto
place and orient the character in the scene. The component ultimately makes use of the core
ImplementingGameplayElementsUsingGamebryo
Chapter2:ControllingCharactersandViewingtheGameLevel3
Gamebryo NiAnimation system feature set for controlling characters, e.g., it uses an
NiActorManager object internally. The NiActorComponent exposes a property named
“Active Se quence ID,” which we can change via the reflection interface to cause a
character to
change its animation state. The NiEntity framework automatically applies the value of this
propertytothecharacterasananimationsequencenumber.Theneteffectisidenticaltocallin g
NiActorManager::SetTargetAnimation directly. The component is in fact calling this
function(orsomethingsimilar)internally.So,usingtheexistingNiActorComponentclass
that
is instantiated automatically when we load an NiEntity scene that contains a character, we
immediatelyhaveawaytocontrolourcharacter’sanimationstatewithoutwritinganynewcode.
Wecould,technically,writeourplayerinputcodein suchawaythatitdirectlymodifiesproperty
valuesownedby
NiActorComponent,suchas“ActiveSequenceID.”ButNiActorComponent
doesnotprovideallofthebehaviorwewilleventuallyneed.And,so,wearegoingtocreateanew
componentinstead,calledCharacterComponent,whichwillprovidethefollowingbenefits:
• Ournewcomponentwillbeabletoreinterpretplayer‐orartificial
‐intelligence‐prescribed
input goals, passing a wider variety of animation state information to the
NiActorComponent, or directly to the NiActorManager it owns, should this be
necessary to satisfy certain constraints or inputs. (Note the foreshadowing in that last
statement.)
• OurnewcomponentwillprovideadditionalbehaviorthatNiActorComponentdoes
not
provide,suchasimplementinggenericlocomotionforcharactermodelsthatdonothave
accumulatingtransformsbakedintothekeyframes.
Thefirst bitofcode weneedistodefineasetofgeneric locomotionstates.We willstartwith a
smallsetofcommonstates:idle,walk,andrun
(andafewothersthatweknowwewillneedlater
on). For the sample code for Part 1 of this chapter, these types are defined by the
CharacterLocomotionState enum in the CommonAnimations.h header file in the
character_controlsubfolder:
enum CharacterLocomotionState
{
CLS_UNKNOWN = -1, ///< Character state is unknown
CLS_IDLE = 1, ///< Character is idle, staying in one location
CLS_WALK_FORWARD, ///< Character walking forward
CLS_RUN_FORWARD, ///< Character running forward
CLS_TURN_LEFT, ///< Character turning left while moving forward
CLS_TURN_RIGHT, ///< Character turning right while moving forward
CLS_WALK_BACKWARD ///< Character walking backward
};
TheCharacterComponentclasswillhaveapropertywhosevaluewillbeequaltooneofthose
enumvalues,asspecifiedbyAIorplayerinput.Theclasswillusethisanditsotherpropertiesto
chooseacharacteranimationsequence.
ImplementingGameplayElementsUsingGamebryo
Chapter2:ControllingCharactersandViewingtheGameLevel4
The demo code requires character animation sequence IDs, located in *.kfm and *.kf files, to
match across all characters used in the demo, e.g., the animation data files must have an idle
sequencewithID
=1,awalkforwardsequencewithID=2,andarunforwardsequencewithID=
3.Foryourowngame,insteadofrequiringconsistentsequenceIDs,youcould choosetorequire
that your artists use the same sequence names for all characters, e.g., always calling the walk
sequence
“walk_forward.”ThiswouldrequireadditionalcodetosearchforthesequenceIDwhen
changingsequences.
Thesample implementationofCharacterComponentis inthecharacter_controlsubfolder for
Part 1. This component will not implement its own code to directly manipulate the character
animation state, since NiActorComponent already provides for that. Rather,
CharacterComponentuses thereflectioninterfaceto feedtheappropriatesequence IDtothe
entity’s NiActorComponent. The following two figures illustrate the manner in which our
player input control code will assign a locomotion state to the entity representing the player’s
character.
NiGenericEntity CharacterComponent
LocomotionState
PlayerInputMapping
Code
Here, the player input mapping code (described later) somehow decides which behavior the
playerintendsforthecharacter,andthenusestheNiEntityreflectionframeworktoassignthe
generic locomotion state to the CharacterComponent. The assignment is done via a generic
call onthe entity,assigningthe propertyby
nameand value. Thereflection frameworksearches
through its collection of components to find the owner of the property. The
CharacterComponentobjectthenusesitsinternalbehaviormappingtochoosetheappropriate
sequence ID, and uses reflection to assign that to the NiActorComponent, as shown in the
followingfigure.
NiGenericEntityCharacterComponent NiActorComponent
ActiveSequence ID
Here too, the sequence IDis assigned to NiActorComponent by generically calling a function
ontheentity.Asdescribedearlier,aprimary advantageofthereflectionframeworkisthatitdoes
allow properties and functionality to be accessed in this generic way. While the approach may
剩余38页未读,继续阅读
资源评论
智匪
- 粉丝: 0
- 资源: 6
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功