1 game system. 2 control system control system user input user input mouse or keyboard mouse or...

81
1 Game System Game System

Upload: arthur-chad-short

Post on 17-Jan-2016

280 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

1

Game SystemGame System

Page 2: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

2

Control systemControl system User inputUser input

Mouse or keyboardMouse or keyboard Keyboard layoutKeyboard layout

Camera controlCamera control View angleView angle View rangeView range Interaction with playerInteraction with player

A “walk through” systemA “walk through” system Combat systemCombat system

ControlsControls Motion management and blendingMotion management and blending NPC AINPC AI FXFX

VisualVisual AudioAudio

Simplify Your Thinking into Modula (1/2)Simplify Your Thinking into Modula (1/2)

Page 3: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

3

Reward systemReward system Number systemNumber system LevelsLevels Damage Damage

User InterfaceUser Interface MenuMenu Mini-mapMini-map MessagesMessages

Blood barBlood bar CaptionCaption

The main programThe main program Main loopMain loop Level managementLevel management ConfigurationConfiguration Save/LoadSave/Load

Simplify Your Thinking into Modula (2/2)Simplify Your Thinking into Modula (2/2)

Page 4: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

4

Page 5: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

5

Game AIGame AISteering BehaviorSteering Behavior

Page 6: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

6

Action selectionAction selection SteeringSteering LocomotionLocomotion

Motion BehaviorMotion Behavior

A Hierarchy of Motion Behavior

Page 7: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

7

Game AI engineGame AI engine State machineState machine

Discussed in “Finite State Machine” sectionDiscussed in “Finite State Machine” section GoalsGoals PlanningPlanning StrategyStrategy

ScriptingScripting Assigned by playersAssigned by players

Players’ inputPlayers’ input

Action SelectionAction Selection

Page 8: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

8

Path determinationPath determination Path finding or path planningPath finding or path planning Discussed in “Path Finding”Discussed in “Path Finding”

BehaviorsBehaviors Seek & fleeSeek & flee Pursuit & evasionPursuit & evasion Obstacle avoidanceObstacle avoidance WanderWander Path followingPath following Unaligned collision avoidanceUnaligned collision avoidance

Group steeringGroup steering

SteeringSteering

Page 9: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

9

Character physically-based modelsCharacter physically-based models MovementMovement

Turn right, move forward, …Turn right, move forward, … AnimationAnimation

By artistsBy artists Implemented / managed by game engineImplemented / managed by game engine

LocomotionLocomotion

Page 10: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

10

A point massA point mass Linear momentumLinear momentum No rotational momentumNo rotational momentum

ParametersParameters MassMass PositionPosition VelocityVelocity

Modified by applied forcesModified by applied forces Max speedMax speed

Top speed of a vehicleTop speed of a vehicle Max steering forceMax steering force

Self-appliedSelf-applied OrientationOrientation

CarCar AircraftAircraft

A Simple Vehicle Model (1/2)A Simple Vehicle Model (1/2)

Page 11: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

11

Local spaceLocal space OriginOrigin ForwardForward UpUp SideSide

Steering forcesSteering forces AsymmetricalAsymmetrical

ThrustThrust BrakingBraking SteeringSteering

Velocity alignmentVelocity alignment No slide, spin, …No slide, spin, … TurnTurn

A Simple Vehicle Model (2/2)A Simple Vehicle Model (2/2)

Page 12: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

12

The approach :The approach : Steer_force = Truncate(streer_direction, Max_force)Steer_force = Truncate(streer_direction, Max_force) Acceleration = Steer_force / massAcceleration = Steer_force / mass Velocity = Truncate(Velocity + Acceleration, Max_speed)Velocity = Truncate(Velocity + Acceleration, Max_speed) Position = Position + VelocityPosition = Position + Velocity

Euler IntegrationEuler Integration

Page 13: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

13

Pursuit to a static targetPursuit to a static target Steer a character toward to a target positionSteer a character toward to a target position

““A moth buzzing a light bulb”A moth buzzing a light bulb” FleeFlee

Inverse of seekInverse of seek VariantsVariants

ArrivalArrival Pursuit to a moving targetPursuit to a moving target

Seek & Flee BehaviorsSeek & Flee Behaviors

Seek Steering forceSeek Steering force desired_velocity = normalize(target - position)*max_speeddesired_velocity = normalize(target - position)*max_speed steering = desired_velocity – velocitysteering = desired_velocity – velocity

Page 14: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

14

One of the idea : a stopping radiusOne of the idea : a stopping radius Outside the radius, arrival is identical to seekOutside the radius, arrival is identical to seek Inside the radius, the speed is ramped down to zeroInside the radius, the speed is ramped down to zero

