Upload
arthur-chad-short
View
280
Download
2
Tags:
Embed Size (px)
Citation preview
1
Game SystemGame System
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)
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)
4
5
Game AIGame AISteering BehaviorSteering Behavior
6
Action selectionAction selection SteeringSteering LocomotionLocomotion
Motion BehaviorMotion Behavior
A Hierarchy of Motion Behavior
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
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
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
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)
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)
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
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
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
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”
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
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
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
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
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
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
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
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
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
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
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
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
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
29
Game AIGame AIFinite State MachineFinite State Machine
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)
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)
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
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
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
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; }}}}
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);}}
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
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
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}}
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
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
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 ……
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(…)
44
FSM Script Language BenefitsFSM Script Language Benefits Accelerated productivityAccelerated productivity Contributions from artists & designersContributions from artists & designers Ease of useEase of use ExtensibilityExtensibility
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
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
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
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
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
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(…);
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
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
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
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
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
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
57
ShadowsShadows
(brief version)(brief version)
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
59
ShadowsShadows
light source
occluder
receivershadow
penumbra
umbra
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.
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
62
Game Control SystemGame Control System
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
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
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
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
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
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
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
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
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 :
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
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
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
75
God-view Camera ExampleGod-view Camera Example
Age of Empire 3
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
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
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.
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
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.
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