Once you have done this, you can load your model files from theTo orient the aliens according to their direction on the Y axis, the YDirection method is required in the game class: float
Trang 1node Once you have done this, you can load your model files from the
To orient the aliens according to their direction on the Y axis, the YDirection()
method is required in the game class:
float YDirection(Vector3 view, Vector3 position){
Vector3 forward = view - position;
return (float)Math.Atan2((double)forward.X, (double)forward.Z);
}
To transform the alien models when drawing and updating them, add these ods to the game class:
meth-Matrix Scale(){
const float SCALAR = 0.5f;
return Matrix.CreateScale(SCALAR, SCALAR, SCALAR);
}
Matrix TransformAliens(bool host, bool controlledLocally,
Vector3 position, Vector3 view){
const float YOFFSET = 0.3f;
const float Z_OFFSET = 2.0f;
translateOffset = Matrix.CreateTranslation(0.0f, YOFFSET, Z_OFFSET); translation = Matrix.CreateTranslation(
new Vector3(position.X, 0.0f, position.Z));
// 3: build cumulative world matrix using I.S.R.O.T sequence
// identity, scale, rotate, orbit(translate & rotate), translate
return yRotation * translateOffset * rotateOffset * translation;
}
Trang 2To update the local position and view data each frame, add
Update-GameNetwork() to your game class Vector3.Transform() updates the view
and position coordinates according to the changes of the locally controlled aliens.
Once the local view and position data is calculated, these values are passed to the
net-work class for distribution across the netnet-work:
public void UpdateGameNetwork(){
if (network.session == null){ // update menu if no game yet
UpdateGameStart();
}
else{ // otherwise update network
// with latest position and view data Matrix world = Scale() * TransformAliens(host, LOCAL_CONTROL,
cam.position, cam.view);
Vector3 position = Vector3.Zero;
Vector3 view = Vector3.Zero;
view.Z =-VIEWOFFSET_Z;
Vector3.Transform(ref position, ref world, out position);
Vector3.Transform(ref view, ref world, out view);
network.UpdateNetwork(cam.position, cam.view);
}
}
To update your game, call UpdateGameNetwork() at the end of the Update()
method in the game class:
UpdateGameNetwork();
This generic DrawModels() routine will draw your models:
void DrawModels(Model model, Matrix[] matrix, Matrix world){
foreach (ModelMesh mesh in model.Meshes){
foreach (BasicEffect effect in mesh.Effects){
// 4: set shader variables
effect.World = matrix[mesh.ParentBone.Index] * world;
Trang 3Add DrawAliens() to your game class to render your alien models This method is called when the game is active, and it switches views depending on whether the game is being run on the network host or from a network client:
public void DrawAliens(){
Matrix world;
if (network.session.RemoteGamers.Count > 0){
if (host){ // host world = Scale() * TransformAliens(host, LOCAL_CONTROL,
cam.position, cam.view);
DrawModels(alien0Model, alien0Matrix, world);
world = Scale() * TransformAliens(host, !LOCAL_CONTROL,
network.remotePosition, network.remoteView);
DrawModels(alien1Model, alien1Matrix, world);
} else{ // client world = Scale() * TransformAliens(host, !LOCAL_CONTROL,
network.remotePosition, network.remoteView);
DrawModels(alien0Model, alien0Matrix, world);
world = Scale() * TransformAliens(host, LOCAL_CONTROL,
cam.position, cam.view);
DrawModels(alien1Model, alien1Matrix, world);
} }
if (network.session == null){
DrawMenu();
}
Trang 4When you have finished adding this code, you will then be able to run your game
on two machines Each player will be able to control one of the aliens in the game.
This next example starts with the code from the peer-to-peer solution and converts it
to a client/server-based network The main difference with this example is that the
clients send their data directly to the server rather than to all of the other clients The
server then distributes the entire collection of data to the clients.
To start, an extra class is needed in Network.cs to store the alien position, view,
and identification:
public class Alien{
public Vector3 position;
public Vector3 view;
public int alienID;
The server collects all of the remote client and local data and stores it in a list, so a
list declaration is needed in the XNANetwork class:
public List<Alien> alienData = new List<Alien>();
A new version of GamerJoinEvent() stores the instance of each new gamer
lo-cally as each new player joins the game The structure, e.Gamer.Tag , stores each
new gamer’s identity e.Gamer.Tag will be referenced later during reads and
writes to identify the gamer data Each new gamer is added to the XNANetwork list.
To add this code, replace GamerJoinEvent() with this new version:
void GamerJoinEvent(object sender, GamerJoinedEventArgs e){
int gamerIndex = session.AllGamers.IndexOf(e.Gamer);
Trang 5e.Gamer.Tag = new Alien(gamerIndex);
Alien tempAlien = new Alien();
void ClientWrite(LocalNetworkGamer gamer,
Vector3 localPosition, Vector3 localView){
Alien localAlien = gamer.Tag as Alien;
// find local players in list and write their data to the network
for (int i = 0; i < alienData.Count; i++){
if (alienData[i].alienID == localAlien.alienID && gamer.IsLocal){ Alien tempAlien = new Alien();
// Send our input data to the server.
differ-ServerWrite() must be placed inside the XNANetwork class to perform this data transfer:
void ServerWrite(Vector3 localPosition, Vector3 localView){
// iterate through all local and remote players
Trang 6foreach (NetworkGamer gamer in session.AllGamers){
Alien alien = gamer.Tag as Alien;
for (int i = 0; i < alienData.Count; i++){
// update local data only
if (gamer.IsLocal && alienData[i].alienID == alien.alienID){
Alien tempAlien = new Alien();
// send all data to everyone on session
LocalNetworkGamer server = (LocalNetworkGamer)session.Host;
server.SendData(packetWriter, SendDataOptions.InOrder);
}
Next, add ServerRead() to the XNANetwork class to read all remote data and
store it locally in the list:
void ServerRead(LocalNetworkGamer gamer){
// read all incoming packets
while (gamer.IsDataAvailable){
NetworkGamer sender;
// read single packet
gamer.ReceiveData(packetReader, out sender);
// store remote data only
Trang 7int gamerId = packetReader.ReadInt32();
Vector3 pos = packetReader.ReadVector3();
Vector3 view = packetReader.ReadVector3();
// get current gamer id NetworkGamer remoteGamer = session.FindGamerById(gamer.Id);
// don't update if gamer left game
if (remoteGamer == null) return;
Alien alien = remoteGamer.Tag as Alien;
// search all aliens and find match with remote ones for (int i = 0; i < alienData.Count; i++){
if (alienData[i].alienID == gamerId) { Alien tempAlien = new Alien();
tempAlien.alienID = gamerId;
tempAlien.position = pos;
Trang 8A revised UpdateNetwork() method must replace the existing one to handle the
client/server processing If the session is in progress, this method triggers read and
write routines on the client and the server:
public void UpdateNetwork(Vector3 localPosition, Vector3 localView){
// ensure session has not ended
if (session == null)
return;
// read incoming network packets.
foreach (LocalNetworkGamer gamer in session.LocalGamers)
foreach (LocalNetworkGamer gamer in session.LocalGamers)
ClientWrite(gamer, localPosition, localView);
// write from server
When you run your code now, your client/server network will allow you to
con-trol two different aliens, each on its own machine With either the peer-to-peer
framework or the client/server framework, you have a performance-friendly way to
exchange data between machines in your game as long as you design the game for
ef-ficient data transfer.
Trang 9C HAPTER 29 REVIEW EXERCISES
To get the most from this chapter, try out these chapter review exercises.
1. If you have not already done so, follow the step-by-step examples shown
in this chapter to implement the peer-to-peer network sample and the client/server network sample.
2. Modify the code to allow more than one player locally You will need to use a split-screen environment to do this.
Trang 10A
abs function, 76
Acceleration of projectiles, 308
Accept New Key option, 14
Accuracy settings for skyboxes, 147
Add/Detach Sounds option, 470–471
Add Existing Item dialog
Add Reference dialog, 446
Add Watch option, 18
Add Xbox 360 Name and Connection
airplane direction, 115–118dot products, 244Animated textures, 174–178Animation, 92
asteroids, 43–45
characters See Character
movementkeyframe, 344–351matrices, 93–95
Quake II See Quake II model
Right Hand Rule, 92–93spaceships, 473–477
sprites See Sprites
windmill, 217–219animations enum, 446, 451–452Application flow, 22
Apply3D method, 464, 483Apply3DAudio method, 483–484Arcing Projectile algorithm, 306Arcing projectiles
example, 319–320overview, 306–309Arctangent function, 104–107Assemblies, 23
Assembly language, 73Asteroid example, 42asteroid animation, 43–45collision detection, 48–52completing, 52–53images for, 42–43rocket ship control, 45–48Atan function, 105–106, 115–116Atan2 function, 107, 116, 140Atmosphere setting, 147AttachedSounds property, 471Attenuation of audio, 471–472Audio, 460
adding, 477–482
attenuation, 471–472
XACT See XACT (Cross
Platform Audio Creation Tool)Zune, 487–489
Audio3DCue class, 483AudioEmitter class, 463, 482AudioEngine class, 461–462AudioListener class, 463, 482audioProject.xap file, 473, 477–478Auditioning Utility, 468
Authoring tool, 461, 464–468AutoComplete format, 12AvailableNetworkSessionCollectionclass, 508
B
backwall.jpg file, 135Ballistics
arcing projectiles, 306–309arcing projectiles example,319–320
linear projectiles, 306–307linear projectiles example,309–319
Bandwidth for networks, 506–507Bank setting for images, 148base.fbx file, 216
Base for windmillcreating, 205–206exporting, 213Base Surface tab, 422Basic Sculpting tool, 421BasicEffect class, 70car object, 226default lighting, 356–357directional lighting, 357–362Quake II model, 448–449shaders, 86–89
windmill, 215–216
527
Trang 11Bold font style, 194
Bold Italic font style, 194
Bui Tuong Phong, 362
Build Action property, 446
car.tga file, 221Cartesian coordinates3D graphics, 56Right Hand Rule, 92–93CarYDirection method, 224Categories of sound banks, 462Cell method, 249–250CellHeight method, 414CellNormal method, 431CellWeight method, 429–430CF-18 Hornet fighter jet example,345–351
cf18.x file, 349cf18Color.jpg file, 349ChangePosition method, 83, 85ChangeView method
cameras, 281–283car object, 222–224mouse, 387–388spaceships, 476split-screen environment,497–498
Character movement, 104, 109–110airplane direction angle, 115–118direction, 104–109
flying airplane with spinningpropeller, 114–115stationary airplane with spinningpropeller, 110–114
CheckCollisions method, 51–52clamp function, 76
Class-level variables, 84Clear method, 341Client/server networksexample, 521–525overview, 506ClientRead method, 524–525ClientWrite method, 522Clip planes, 270Closing games, 26Cloud Shading setting, 147Clouds Cast Shadows option, 424Code files
adding and removing, 12managing, 8–9Collision detection, 37, 286asteroid example, 48–52bounding box implementation,302–304
bounding spheresimplementation, 299–302
bounding spheres initializationand drawing, 290–299BoundingBox, 288–289BoundingSphere, 288containment types, 287early warning systems, 287per pixel, 39–40
rectangle, 37transformation matrices, 37–39Collision method, 299
Colorlandscape, 422shaders, 71–72, 75, 81–86textures, 48–49, 128, 140–141Combining images
multitexturing, 178–189
sprites See Sprites
CommitChanges method, 78, 87,
126, 133Compatibility of shaders, 73Compiling Xbox 360 Game projects,12–13
Conjugate quaternions, 279Connect to Computer screen, 14–15Connection Key dialog, 14Connections to PC and Xbox 360, 3–4ContainmentType type, 287
Contains containment type, 287Contains method
BoundingBox, 289BoundingSphere, 288Content Importer property, 446Content node, 34
Content pipeline and processors, 402ContentImporter, 403ContentTypeReader, 404example, 404–417images, 34overview, 33Content Pipeline Extensionprojects, 405
ContentImporter class, 403, 408ContentManager classdescription, 24models, 312particles, 334textures, 121ContentProcessor class, 402, 407ContentReader class, 409ContentTypeReader class, 404ContentTypeWriter class,403–404, 408Continue option, 18Control points for curves, 344Controllers, 379–380, 390–391bumpers, 392–393DPad, 393game pad buttons, 391–392game pad states, 380–381pressed and released states, 381
Trang 12Cross Platform Audio Creation Tool.
See XACT (Cross Platform Audio
to Zune, 4–5Depth of animated sprites layers, 36Detail setting for skyboxes, 147Developer basics, 8
code project management, 8–9debugging, 15–19
deploying, 14–15editing, 12–13Windows Game projects, 9–10Xbox 360 Game projects, 10–11Zune game projects, 11Development environment setup, 2–5DeviceReset events, 25
Diffuse light, 355DiffuseColor property, 357Direction, 104
airplane angle, 115–118cameras, 269
scaling in, 108–109speed for, 105–107trigonometry for, 104–105vectors for, 107–108Direction property, 357Directional lights, 354, 356–362, 449DirectionMatrix method, 117DirectX, 212
Disjoint containment type, 287Display
bumpers, 392–393fonts, 193–198frames-per-second count,198–199
game pad button state, 392heads-up, 169–173input device states, 385–386mouse states, 388
thumbsticks, 394–395triggers, 395DisplayCurrentHeight, 416–417Dispose method, 479
Dot method, 76, 244Dot products of vectors, 243–245Down attribute in DPad, 393Downloading examples, 5–6DPad control, 41, 380–382, 393Draw method
animated sprites, 35–36animated texture, 178fire, 339–341fonts, 197–198
images, 43meshes, 216, 218–219overriding, 28purpose, 26shaders, 82split-screen environment,499–500
sprites, 167–168, 172–173textures, 137–138triggering, 25DrawAirplaneBody method, 112,114–117
DrawAliens method, 502–503,520–521
DrawAnimatedHud method, 172–173DrawAnimatedTexture method, 177DrawCar method, 226
DrawCF18 method, 350DrawCursor method, 389–390DrawEarth method, 99–101DrawFonts method, 197–198bumpers, 392–393controllers, 391game pad button state, 392input device states, 385–386matrix display, 251mouse states, 388thumbsticks, 394–395triggers, 395vector calculations in, 235Zune, 397
DrawGround methodgrass, 134ground, 88–89skyboxes, 149split-screen environment,497–498
DrawIndexedGrid method, 162–163multitexturing, 184–186point lights, 372, 375terrain, 426DrawIndexedPrimitives method, 159,162–163
Drawingbounding spheres, 290–299fonts, 197–198
games, 25–26with shaders, 78, 80–81spaceships, 473–477windmill, 215–219DrawLauncher method, 314–315DrawMatrix method, 250–251DrawMD2Model method,450–452, 456DrawMenu method, 515DrawMessage method, 515–516DrawModel method
car object, 226spaceships, 435, 476DrawModels method, 519
Trang 13Existing Game Studio projects, 8–9
Export Heightfield dialog, 422
Exportingheight maps, 422–423
to md2 format, 445–446windmill, 213
ExtractBoundingSphere method,296–297
Eyebrows, Martian, 60, 66–67Eyes, Martian, 59–60, 63–65, 67–68
F
Face, Martian, 59–60eyebrows, 66–67eyes, 59–60, 63–65, 67–68mouth, 60–63
nose, 60, 65–66Fade with point sprites, 327Fan, windmill, 206–213fan.fbx file, 213, 216Far clip planes, 270.fbx format, 202–203, 207, 212–213Field of view, 270
Fighter jet example, 345–351Filters for textures, 123, 128Find method, 508
Finite audio loops, 467–468Fire example, 331–341Fire method, 479–480fire.wav file, 466, 477, 487Firing sound, 466float data type for shaders, 75Flow control for shaders, 75Flowing river effect, 179–187Fonts
bumpers, 392–393drawing, 197–198frames-per-second countexample, 198–199game pad button state, 392height, 416–417
input device states, 385–386loading, 193–196
monospace, 249mouse states, 388peer-to-peer networks, 515thumbsticks, 394–395triggers, 395
in visible window portion, 196Zune, 397
Force with projectiles, 308Forward vector
direction calculations, 107–108spaceship, 433–434
textures, 139Fractions, scaling vectors by, 237Frame swapping, 166
Frames-per-second count display,198–199
Game controllers See Controllers
Game pad buttons, 391–392Game stats
fonts for, 193–198frames-per-second count,198–199
Game Studio projects, 8Game windows, 22closing, 26drawing and updating, 25–26example, 26–28
game foundation, 22–25Game1 class, 27–28Game1.cs fileaudio, 477cameras, 272color shaders, 83fire example, 336input events, 383MD2 class, 448namespaces, 23new projects, 12, 27particles, 336projectiles, 312vertices, 97GamePadState classinput, 494, 497Quake II animation, 453states, 41, 380–381, 390GamerEnded event, 508GamerJoined event, 508–509GamerJoinEvent method, 509, 512,521–522
GamerLeft event, 508GamerServices class, 507, 514GamerServicesComponent class,
507, 514GameStarted event, 508Generate Connection Key option, 14generateNormals method, 407generatePositions method, 406–407GetAccelerationVolume method,480–481
GetCue method, 463–464, 479, 482GetPositionOnCurve method, 348GetPositionOnLine method, 348GetRuntimeReader method, 403,408–409
GetRuntimeType method, 403, 408GetState method
controllers, 381, 390GamePad, 41KeyboardState, 40, 379, 384