target_offset = target – positiontarget_offset = target – position distance = length(target_offset)distance = length(target_offset) ramped_speed = max_speed*(distance/slowing_distance)ramped_speed = max_speed*(distance/slowing_distance) clipped_speed = minimum(ramped_speed, max_speed)clipped_speed = minimum(ramped_speed, max_speed) desired_velocity = (clipped_speed/distance)*target_offset desired_velocity = (clipped_speed/distance)*target_offset steering = desired_velocity – velocitysteering = desired_velocity – velocity

Arrival BehaviorArrival Behavior

Page 15: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

15

Target is movingTarget is moving Apply seek or flee to the target’s predicted positionApply seek or flee to the target’s predicted position

Pursuit & Evasion BehaviorsPursuit & Evasion Behaviors

Estimate the prediction interval TEstimate the prediction interval T T = DcT = Dc D = distance(pursur, quarry)D = distance(pursur, quarry) c = turning parameterc = turning parameter

VariantsVariants Offset pursuitOffset pursuit

““Fly by”Fly by”

Page 16: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

16

Use bounding sphereUse bounding sphere Not collision detectionNot collision detection

Obstacle Avoidance Behavior Obstacle Avoidance Behavior

steering force

ProbeProbe A cylinder lying along forward axisA cylinder lying along forward axis Diameter = character’s bounding sphereDiameter = character’s bounding sphere Length = speed (means Alert range)Length = speed (means Alert range)

Find the most threaten obstacleFind the most threaten obstacle Nearest intersected obstacleNearest intersected obstacle

Steering Steering

Page 17: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

17

Random steeringRandom steering One solution :One solution :

Retain steering direction stateRetain steering direction state Constrain steering force to the sphere surface Constrain steering force to the sphere surface

located slightly ahead of the characterlocated slightly ahead of the character Make small random displacements to it each frameMake small random displacements to it each frame

A small sphere on sphere surface to indicate and A small sphere on sphere surface to indicate and constrain the displacementconstrain the displacement

Wander BehaviorWander Behavior

Another one :Another one : Perlin noisePerlin noise

VariantsVariants ExploreExplore

Page 18: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

18

The pathThe path SpineSpine

A spline or poly-line to define the pathA spline or poly-line to define the path PipePipe

The tube or generated cylinder by a defined “radius”The tube or generated cylinder by a defined “radius”

Path Following BehaviorPath Following Behavior

VariantsVariants Wall followingWall following ContainmentContainment

FollowingFollowing A velocity-based prediction positionA velocity-based prediction position

Inside the tubeInside the tube Do nothing about steeringDo nothing about steering

Outside the tubeOutside the tube ““Seek” to the on-path projectionSeek” to the on-path projection

Page 19: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

19

A flow field environment is defined.A flow field environment is defined. Virtual realityVirtual reality

Not common in gamesNot common in games

Flow Field Following BehaviorFlow Field Following Behavior

Page 20: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

20

Turn away from possible collisionTurn away from possible collision Predict the potential collisionPredict the potential collision

Use bounding spheresUse bounding spheres

Unaligned Collision Avoidance BehaviorUnaligned Collision Avoidance Behavior

If possibly collide,If possibly collide, Apply the steering on both charactersApply the steering on both characters Steering direction is possible collision resultSteering direction is possible collision result

Use “future” possible positionUse “future” possible position The connected line between two sphere centersThe connected line between two sphere centers

Page 21: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

21

Steering behaviors determining how the character Steering behaviors determining how the character reacts to the other characters within his/her local reacts to the other characters within his/her local neighborhoodneighborhood

The behaviors including :The behaviors including : SeparationSeparation CohesionCohesion AlignmentAlignment

Steering Behaviors for Groups of CharactersSteering Behaviors for Groups of Characters

Page 22: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

22

The local neighborhood is defined as :The local neighborhood is defined as : A distanceA distance The field-of-viewThe field-of-view

AngleAngle

The Local Neighborhood of a CharacterThe Local Neighborhood of a Character

The Neighborhood

Page 23: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

23

Make a character to maintain a distance from others Make a character to maintain a distance from others nearby.nearby. Compute the repulsive forces within local neighborhoodCompute the repulsive forces within local neighborhood

Calculate the position vector for each nearbyCalculate the position vector for each nearby Normalize itNormalize it Weight the magnitude with distanceWeight the magnitude with distance

1/distance1/distance Sum the result forcesSum the result forces Negate itNegate it

Separation BehaviorSeparation Behavior

Page 24: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

24

Make a character to cohere with the others nearbyMake a character to cohere with the others nearby Compute the cohesive forces within local neighborhoodCompute the cohesive forces within local neighborhood

Compute the average position of the others nearbyCompute the average position of the others nearby Gravity centerGravity center

Apply “Seek” to the positionApply “Seek” to the position

Cohesion BehaviorCohesion Behavior

Page 25: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

25

Make a character to align with the others nearbyMake a character to align with the others nearby Compute the steering forceCompute the steering force

Average the together velocity of all other characters nearbyAverage the together velocity of all other characters nearby The result is the desired velocityThe result is the desired velocity Correct the current velocity to the desired one with the Correct the current velocity to the desired one with the

steering forcesteering force

Alignment BehaviorAlignment Behavior

Page 26: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

26

““Boids Model of Flocks”Boids Model of Flocks” [Reynolds 87][Reynolds 87]

Combination of :Combination of : Separation steeringSeparation steering Cohesion steeringCohesion steering Alignment steeringAlignment steering

For each combination including :For each combination including : A weight for combingA weight for combing A distanceA distance An AngleAn Angle

Flocking BehaviorFlocking Behavior

Page 27: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

27

Follow a leaderFollow a leader Stay with the leaderStay with the leader

““Pursuit” behavior (Arrival style)Pursuit” behavior (Arrival style) Stay out of the leader’s wayStay out of the leader’s way

Defined as “next position” with an extensionDefined as “next position” with an extension ““Evasion” behavior when inside the above areaEvasion” behavior when inside the above area

““Separation” behavior for the followersSeparation” behavior for the followers

Leader Following BehaviorLeader Following Behavior

Page 28: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

28

A simple vehicle model with local neighborhoodA simple vehicle model with local neighborhood Common steering behaviors including :Common steering behaviors including :

SeekSeek FleeFlee PursuitPursuit EvasionEvasion Offset pursuitOffset pursuit ArrivalArrival Obstacle avoidanceObstacle avoidance WanderWander Path followingPath following

Behavior ConclusionBehavior Conclusion

Wall followingWall following ContainmentContainment Flow field followingFlow field following Unaligned collision avoidanceUnaligned collision avoidance SeparationSeparation CohesionCohesion AlignmentAlignment FlockingFlocking Leader followingLeader following

Combining the above behaviors in your applicationCombining the above behaviors in your application

Page 29: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

29

Game AIGame AIFinite State MachineFinite State Machine

Page 30: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

30

Finite State Machine (FSM) is the most commonly Finite State Machine (FSM) is the most commonly used game AI technology today.used game AI technology today. SimpleSimple EfficientEfficient Easily extensibleEasily extensible Powerful enough to handle a wide variety of situationsPowerful enough to handle a wide variety of situations

Theory (simplified)Theory (simplified) A set states, SA set states, S An input vocabulary, IAn input vocabulary, I Transition function, T(s, i)Transition function, T(s, i)

Map a state and an input to another stateMap a state and an input to another state

Introduction (1/2)Introduction (1/2)

Page 31: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

31

Practical usePractical use StateState

BehaviorBehavior TransitionTransition

Across statesAcross states ConditionsConditions

It’s all about driving behaviorIt’s all about driving behavior Flow-chart diagramFlow-chart diagram

UML State chartUML State chart ArrowArrow

TransitionTransition RectangleRectangle

StateState

Introduction (2/2)Introduction (2/2)

Page 32: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

32

An Example of FSM As a DiagramAn Example of FSM As a Diagram

GatherTreasure

Flee

Fight

Monster in sight

No monsterMonster dead

Cor

nere

d

Page 33: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

33

Character AICharacter AI ““Decision-Action” modelDecision-Action” model BehaviorBehavior

Mental stateMental state TransitionTransition

Players’ actionPlayers’ action The other characters’ actionsThe other characters’ actions Some features in the game worldSome features in the game world

FSM for GamesFSM for Games

Page 34: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

34

Code-based FSMCode-based FSM Simple Code One UpSimple Code One Up

StraightforwardStraightforward Most commonMost common

Macro-assisted FSM LanguageMacro-assisted FSM Language Data-Driven FSMData-Driven FSM

FSM Script LanguageFSM Script Language

Implement FSMImplement FSM

Page 35: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

35

Coding an FSM – Code Example 1Coding an FSM – Code Example 1

void RunLogic(int *state)void RunLogic(int *state){{ switch(*state)switch(*state) {{ case 0: // Wandercase 0: // Wander Wander();Wander(); if (SeeEnemy()) *state = 1;if (SeeEnemy()) *state = 1; if (Dead()) *state = 2;if (Dead()) *state = 2; break;break; case 1: // Attackcase 1: // Attack Attack();Attack(); *state = 0;*state = 0; if (Dead()) *state = 2;if (Dead()) *state = 2; break;break; case 2: // Deadcase 2: // Dead SlowlyRot();SlowlyRot(); break;break; }}}}

Page 36: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

36

Coding an FSM – Code Example 2Coding an FSM – Code Example 2void RunLogic(FSM *fsm)void RunLogic(FSM *fsm){{ // Do action based on the state and determine next input// Do action based on the state and determine next input input = 0;input = 0; switch(fsm->GetStateID())switch(fsm->GetStateID()) {{ case 0: // Wandercase 0: // Wander Wander();Wander(); if (SeeEnemy()) input = SEE_ENEMY;if (SeeEnemy()) input = SEE_ENEMY; if (Dead()) input = DEAD;if (Dead()) input = DEAD; break;break; case 1: // Attackcase 1: // Attack Attack();Attack(); input = WANDER;input = WANDER; if (Dead()) input = DEAD;if (Dead()) input = DEAD; break;break; case 2: // Deadcase 2: // Dead SlowlyRot();SlowlyRot(); break;break; }} // DO state transition based on computed input// DO state transition based on computed input fsm->StateTransition(input);fsm->StateTransition(input);}}

Page 37: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

37

Mealy & Moore MachinesMealy & Moore Machines Mealy machineMealy machine

A Mealy machine is an FSM whose actions are performed on A Mealy machine is an FSM whose actions are performed on transitionstransitions

Moore machineMoore machine A Moore machine’s actions reside in statesA Moore machine’s actions reside in states More intuitive for game developersMore intuitive for game developers

Page 38: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

38

FSM Language Use MacrosFSM Language Use Macros Coding a state machine directly causes lack of Coding a state machine directly causes lack of

structurestructure Going complex when FSM at their largestGoing complex when FSM at their largest

Use macrosUse macros Beneficial propertiesBeneficial properties

StructureStructure ReadabilityReadability DebuggingDebugging

SimplicitySimplicity

Page 39: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

39

FSM Language Use Macros – An ExampleFSM Language Use Macros – An Example#define BeginStateMachine …#define BeginStateMachine …#define State(a) …#define State(a) ………bool MyStateMachine::States(StateMachineEvent event,bool MyStateMachine::States(StateMachineEvent event, int state)int state){{ BeginStateMachineBeginStateMachine State(0)State(0) OnUpdateOnUpdate Wander();Wander(); if (SeeEnemy()) SetState(1);if (SeeEnemy()) SetState(1); if (Dead()) SetState(2);if (Dead()) SetState(2); State(1)State(1) OnUpdateOnUpdate Attack();Attack(); SetState(0);SetState(0); if (Dead()) SetState(2);if (Dead()) SetState(2); State(2);State(2); OnUpdateOnUpdate RotSlowly();RotSlowly(); EndStateMachineEndStateMachine}}

Page 40: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

40

Data-Driven FSMData-Driven FSM Scripting languageScripting language

Text-based script fileText-based script file Transformed intoTransformed into

C++C++ Integrated into source codeIntegrated into source code

BytecodeBytecode Interpreted by the gameInterpreted by the game

AuthoringAuthoring CompilerCompiler AI editing toolAI editing tool

GameGame FSM script engineFSM script engine FSM interfaceFSM interface

Page 41: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

41

Data-Driven FSM DiagramData-Driven FSM Diagram

Authoring

FSMs bytecodeCompiler

AI EditingTool

Condition &Action

Vocabulary

Games

FSM ScriptEngine

FSM Interface

Condition &Action Code

Game Engine

Artist,Designers, &Developers

Page 42: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

42

AI Editing Tool for FSMAI Editing Tool for FSM Pure textPure text

Syntax ?Syntax ? Visual graph with textVisual graph with text Used by Designers, Artists, or DevelopersUsed by Designers, Artists, or Developers

Non-programmersNon-programmers Conditions & action vocabularyConditions & action vocabulary

SeeEnemySeeEnemy CloseToEnemyCloseToEnemy AttackAttack ……

Page 43: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

43

FSM InterfaceFSM Interface Facilitating the binding between vocabulary and game worFacilitating the binding between vocabulary and game wor

ldld Glue layer that implements the condition & action vocabulGlue layer that implements the condition & action vocabul

ary in the game worldary in the game world Native conditionsNative conditions

SeeEnemy(), CloseToEnemy()SeeEnemy(), CloseToEnemy() Action libraryAction library

Attack(…)Attack(…)

Page 44: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

44

FSM Script Language BenefitsFSM Script Language Benefits Accelerated productivityAccelerated productivity Contributions from artists & designersContributions from artists & designers Ease of useEase of use ExtensibilityExtensibility

Page 45: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

45

Processing Models for FSMsProcessing Models for FSMs Processing the FSMsProcessing the FSMs

Evaluate the transition conditions for current stateEvaluate the transition conditions for current state Perform any associated actionsPerform any associated actions

When and how ?When and how ? Depend on the exact need of gamesDepend on the exact need of games

Three common FSM processing modelsThree common FSM processing models PollingPolling Event-drivenEvent-driven MultithreadMultithread

Page 46: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

46

Polling Processing ModelPolling Processing Model Processing each FSM at regular time intervalsProcessing each FSM at regular time intervals

Tied to game frame rateTied to game frame rate Or some desired FSM update frequencyOr some desired FSM update frequency Limit one state transition in a cycleLimit one state transition in a cycle Give a FSM a time-boundGive a FSM a time-bound

ProsPros StraightforwardStraightforward Easy to implementEasy to implement Easy to debugEasy to debug

ConsCons InefficiencyInefficiency

Some transition are not necessary to check every frameSome transition are not necessary to check every frame Careful design to your FSMCareful design to your FSM

Page 47: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

47

Event-driven Processing ModelEvent-driven Processing Model Designed to prevent from wasted FSM processingDesigned to prevent from wasted FSM processing An FSM is only processed when it’s relevantAn FSM is only processed when it’s relevant ImplementationImplementation

A Publish-subscribe messaging system (Observer pattern)A Publish-subscribe messaging system (Observer pattern) Allows the engine to send events to individual FSMsAllows the engine to send events to individual FSMs An FSM subscribes only to the events that have the potential to chaAn FSM subscribes only to the events that have the potential to cha

nge the current statenge the current state When an event is generated, the FSMs subscribed to that events are When an event is generated, the FSMs subscribed to that events are

all processedall processed ““As-needed” approachAs-needed” approach

Should be much more efficient than polling ?Should be much more efficient than polling ? Tricky balance for fine-grained or coarse-grained eventsTricky balance for fine-grained or coarse-grained events

Page 48: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

48

Multithread Processing ModelMultithread Processing Model Both polling & event-driven are serially processedBoth polling & event-driven are serially processed Multithread processing modelMultithread processing model

Each FSM is assigned to its own thread for processingEach FSM is assigned to its own thread for processing Game engine is running in another separate threadGame engine is running in another separate thread All FSM processing is effectively concurrent and continuousAll FSM processing is effectively concurrent and continuous Communication between threads must be thread-safeCommunication between threads must be thread-safe

Using standard locking & synchronization mechanismsUsing standard locking & synchronization mechanisms ProsPros

FSM as an autonomous agent who can constantly and FSM as an autonomous agent who can constantly and independently examine and react to his environmentindependently examine and react to his environment

ConsCons Overhead when many simultaneous characters activeOverhead when many simultaneous characters active Multithreaded programming is difficultMultithreaded programming is difficult

Page 49: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

49

Interfacing with Game Engine (1/2)Interfacing with Game Engine (1/2) FSMs encapsulate complex behavior logicFSMs encapsulate complex behavior logic

Decision, condition, action, …Decision, condition, action, … Game engine does correspondingGame engine does corresponding

Character animation, movements, sounds, …Character animation, movements, sounds, … The interface :The interface :

Code each action as a functionCode each action as a function Need recompile if any code is changedNeed recompile if any code is changed ie., FleeWolf()ie., FleeWolf()

CallbacksCallbacks Function pointersFunction pointers ie., actionFunction[fleeWolf]()ie., actionFunction[fleeWolf]()

Container methodContainer method actionFunctions->FleeWolf();actionFunctions->FleeWolf(); DLLDLL

Page 50: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

50

Interfacing with Game Engine (2/2)Interfacing with Game Engine (2/2) Take TheFly3D as example:Take TheFly3D as example:

class AArmyUnit : public FnCharacter{ … void DoAttack(…);}

AArmyUnit *army;

army->Object(…);army->MoveForward(dist, …);…army->DoAttack(…);

Page 51: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

51

FSM Efficiency & OptimizationFSM Efficiency & Optimization Two categories :Two categories :

Time spentTime spent Computational costComputational cost

Scheduled processingScheduled processing Priority for each FSMPriority for each FSM Different update frequencyDifferent update frequency

Load balancing schemeLoad balancing scheme Collecting statistics of past performance & extrapolating Collecting statistics of past performance & extrapolating

Time-bound for each FSMTime-bound for each FSM Do careful designDo careful design

At the design levelAt the design level Level-of-detail FSMsLevel-of-detail FSMs

Page 52: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

52

Level-Of-Detail FSMs Level-Of-Detail FSMs Simplify the FSM when the player won’t notice the Simplify the FSM when the player won’t notice the

differencesdifferences Outside the player’s perceptual rangeOutside the player’s perceptual range Just like the LOD technique used in 3D game engine Just like the LOD technique used in 3D game engine

Three design keys :Three design keys : Decide how many LOD levelsDecide how many LOD levels

How much development time available ?How much development time available ? The approximation extentThe approximation extent

LOD selection policyLOD selection policy The distance between the NPC with the player ?The distance between the NPC with the player ? If the NPC can “see” the player ?If the NPC can “see” the player ? Be careful the problem of “visible discontinuous behavior”Be careful the problem of “visible discontinuous behavior”

What kind of approximationsWhat kind of approximations Cheaper and less accurate solution Cheaper and less accurate solution

Page 53: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

53

Extending the Basic FSM Extending the Basic FSM Extending statesExtending states

Begin-end blockBegin-end block

BeginDoAction(); DoActions();EndDoAction();

Stacks & FSMsStacks & FSMs Stack-based “history” of FSMsStack-based “history” of FSMs

““Remember” the sequence of states passed throughRemember” the sequence of states passed through ““Retrace” its steps at willRetrace” its steps at will

Hierarchical FSMHierarchical FSM Polymorphic FSMsPolymorphic FSMs Fuzzy State MachineFuzzy State Machine

Combined with fuzzy logicCombined with fuzzy logic

Page 54: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

54

A Hierarchical FSM Example A Hierarchical FSM Example

GatherTreasure

Flee

Fight

Monster in sight

No monster

Monster dead Corn

ered

FindTreasure

Go ToTreasure

TakeTreasure

FindTreasureGather

Treasure

Live

Active FSM

Stack

Page 55: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

55

Another Hierarchical FSM Example Another Hierarchical FSM Example

Patrol

Investigate

Attack

Done

Noise

Saw Enemy

Saw Enemy

Done

Go to ALook forIntruders

Go to BLook forIntruders

Patrol

ReportNoise

Go OverTo Noise

Look forIntruders

FalseAlarm!

Investigate

noisenoise

Page 56: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

56

More Topics in Game AI More Topics in Game AI ScriptingScripting Goal-based planningGoal-based planning Rule-based inference engineRule-based inference engine Neural networkNeural network ReferencesReferences

Game GemsGame Gems AI Game Programming WisdomAI Game Programming Wisdom

Page 57: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

57

ShadowsShadows

(brief version)(brief version)

Page 58: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

58

ContentsContents

Fake shadowFake shadow Traditional projected shadowTraditional projected shadow

Two-pass shadow renderingTwo-pass shadow rendering Projective texture mappingProjective texture mapping Shadow mapping (shader)Shadow mapping (shader) Shadow volumeShadow volume

Page 59: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

59

ShadowsShadows

light source

occluder

receivershadow

penumbra

umbra

Page 60: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

60

Traditional Projected ShadowTraditional Projected Shadow

By Jim BlinnBy Jim Blinn Me and My (Fake) ShadowMe and My (Fake) Shadow IEEE Computer Graphics and Applications, January, 1988IEEE Computer Graphics and Applications, January, 1988

Project the geometry on the “ground” plane.Project the geometry on the “ground” plane. Scale the height to zero.Scale the height to zero. Make the shadow material to black.Make the shadow material to black.

Polygon solutionPolygon solution ““Flat” shadow on the ground.Flat” shadow on the ground.

Page 61: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

61

Two-pass Shadow RenderingTwo-pass Shadow Rendering First pass :First pass :

Treat the light source as the camera.Treat the light source as the camera. Assign the material color of the object (to be shadowed)Assign the material color of the object (to be shadowed)

1 – shadow_color1 – shadow_color ““Render” the object on a texture (shadow map).Render” the object on a texture (shadow map).

Second pass :Second pass : Texture map the shadow map on the terrain withTexture map the shadow map on the terrain with

Source_blend = zeroSource_blend = zero Destination_blend = 1 – source_colorDestination_blend = 1 – source_color

ProsPros Easy to implementEasy to implement

ConsCons Texture resolutionTexture resolution Z fightingZ fighting AliasingAliasing

Page 62: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

62

Game Control SystemGame Control System

Page 63: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

63

Introduction (1/2)Introduction (1/2) Game control is the interface between the game Game control is the interface between the game

and the user.and the user. Game control is not only input device control but Game control is not only input device control but

also camera controlalso camera control Input device controlInput device control

On PCOn PC MouseMouse KeyboardKeyboard GamepadGamepad

On game consoleOn game console GamepadGamepad

0 or 2550 or 255 JoystickJoystick

0 - 2550 - 255

Page 64: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

64

Introduction (2/2)Introduction (2/2) Camera controlCamera control

First-personal viewFirst-personal view Third-personal viewThird-personal view God viewGod view Pre-set camera viewPre-set camera view

Page 65: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

65

Mouse Control (1/3)Mouse Control (1/3)

Mouse is a 2D device.Mouse is a 2D device. 2-axis moving2-axis moving Related movementRelated movement 2 or 3 buttons2 or 3 buttons

Mouse canMouse can MoveMove DragDrag Double-clickDouble-click

BehaviorsBehaviors Hit testHit test SelectionSelection PilotPilot

Position & orientationPosition & orientation

Page 66: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

66

Mouse Control (2/3)Mouse Control (2/3)

Typical game types using mouse controlTypical game types using mouse control Real-time strategy gamesReal-time strategy games Role Playing GameRole Playing Game

Typical game play examples :Typical game play examples : Path finding for playable characterPath finding for playable character Hitting the enemyHitting the enemy Selecting a group of unitsSelecting a group of units Orientating the camera in FPS gamesOrientating the camera in FPS games Menu selectionMenu selection ……

FeaturesFeatures Always coupling with god-view camera controlAlways coupling with god-view camera control

Viewing from the top of game worldViewing from the top of game world

Page 67: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

67

Mouse Control (3/3)Mouse Control (3/3) Easy to hand onEasy to hand on

一鼠到底一鼠到底 Slow actionSlow action

Compared with joystickCompared with joystick Value range from -32727 - 32727Value range from -32727 - 32727

Page 68: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

68

Keyboard Control (1/3)Keyboard Control (1/3)

Standard PC input deviceStandard PC input device Simulating the gamepads usuallySimulating the gamepads usually

Not every PC game player having gamepadNot every PC game player having gamepad Using keyboard as the alternative deviceUsing keyboard as the alternative device

Hotkey systemHotkey system Each key has two states.Each key has two states.

PressedPressed ReleasedReleased

256 keys256 keys BehaviorsBehaviors

Key presses/releasedKey presses/released ASCII codeASCII code

One hotkey can represent a commandOne hotkey can represent a command

Page 69: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

69

Keyboard Control (2/3)Keyboard Control (2/3)

Communication toolCommunication tool Typing messages Typing messages

Typical game types using keyboardTypical game types using keyboard MMORPGMMORPG

Needs chatting with friendsNeeds chatting with friends Real-time strategy gamesReal-time strategy games

Hotkey systemHotkey system First-person shooting gamesFirst-person shooting games Fighting gamesFighting games

Typical game play examples :Typical game play examples : ChattingChatting Character controlsCharacter controls

Move forwardMove forward TurningTurning

Page 70: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

70

Keyboard Control (3/3)Keyboard Control (3/3)

FeaturesFeatures Shortcut for a sequence of actionsShortcut for a sequence of actions

CommandsCommands Menu selectionMenu selection

But a little bit complicated for playersBut a little bit complicated for players 256 keys256 keys

Page 71: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

71

Gamepad Control (1/3)Gamepad Control (1/3) A small “keyboard” designed for game playingA small “keyboard” designed for game playing

Gamepad can map to the hotkey systemGamepad can map to the hotkey system Same behaviorsSame behaviors Less than 20 keysLess than 20 keys

Majors keys :Majors keys :

Page 72: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

72

Gamepad Control (2/3)Gamepad Control (2/3) Recent gamepad capable of two extra digital joysRecent gamepad capable of two extra digital joys

ticksticks For keysFor keys

Value range : 0 or 255Value range : 0 or 255 For joystickFor joystick

Value range : 0 to 255Value range : 0 to 255 Typical game types using gamepadTypical game types using gamepad

Almost all types of games exceptAlmost all types of games except Need typingNeed typing Need large-range selection for game unitsNeed large-range selection for game units

Typical game play examples :Typical game play examples : Character controlsCharacter controls

Move forwardMove forward Turn Turn

Page 73: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

73

Gamepad Control (3/3)Gamepad Control (3/3) Combat system in a fighting gameCombat system in a fighting game

Move forwardMove forward TurnTurn

…… FeaturesFeatures

Designed for game playingDesigned for game playing Look and feelLook and feel

Easy to hand-onEasy to hand-on If you not to challenge the players’ usual If you not to challenge the players’ usual

practicepractice

Page 74: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

74

Camera ControlCamera Control

TypesTypes First-personal viewFirst-personal view Third-personal view but following the playable Third-personal view but following the playable

charactercharacter God viewGod view

FixedFixed Following the playable characterFollowing the playable character

Fixed viewFixed view Pre-rendered backgroundPre-rendered background

Pre-set viewPre-set view ……

Very sensitive to game play design & game Very sensitive to game play design & game controlcontrol

Camera control is not an independent systemCamera control is not an independent system

Page 75: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

75

God-view Camera ExampleGod-view Camera Example

Age of Empire 3

Page 76: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

76

Game Control Case Study – Third-personal Game Control Case Study – Third-personal View (1/6)View (1/6)

Use arrow keys on keyboard or gamepadUse arrow keys on keyboard or gamepad

Basic key assignments :Basic key assignments : Up key to move the playable character forwardUp key to move the playable character forward Down key to turn character facing to the camera Down key to turn character facing to the camera

and move forwardand move forward Left & right keys to turn the character to left or rightLeft & right keys to turn the character to left or right

Page 77: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

77

Game Control Case Study – Third-personal Game Control Case Study – Third-personal View (2/6)View (2/6)

The camera following the character to moveThe camera following the character to move And keeping a range of distance, a reasonable And keeping a range of distance, a reasonable

height and look-down angle with the character.height and look-down angle with the character.

Distance

PC

Camera

Height

Page 78: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

78

Game Control Case Study – Third-personal Game Control Case Study – Third-personal View (3/6)View (3/6)

Detailed key assignments :Detailed key assignments : Up keyUp key

Turn the character facing back to the cameraTurn the character facing back to the camera Move the character forwardMove the character forward If the distance between the character and the camera is If the distance between the character and the camera is

larger a pre-set range, move the camera forward to keep larger a pre-set range, move the camera forward to keep the distance.the distance.

At the same time, the height to the ground will be At the same time, the height to the ground will be changed to synchronize with the character.changed to synchronize with the character.

Down keyDown key Turn the character facing to the cameraTurn the character facing to the camera Move the character forwardMove the character forward The camera will move backward to keep a distance with The camera will move backward to keep a distance with

the character.the character. The height to the ground will be changed to synchronize The height to the ground will be changed to synchronize

with the character.with the character.

Page 79: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

79

Game Control Case Study – Third-personal Game Control Case Study – Third-personal View (4/6)View (4/6)

If the camera is blocked by obstacle to move backward, raise If the camera is blocked by obstacle to move backward, raise the height of the camera but keep the eyes on the character.the height of the camera but keep the eyes on the character.

PCCamera

Page 80: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

80

Game Control Case Study – Third-personal Game Control Case Study – Third-personal View (5/6)View (5/6)

Right keyRight key Turn the character facing to the right of the camera.Turn the character facing to the right of the camera. Take the camera’s position as a circle center and the distance Take the camera’s position as a circle center and the distance

between the camera and the character as the radius.between the camera and the character as the radius. Set the circle as the movement orbit.Set the circle as the movement orbit. Let the character move on the orbit.Let the character move on the orbit. When the character moving, turn the camera to right to keep When the character moving, turn the camera to right to keep

eyes on the character.eyes on the character.

Page 81: 1 Game System. 2 Control system Control system User input User input Mouse or keyboard Mouse or keyboard Keyboard layout Keyboard layout Camera control

81

Game Control Case Study – Third-personal Game Control Case Study – Third-personal View (6/6)View (6/6)

When the character hitting the obstacle, let the character keeWhen the character hitting the obstacle, let the character keep on turning and moving, use the same approach in “Down kp on turning and moving, use the same approach in “Down key” step to raise the camera.ey” step to raise the camera.

Left keyLeft key As same as “Right key” step except the left direction.As same as “Right key” step except the left direction.

Reference game examples:Reference game examples: Sprinter cell 3Sprinter cell 3 PSOPSO Prince of Persia(Prince of Persia( 波斯王子波斯王子 )) The Legend of ZeldaThe Legend of Zelda (( 薩爾達傳說薩爾達傳說 )) ……

Demo : DCI students’ work : iRobotDemo : DCI students’ work : iRobot