Admin đã trở lại và lợi hại gấp đôi :D
Sun May 18, 2014 1:05 pm by admin_huyetsat
Sorry mọi người vì mình vắng mặt quá lâu, mình là HuyetSat, admin đây.
Hiện tại mình đã chuyển nền tảng phát triển game sang mobile (dùng libgdx framework) và cũng đang dev game và up lên play store, ai dùng đt android thì tải về ủng hộ ad nha:
play.google.com/store/apps/developer?id=Top+Game+Free
[img]…
[ Full reading ]
Hiện tại mình đã chuyển nền tảng phát triển game sang mobile (dùng libgdx framework) và cũng đang dev game và up lên play store, ai dùng đt android thì tải về ủng hộ ad nha:
play.google.com/store/apps/developer?id=Top+Game+Free
[img]…
[ Full reading ]
Comments: 1
Game4V và Event "Viết bài hay, nhận ngay quà tặng"
Mon Feb 20, 2012 11:18 pm by noheart91
Game4V là một trong những cộng đồng game thủ đầu tiên của Việt Nam với lịch sử hơn 5 năm hình thành và phát triển. Sau nhiều biến động, có thể nói hiện nay G4V là một cộng đồng game hoạt động hoàn toàn độc lập, không bị ảnh hưởng bởi tổ chức chuyên nghiệp nào với nền tảng máy chủ được trang bị từ …
[ Full reading ]
[ Full reading ]
Comments: 0
Mình sẽ tạm dừng hoạt động một thời gian
Fri Sep 02, 2011 7:19 am by HuyetSat
Vì lý do cá nhân nên tạm thời mình sẽ ko support xna trên các diễn đàn nữa.
Bạn nào gặp vấn đề về xna cứ mail trực tiếp cho mình.
thanh_vinh648@yahoo.com
Thân
Bạn nào gặp vấn đề về xna cứ mail trực tiếp cho mình.
thanh_vinh648@yahoo.com
Thân
Comments: 0
xin cho minh tham gia voi
Fri Apr 15, 2011 12:35 am by luongthanhbinh3824
Mình giỏi 3ds max có thể cho mình làm designer được không anh HuyetSat
Email: thanh_binh3824@yahoo.com
Phone: 0633703673
Email: thanh_binh3824@yahoo.com
Phone: 0633703673
Comments: 1
Latest topics
» Xin TUT game bắn trứng khủng longby anhkhoa2110 Mon Mar 16, 2015 4:29 pm
» xna getRGB texture image?
by bachdienquan Thu Feb 05, 2015 8:34 am
» Cần giúp đỡ về hiệu ứng hình ảnh khi va chạm
by phiemltv Fri Nov 28, 2014 12:20 pm
» Cho mình hỏi về boundbox
by septimus2810 Mon Jul 21, 2014 10:08 am
» Hỏi về cách di chuyển 1 điểm ở tọa độ này sang tọa độ khác cho trước.
by septimus2810 Mon Jul 21, 2014 10:02 am
» Admin đã trở lại và lợi hại gấp đôi :D
by konamij Fri Jun 27, 2014 2:50 pm
» lỗi An unhandled exception of type 'System.NullReferenceException'
by _VH_HV_ Mon Jun 16, 2014 1:59 pm
» networking cho game xna 2d
by admin_huyetsat Tue May 20, 2014 1:04 pm
» hướng dẫn traning C# chuẩn bị cho xna
by lqchinh Tue Apr 15, 2014 11:31 pm
» HelpGameBom2D
by thaimavn Mon Mar 24, 2014 10:35 am
» Hỏi về cách di chuyển 1 điểm ở tọa độ này sang tọa độ khác cho trước.
by bocapzz Mon Feb 24, 2014 10:45 pm
» Hỏi về cài đặt XNA game studio 4.0
by bocapzz Sat Dec 14, 2013 12:33 am
» Cuộc thi lập trình game thế giới 2013 với cơ hội thăm quan Phần Lan
by viope Tue Oct 29, 2013 4:51 pm
» chơi game làm bởi xna như thế nào?
by thinnhph01957 Sat Sep 14, 2013 3:23 pm
» Với 1 Game cái gì là quan trọng ?
by qhhqnavy Tue Aug 13, 2013 8:09 am
» Load fiel .fbx vào Xna bị mất màu
by qhhqnavy Wed Aug 07, 2013 7:42 pm
» Help me hàm Update và Draw với
by sieuthi Mon Dec 24, 2012 11:56 pm
» Hỏi về load hình chồng nhau trong XNA
by sieuthi Mon Dec 24, 2012 11:49 pm
» nơi ghi danh tham gia Game Development Team
by echdonghop Fri Dec 21, 2012 1:56 pm
» tài liệu cơ bản 5 chương cho xna
by Nelson Quang Thu Nov 22, 2012 12:26 pm
simple 3D game
Trang 1 trong tổng số 1 trang
simple 3D game
Phan 1:
Resource: model : ground.x , nen` cua game
Phan 1: Lop chua cac hang so:
Class cho game chinh':
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
namespace FuelCell
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class FuelCellGame : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
//dat
GameObject ground;
//camera
Camera gameCamera;
public FuelCellGame()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
ground = new GameObject();
gameCamera = new Camera();
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
ground.Model = Content.Load<Model>("Models/ground");
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
//goc xoay camera la 0f
float rotation = 0.0f;
Vector3 position = Vector3.Zero;
//update cho camera
gameCamera.Update(rotation, position, graphics.GraphicsDevice.Viewport.AspectRatio);
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.Black);
DrawTerrain(ground.Model);
base.Draw(gameTime);
}
//code de ve~ model ground
private void DrawTerrain(Model model)
{
foreach (ModelMesh mesh in model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.EnableDefaultLighting();
effect.PreferPerPixelLighting = true;
effect.World = Matrix.Identity;
// Use the matrices provided by the game camera
effect.View = gameCamera.ViewMatrix;
effect.Projection = gameCamera.ProjectionMatrix;
}
mesh.Draw();
}
}
}
}
Phan 2:
Bo sung them class constant:
//ship constants
//van toc player
public const float Velocity = 0.75f;
public const float TurnSpeed = 0.025f;
//Khoang cach xa nhat di chuyen
public const int MaxRange = 98;
//Cac vat can player
class Barrier : GameObject
{
//chuoi ky tu ghi lai kieu vat can
public string BarrierType { get; set; }
public Barrier()
: base()
{
BarrierType = null;
}
//load content
public void LoadContent(ContentManager content, string modelName)
{
Model = content.Load<Model>(modelName);
BarrierType = modelName;
Position = Vector3.Down;
}
//Draw method
public void Draw(Matrix view, Matrix projection)
{
Matrix translateMatrix = Matrix.CreateTranslation(Position);
Matrix worldMatrix = translateMatrix;
foreach (ModelMesh mesh in Model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = worldMatrix;
effect.View = view;
effect.Projection = projection;
effect.EnableDefaultLighting();
effect.PreferPerPixelLighting = true;
}
mesh.Draw();
}
}
}
//cai player control
class FuelCarrier : GameObject
{
public float ForwardDirection { get; set; }
//khoang cach de ...
public int MaxRange { get; set; }
public FuelCarrier()
: base()
{
ForwardDirection = 0.0f;
MaxRange = GameConstants.MaxRange;
}
public void LoadContent(ContentManager content, string modelName)
{
Model = content.Load<Model>(modelName);
}
public void Draw(Matrix view, Matrix projection)
{
Matrix worldMatrix = Matrix.Identity;
Matrix rotationYMatrix = Matrix.CreateRotationY(ForwardDirection);
Matrix translateMatrix = Matrix.CreateTranslation(Position);
worldMatrix = rotationYMatrix * translateMatrix;
foreach (ModelMesh mesh in Model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = worldMatrix;
effect.View = view;
effect.Projection = projection;
effect.EnableDefaultLighting();
effect.PreferPerPixelLighting = true;
}
mesh.Draw();
}
}
}
//class cho camera, ko thay doi
class Camera
{
public Vector3 AvatarHeadOffset { get; set; }
public Vector3 TargetOffset { get; set; }
public Matrix ViewMatrix { get; set; }
public Matrix ProjectionMatrix { get; set; }
public Camera()
{
AvatarHeadOffset = new Vector3(0, 7, -15);
TargetOffset = new Vector3(0, 5, 0);
ViewMatrix = Matrix.Identity;
ProjectionMatrix = Matrix.Identity;
}
public void Update(float avatarYaw, Vector3 position, float aspectRatio)
{
Matrix rotationMatrix = Matrix.CreateRotationY(avatarYaw);
Vector3 transformedheadOffset = Vector3.Transform(AvatarHeadOffset, rotationMatrix);
Vector3 transformedReference = Vector3.Transform(TargetOffset, rotationMatrix);
Vector3 cameraPosition = position + transformedheadOffset;
Vector3 cameraTarget = position + transformedReference;
//Calculate the camera's view and projection matrices based on current values.
ViewMatrix = Matrix.CreateLookAt(cameraPosition, cameraTarget, Vector3.Up);
ProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(GameConstants.ViewAngle),
aspectRatio, GameConstants.NearClip, GameConstants.FarClip);
}
}
}
Source: http://www.mediafire.com/?2qodaznmizm
Resource: model : ground.x , nen` cua game
Phan 1: Lop chua cac hang so:
- Code:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace FuelCell
{
class GameConstants
{
//camera constants
public const float NearClip = 1.0f;
public const float FarClip = 1000.0f;
public const float ViewAngle = 45.0f;
}
}
Trong game co cac object, di chuyen, tuong tac, dc quy dinh boi class sau:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace FuelCell
{
//start class cho object
class GameObject
{
//model nhap vao`
public Model Model { get; set; }
//Vi tri cua object
public Vector3 Position { get; set; }
//co hoat dong hay ko
public bool IsActive { get; set; }
//bounding cho model
public BoundingSphere BoundingSphere { get; set; }
public GameObject()
{
Model = null;
Position = Vector3.Zero;
IsActive = false;
BoundingSphere = new BoundingSphere();
}
}
- Code:
class Camera
{
//vi tri camera
public Vector3 AvatarHeadOffset { get; set; }
//diem target
public Vector3 TargetOffset { get; set; }
public Matrix ViewMatrix { get; set; }
public Matrix ProjectionMatrix { get; set; }
public Camera()
{
AvatarHeadOffset = new Vector3(0, 7, -15);
TargetOffset = new Vector3(0, 5, 0);
ViewMatrix = Matrix.Identity;
ProjectionMatrix = Matrix.Identity;
}
//Update camera (goc xoay, vi tri tinh tien cameraPosition va target, ti le man hinh)
public void Update(float avatarYaw, Vector3 position, float aspectRatio)
{
//camera chi xoay quanh truc Y
Matrix rotationMatrix = Matrix.CreateRotationY(avatarYaw);
//Vector huong den bien doi:
Vector3 transformedheadOffset = Vector3.Transform(AvatarHeadOffset, rotationMatrix);
//bien doi diem target
Vector3 transformedReference = Vector3.Transform(TargetOffset, rotationMatrix);
//cac thanh phan cho viewMatrix
Vector3 cameraPosition = position + transformedheadOffset;
Vector3 cameraTarget = position + transformedReference;
//Calculate the camera's view and projection matrices based on current values.
ViewMatrix = Matrix.CreateLookAt(cameraPosition, cameraTarget, Vector3.Up);
ProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(GameConstants.ViewAngle),
aspectRatio, GameConstants.NearClip, GameConstants.FarClip);
}
}
Class cho game chinh':
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
namespace FuelCell
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class FuelCellGame : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
//dat
GameObject ground;
//camera
Camera gameCamera;
public FuelCellGame()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
ground = new GameObject();
gameCamera = new Camera();
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
ground.Model = Content.Load<Model>("Models/ground");
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
//goc xoay camera la 0f
float rotation = 0.0f;
Vector3 position = Vector3.Zero;
//update cho camera
gameCamera.Update(rotation, position, graphics.GraphicsDevice.Viewport.AspectRatio);
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.Black);
DrawTerrain(ground.Model);
base.Draw(gameTime);
}
//code de ve~ model ground
private void DrawTerrain(Model model)
{
foreach (ModelMesh mesh in model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.EnableDefaultLighting();
effect.PreferPerPixelLighting = true;
effect.World = Matrix.Identity;
// Use the matrices provided by the game camera
effect.View = gameCamera.ViewMatrix;
effect.Projection = gameCamera.ProjectionMatrix;
}
mesh.Draw();
}
}
}
}
Phan 2:
Bo sung them class constant:
//ship constants
//van toc player
public const float Velocity = 0.75f;
public const float TurnSpeed = 0.025f;
//Khoang cach xa nhat di chuyen
public const int MaxRange = 98;
- Code:
Phan GameObject:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace FuelCell
{
class GameObject
{
//cac thanh phan cua model
public Model Model { get; set; }
public Vector3 Position { get; set; }
public BoundingSphere BoundingSphere { get; set; }
//thiet lap
public GameObject()
{
Model = null;
Position = Vector3.Zero;
BoundingSphere = new BoundingSphere();
}
}
//cai an dc
class FuelCell : GameObject
{
public bool Retrieved { get; set; }
public FuelCell()
: base()
{
Retrieved = false;
}
//load model
public void LoadContent(ContentManager content, string modelName)
{
Model = content.Load<Model>(modelName);
Position = Vector3.Down;
}
//Dua object len monitor
public void Draw(Matrix view, Matrix projection)
{
Matrix translateMatrix = Matrix.CreateTranslation(Position);
Matrix worldMatrix = translateMatrix;
//Neu no chua dc an
if (!Retrieved)
{
foreach (ModelMesh mesh in Model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = worldMatrix;
effect.View = view;
effect.Projection = projection;
effect.EnableDefaultLighting();
effect.PreferPerPixelLighting = true;
}
mesh.Draw();
}
}
}
//Cac vat can player
class Barrier : GameObject
{
//chuoi ky tu ghi lai kieu vat can
public string BarrierType { get; set; }
public Barrier()
: base()
{
BarrierType = null;
}
//load content
public void LoadContent(ContentManager content, string modelName)
{
Model = content.Load<Model>(modelName);
BarrierType = modelName;
Position = Vector3.Down;
}
//Draw method
public void Draw(Matrix view, Matrix projection)
{
Matrix translateMatrix = Matrix.CreateTranslation(Position);
Matrix worldMatrix = translateMatrix;
foreach (ModelMesh mesh in Model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = worldMatrix;
effect.View = view;
effect.Projection = projection;
effect.EnableDefaultLighting();
effect.PreferPerPixelLighting = true;
}
mesh.Draw();
}
}
}
//cai player control
class FuelCarrier : GameObject
{
public float ForwardDirection { get; set; }
//khoang cach de ...
public int MaxRange { get; set; }
public FuelCarrier()
: base()
{
ForwardDirection = 0.0f;
MaxRange = GameConstants.MaxRange;
}
public void LoadContent(ContentManager content, string modelName)
{
Model = content.Load<Model>(modelName);
}
public void Draw(Matrix view, Matrix projection)
{
Matrix worldMatrix = Matrix.Identity;
Matrix rotationYMatrix = Matrix.CreateRotationY(ForwardDirection);
Matrix translateMatrix = Matrix.CreateTranslation(Position);
worldMatrix = rotationYMatrix * translateMatrix;
foreach (ModelMesh mesh in Model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = worldMatrix;
effect.View = view;
effect.Projection = projection;
effect.EnableDefaultLighting();
effect.PreferPerPixelLighting = true;
}
mesh.Draw();
}
}
}
//class cho camera, ko thay doi
class Camera
{
public Vector3 AvatarHeadOffset { get; set; }
public Vector3 TargetOffset { get; set; }
public Matrix ViewMatrix { get; set; }
public Matrix ProjectionMatrix { get; set; }
public Camera()
{
AvatarHeadOffset = new Vector3(0, 7, -15);
TargetOffset = new Vector3(0, 5, 0);
ViewMatrix = Matrix.Identity;
ProjectionMatrix = Matrix.Identity;
}
public void Update(float avatarYaw, Vector3 position, float aspectRatio)
{
Matrix rotationMatrix = Matrix.CreateRotationY(avatarYaw);
Vector3 transformedheadOffset = Vector3.Transform(AvatarHeadOffset, rotationMatrix);
Vector3 transformedReference = Vector3.Transform(TargetOffset, rotationMatrix);
Vector3 cameraPosition = position + transformedheadOffset;
Vector3 cameraTarget = position + transformedReference;
//Calculate the camera's view and projection matrices based on current values.
ViewMatrix = Matrix.CreateLookAt(cameraPosition, cameraTarget, Vector3.Up);
ProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(GameConstants.ViewAngle),
aspectRatio, GameConstants.NearClip, GameConstants.FarClip);
}
}
}
- Code:
Game1.cs:
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
namespace FuelCell
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class FuelCellGame : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
//nen`
GameObject ground;
//camera
Camera gameCamera;
//tao so ngau nhien
Random random;
//player
FuelCarrier fuelCarrier;
//nhung cuc fuel
FuelCell[] fuelCells;
//cac vat can
Barrier[] barriers;
public FuelCellGame()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
ground = new GameObject();
gameCamera = new Camera();
//Initialize and place fuel cell
fuelCells = new FuelCell[1];
fuelCells[0] = new FuelCell();
fuelCells[0].LoadContent(Content, "Models/fuelcell");
fuelCells[0].Position = new Vector3(0, 0, 15);
//Initialize and place barriers
barriers = new Barrier[3];
barriers[0] = new Barrier();
barriers[0].LoadContent(Content, "Models/cube10uR");
barriers[0].Position = new Vector3(0, 0, 30);
barriers[1] = new Barrier();
barriers[1].LoadContent(Content, "Models/cylinder10uR");
barriers[1].Position = new Vector3(15, 0, 30);
barriers[2] = new Barrier();
barriers[2].LoadContent(Content, "Models/pyramid10uR");
barriers[2].Position = new Vector3(-15, 0, 30);
//Initialize and place fuel carrier
fuelCarrier = new FuelCarrier();
fuelCarrier.LoadContent(Content, "Models/fuelcarrier");
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
ground.Model = Content.Load<Model>("Models/ground");
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
//camera cua chung ta la fixed, do do' khong co goc xoay, lay mac dinh //la 0f
float rotation = 0.0f;
Vector3 position = Vector3.Zero;
gameCamera.Update(rotation, position, graphics.GraphicsDevice.Viewport.AspectRatio);
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.Black);
//ve nen`
DrawTerrain(ground.Model);
fuelCells[0].Draw(gameCamera.ViewMatrix, gameCamera.ProjectionMatrix);
foreach (Barrier barrier in barriers)
barrier.Draw(gameCamera.ViewMatrix, gameCamera.ProjectionMatrix);
fuelCarrier.Draw(gameCamera.ViewMatrix, gameCamera.ProjectionMatrix);
base.Draw(gameTime);
}
/// <summary>
/// Draws the game terrain, a simple blue grid.
/// </summary>
/// <param name="model">Model representing the game playing field.</param>
private void DrawTerrain(Model model)
{
foreach (ModelMesh mesh in model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.EnableDefaultLighting();
effect.PreferPerPixelLighting = true;
effect.World = Matrix.Identity;
// Use the matrices provided by the game camera
effect.View = gameCamera.ViewMatrix;
effect.Projection = gameCamera.ProjectionMatrix;
}
mesh.Draw();
}
}
}
}
Phan 3:Viet game hoan chinh:
1.Khai bao cac hang so:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace FuelCell
{
class GameConstants
{
//DAnh cho camera
public const float NearClip = 1.0f;
public const float FarClip = 1000.0f;
public const float ViewAngle = 45.0f;
//danh cho player
public const float Velocity = 0.75f;
public const float TurnSpeed = 0.025f;
public const int MaxRange = 98;
//Kick thuoc cua terrain
public const int MaxRangeTerrain = 98;
public const int NumBarriers = 40;
public const int NumFuelCells = 12;
public const int MinDistance = 10;
public const int MaxDistance = 90;
//thoi gian de thu nhat fuel
public static readonly TimeSpan RoundTime = TimeSpan.FromSeconds(30.25);
public const string StrTimeRemaining = "Time Remaining: ";
public const string StrCellsFound = "Fuel Cells Retrieved: ";
public const string StrGameWon = "Game Won !";
public const string StrGameLost = "Game Lost !";
public const string StrPlayAgain = "Press Enter/Start to play again or Esc/Back to quit";
public const string StrInstructions1 = "Retrieve all Fuel Cells before time runs out.";
public const string StrInstructions2 = "Control ship using keyboard (A, D, W, S) or the left thumbstick.";
//Thay doi ti le bounding cua model
public const float FuelCarrierBoundingSphereFactor = .8f;
public const float FuelCellBoundingSphereFactor = .5f;
public const float BarrierBoundingSphereFactor = .7f;
}
}
2.Lop chua dinh nghia cac doi tuong cua game:
//lop nay` cho cac object khac thua` ke'
class GameObject
{
public Model Model { get; set; }
public Vector3 Position { get; set; }
public BoundingSphere BoundingSphere { get; set; }
public GameObject()
{
Model = null;
Position = Vector3.Zero;
BoundingSphere = new BoundingSphere();
}
//bounding dua tren cac mesh cua model
protected BoundingSphere CalculateBoundingSphere()
{
BoundingSphere mergedSphere = new BoundingSphere();
BoundingSphere[] boundingSpheres;
int index = 0;
int meshCount = Model.Meshes.Count;
boundingSpheres = new BoundingSphere[meshCount];
foreach (ModelMesh mesh in Model.Meshes)
{
boundingSpheres[index++] = mesh.BoundingSphere;
}
mergedSphere = boundingSpheres[0];
if ((Model.Meshes.Count) > 1)
{
index = 1;
do
{
mergedSphere = BoundingSphere.CreateMerged(mergedSphere, boundingSpheres[index]);
index++;
} while (index < Model.Meshes.Count);
}
mergedSphere.Center.Y = 0;
return mergedSphere;
}
//Draw cai model :
internal void DrawBoundingSphere(Matrix view, Matrix projection, GameObject boundingSphereModel)
{
Matrix scaleMatrix = Matrix.CreateScale(BoundingSphere.Radius);
Matrix translateMatrix = Matrix.CreateTranslation(BoundingSphere.Center);
Matrix worldMatrix = scaleMatrix * translateMatrix;
foreach (ModelMesh mesh in boundingSphereModel.Model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = worldMatrix;
effect.View = view;
effect.Projection = projection;
}
mesh.Draw();
}
}
}
3.Lop cho fuel, cai chung ta thu nhat
[code] class FuelCell : GameObject
{
//da dc thu nhat hay chua:
public bool Retrieved { get; set; }
public FuelCell()
: base()
{
Retrieved = false;
}
public void LoadContent(ContentManager content, string modelName)
{
Model = content.Load<Model>(modelName);
Position = Vector3.Down;
BoundingSphere = CalculateBoundingSphere();
BoundingSphere scaledSphere;
scaledSphere = BoundingSphere;
scaledSphere.Radius *= GameConstants.FuelCellBoundingSphereFactor;
//bounding sau khi da dc scale:
BoundingSphere = new BoundingSphere(scaledSphere.Center, scaledSphere.Radius);
}
public void Draw(Matrix view, Matrix projection)
{
//di chuyen object sang vi tri' xac dinh
Matrix translateMatrix = Matrix.CreateTranslation(Position);
Matrix worldMatrix = translateMatrix;
foreach (ModelMesh mesh in Model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = worldMatrix;
effect.View = view;
effect.Projection = projection;
effect.EnableDefaultLighting();
effect.PreferPerPixelLighting = true;
}
mesh.Draw();
}
}
//KT va cham voi mot bounding cua object di chuyen (player)
internal void Update(BoundingSphere vehicleBoundingSphere)
{
if (vehicleBoundingSphere.Intersects(this.BoundingSphere))
//da co va cham
this.Retrieved = true;
}
}[/code]
4.class cho cac vat can
class Barrier : GameObject
{
public string BarrierType { get; set; }
public Barrier()
: base()
{
BarrierType = null;
}
public void LoadContent(ContentManager content, string modelName)
{
Model = content.Load<Model>(modelName);
//kieu cua vat can trung voi ten model cua no'
BarrierType = modelName;
Position = Vector3.Down;
BoundingSphere = CalculateBoundingSphere();
BoundingSphere scaledSphere;
scaledSphere = BoundingSphere;
scaledSphere.Radius *= GameConstants.BarrierBoundingSphereFactor;unding sau khi scale
//b
BoundingSphere = new BoundingSphere(scaledSphere.Center, scaledSphere.Radius);
}
public void Draw(Matrix view, Matrix projection)
{
//dat object o vi tri xac dinh
Matrix translateMatrix = Matrix.CreateTranslation(Position);
Matrix worldMatrix = translateMatrix;
foreach (ModelMesh mesh in Model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = worldMatrix;
effect.View = view;
effect.Projection = projection;
effect.EnableDefaultLighting();
effect.PreferPerPixelLighting = true;
}
mesh.Draw();
}
}
}
//class cua player
class FuelCarrier : GameObject
{
//goc xoay di chuyen
public float ForwardDirection { get; set; }
//khoang cach toi da di chuyen
public int MaxRange { get; set; }
public FuelCarrier()
: base()
{
ForwardDirection = 0.0f;
MaxRange = GameConstants.MaxRange;
}
public void LoadContent(ContentManager content, string modelName)
{
Model = content.Load<Model>(modelName);
BoundingSphere = CalculateBoundingSphere();
BoundingSphere scaledSphere;
scaledSphere = BoundingSphere;
scaledSphere.Radius *= GameConstants.FuelCarrierBoundingSphereFactor;
//bounding sau khi scale
BoundingSphere = new BoundingSphere(scaledSphere.Center, scaledSphere.Radius);
}
//dat lai vi tri cho player
internal void Reset()
{
Position = Vector3.Zero;
ForwardDirection = 0f;
}
public void Draw(Matrix view, Matrix projection)
{
Matrix worldMatrix = Matrix.Identity;
//goc xoay quanh truc Y
Matrix rotationYMatrix = Matrix.CreateRotationY(ForwardDirection);
Matrix translateMatrix = Matrix.CreateTranslation(Position);
//object tu xoay quanh truc Y cua model
worldMatrix = rotationYMatrix * translateMatrix;
foreach (ModelMesh mesh in Model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = worldMatrix;
effect.View = view;
effect.Projection = projection;
effect.EnableDefaultLighting();
effect.PreferPerPixelLighting = true;
}
mesh.Draw();
}
}
//Control player
public void Update(GamePadState gamepadState, KeyboardState keyboardState, Barrier[] barriers)
{
Vector3 futurePosition = Position;
float turnAmount = 0;
//xoay sang trai hay phai
if (keyboardState.IsKeyDown(Keys.A))
{
turnAmount = 1;
}
else if(keyboardState.IsKeyDown(Keys.D))
{
turnAmount = -1;
}
else if(gamepadState.ThumbSticks.Left.X != 0)
{
turnAmount = -gamepadState.ThumbSticks.Left.X;
}
//tang goc xoay khi chung ta bam nut'! kem` voi 1 const kiem` che' toi' //do.
ForwardDirection += turnAmount * GameConstants.TurnSpeed;
Matrix orientationMatrix = Matrix.CreateRotationY(ForwardDirection);
//di chyen toi' va` lui
Vector3 movement = Vector3.Zero;
if (keyboardState.IsKeyDown(Keys.W))
{
movement.Z = 1;
}
else if(keyboardState.IsKeyDown(Keys.S))
{
movement.Z = -1;
}
else if (gamepadState.ThumbSticks.Left.Y != 0)
{
movement.Z = gamepadState.ThumbSticks.Left.Y;
}
//toa do. moi' cua player, bien doi vi tri movement theo viec xoay quanh 1 ma tran xoay orientationMatrix
Vector3 speed = Vector3.Transform(movement, orientationMatrix);
//Kiem? Soat no voi const
speed *= GameConstants.Velocity;
//Vi tri moi; se dc cong them vao vi tri hien tai
futurePosition = Position + speed;
//KT xem vi tri moi co hop ly hay ko
if (ValidateMovement(futurePosition, barriers))
{
//Neu no hop ly', future se tro thanh present!
Position = futurePosition;
//bounding cua player can thay doi khi no di chuyen:
BoundingSphere updatedSphere;
updatedSphere = BoundingSphere;
updatedSphere.Center.X = Position.X;
updatedSphere.Center.Z = Position.Z;
//bounding sau khi update!
BoundingSphere = new BoundingSphere(updatedSphere.Center, updatedSphere.Radius);
}
}
//method KT diem future co hop ly hay ko
private bool ValidateMovement(Vector3 futurePosition, Barrier[] barriers)
{
BoundingSphere futureBoundingSphere = BoundingSphere;
futureBoundingSphere.Center.X = futurePosition.X;
futureBoundingSphere.Center.Z = futurePosition.Z;
//Khoang cach ma player di dc toi da
if ((Math.Abs(futurePosition.X) > MaxRange) || (Math.Abs(futurePosition.Z) > MaxRange))
return false;
//Don't allow driving through a barrier
if (CheckForBarrierCollision(futureBoundingSphere, barriers))
return false;
return true;
}
//KT va cham voi cac vat can
private bool CheckForBarrierCollision(BoundingSphere vehicleBoundingSphere, Barrier[] barriers)
{
for (int curBarrier = 0; curBarrier < barriers.Length; curBarrier++)
{
if (vehicleBoundingSphere.Intersects(barriers[curBarrier].BoundingSphere))
return true;
}
return false;
}
}
6.class cho camera,
[code] class Camera
{
public Vector3 AvatarHeadOffset { get; set; }
public Vector3 TargetOffset { get; set; }
public Matrix ViewMatrix { get; set; }
public Matrix ProjectionMatrix { get; set; }
public Camera()
{
AvatarHeadOffset = new Vector3(0, 7, -15);
TargetOffset = new Vector3(0, 5, 0);
ViewMatrix = Matrix.Identity;
ProjectionMatrix = Matrix.Identity;
}
//cho biet goc ma` camera xoay quanh truc Y
//Goc nay trung voi goc ma` player phai xoay:
public void Update(float avatarYaw, Vector3 position, float aspectRatio)
{
Matrix rotationMatrix = Matrix.CreateRotationY(avatarYaw);
Vector3 transformedheadOffset = Vector3.Transform(AvatarHeadOffset, rotationMatrix);
Vector3 transformedReference = Vector3.Transform(TargetOffset, rotationMatrix);
Vector3 cameraPosition = position + transformedheadOffset;
Vector3 cameraTarget = position + transformedReference;
//Calculate the camera's view and projection matrices based on current values.
ViewMatrix = Matrix.CreateLookAt(cameraPosition, cameraTarget, Vector3.Up);
ProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(GameConstants.ViewAngle),
aspectRatio, GameConstants.NearClip, GameConstants.FarClip);
}
}
}[/code]
7.Game1.cs:
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
namespace FuelCell
{
//cac man` cua game
public enum GameState { Loading, Running, Won, Lost }
/// <summary>
/// This is the main type for your game
/// </summary>
public class FuelCellGame : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
//tao phim release
KeyboardState lastKeyboardState = new KeyboardState();
KeyboardState currentKeyboardState = new KeyboardState();
GamePadState lastGamePadState = new GamePadState();
GamePadState currentGamePadState = new GamePadState();
//so luong fuel da nhat dc
int retrievedFuelCells = 0;
//thoi diem bat dau`,dem' thoi gian da qua, Thoi gian toi' da
TimeSpan startTime, roundTimer, roundTime;
Random random;
SpriteBatch spriteBatch;
SpriteFont statsFont;
//dat man` hien tai la "loading"
GameState currentGameState = GameState.Loading;
GameObject ground;
Camera gameCamera;
//bounding cua...
GameObject boundingSphere;
FuelCarrier fuelCarrier;
FuelCell[] fuelCells;
Barrier[] barriers;
public FuelCellGame()
{
graphics = new GraphicsDeviceManager(this);
graphics.PreferredBackBufferWidth = 853;
graphics.PreferredBackBufferHeight = 480;
Content.RootDirectory = "Content";
//roundTime = 30.25f
roundTime = GameConstants.RoundTime;
random = new Random();
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
ground = new GameObject();
gameCamera = new Camera();
boundingSphere = new GameObject();
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
//load ground
ground.Model = Content.Load<Model>("Models/ground");
boundingSphere.Model = Content.Load<Model>("Models/sphere1uR");
spriteBatch = new SpriteBatch(GraphicsDevice);
//load font
statsFont = Content.Load<SpriteFont>("Fonts/StatsFont");
//Thiet lap cac fuel
fuelCells = new FuelCell[GameConstants.NumFuelCells];
//lap tat ca cac fuel
for (int index = 0; index < fuelCells.Length; index++)
{
fuelCells[index] = new FuelCell();
fuelCells[index].LoadContent(Content, "Models/fuelcell");
}
//Initialize barriers
barriers = new Barrier[GameConstants.NumBarriers];
int randomBarrier = random.Next(3);
string barrierName = null;
for (int index = 0; index < barriers.Length; index++)
{
switch (randomBarrier)
{
case 0:
barrierName = "Models/cube10uR";
break;
case 1:
barrierName = "Models/cylinder10uR";
break;
case 2:
barrierName = "Models/pyramid10uR";
break;
}
barriers[index] = new Barrier();
barriers[index].LoadContent(Content, barrierName);
randomBarrier = random.Next(3);
}
//method dat fuel va barrier vao` vi tri phu hop
PlaceFuelCellsAndBarriers();
//Initialize fuel carrier
fuelCarrier = new FuelCarrier();
fuelCarrier.LoadContent(Content, "Models/fuelcarrier");
}
//dat cac thanh phan tren vao` vi tri
private void PlaceFuelCellsAndBarriers()
{
int min = GameConstants.MinDistance;
int max = GameConstants.MaxDistance;
Vector3 tempCenter;
//place fuel cells
foreach (FuelCell cell in fuelCells)
{
//lay ngau nhien vi tri fuel
cell.Position = GenerateRandomPosition(min, max);
tempCenter.X = cell.Position.X;
tempCenter.Y = 0;
tempCenter.Z = cell.Position.Z;
//bounding cho fuel
cell.BoundingSphere = new BoundingSphere(tempCenter, cell.BoundingSphere.Radius);
cell.Retrieved = false;
}
//place barriers
foreach (Barrier barrier in barriers)
{
//dat ngau nhien vat can
barrier.Position = GenerateRandomPosition(min, max);
tempCenter.X = barrier.Position.X;
tempCenter.Y = 0;
tempCenter.Z = barrier.Position.Z;
barrier.BoundingSphere = new BoundingSphere(tempCenter, barrier.BoundingSphere.Radius);
}
}
//ham dat ngau nhien vi tri'
private Vector3 GenerateRandomPosition(int min, int max)
{
int xValue, zValue;
do
{
xValue = random.Next(min, max);
zValue = random.Next(min, max);
//50% khi muon dat nguoc lai vi tri cua object
if (random.Next(100) % 2 == 0)
xValue *= -1;
if (random.Next(100) % 2 == 0)
zValue *= -1;
}
//Vi tri chi thoa man neu no ko co van de`
while (IsOccupied(xValue, zValue));
return new Vector3(xValue, 0, zValue);
}
private bool IsOccupied(int xValue, int zValue)
{
foreach (GameObject currentObj in fuelCells)
{
if (((int)(MathHelper.Distance(xValue, currentObj.Position.X)) < 15) &&
((int)(MathHelper.Distance(zValue, currentObj.Position.Z)) < 15))
return true;
}
foreach (GameObject currentObj in barriers)
{
if (((int)(MathHelper.Distance(xValue, currentObj.Position.X)) < 15) &&
((int)(MathHelper.Distance(zValue, currentObj.Position.Z)) < 15))
return true;
}
return false;
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
float aspectRatio = graphics.GraphicsDevice.Viewport.AspectRatio;
lastKeyboardState = currentKeyboardState;
currentKeyboardState = Keyboard.GetState();
lastGamePadState = currentGamePadState;
currentGamePadState = GamePad.GetState(PlayerIndex.One);
//update cho Loading screen
if (currentGameState == GameState.Loading)
{
//release phim Enter
if ((lastKeyboardState.IsKeyDown(Keys.Enter) && (currentKeyboardState.IsKeyUp(Keys.Enter))) ||
currentGamePadState.Buttons.Start == ButtonState.Pressed)
{
// bat dau cho play screen
roundTimer = roundTime;
currentGameState = GameState.Running;
}
}
//update cho play screen
if ((currentGameState == GameState.Running))
{
//Dieu khien player
fuelCarrier.Update(currentGamePadState, currentKeyboardState, barriers);
//dieu khien camera
gameCamera.Update(fuelCarrier.ForwardDirection, fuelCarrier.Position, aspectRatio);
retrievedFuelCells = 0;
foreach (FuelCell fuelCell in fuelCells)
{
//KT va cham voi player
fuelCell.Update(fuelCarrier.BoundingSphere);
//dem sl fuel thu nhat dc
if (fuelCell.Retrieved)
{
retrievedFuelCells++;
}
}
//KT dieu khien Win
if (retrievedFuelCells == GameConstants.NumFuelCells)
{
currentGameState = GameState.Won;
}
//Thoi gian la 30.25f giay va` dang giam dan`
roundTimer -= gameTime.ElapsedGameTime;
if ((roundTimer < TimeSpan.Zero) && (retrievedFuelCells != GameConstants.NumFuelCells))
{
//nguoi choi se thua
currentGameState = GameState.Lost;
}
}
if ((currentGameState == GameState.Won) || (currentGameState == GameState.Lost))
{
// Bat dau` lai tro` choi (play screen)
if ((lastKeyboardState.IsKeyDown(Keys.Enter) && (currentKeyboardState.IsKeyUp(Keys.Enter))) ||
currentGamePadState.Buttons.Start == ButtonState.Pressed)
ResetGame(gameTime, aspectRatio);
}
base.Update(gameTime);
}
private void ResetGame(GameTime gameTime, float aspectRatio)
{
fuelCarrier.Reset();
gameCamera.Update(fuelCarrier.ForwardDirection, fuelCarrier.Position, aspectRatio);
//tao lai cac barriers
InitializeGameField();
retrievedFuelCells = 0;
startTime = gameTime.TotalGameTime;
roundTimer = roundTime;
currentGameState = GameState.Running;
}
private void InitializeGameField()
{
//Initialize barriers
barriers = new Barrier[GameConstants.NumBarriers];
int randomBarrier = random.Next(3);
string barrierName = null;
for (int index = 0; index < GameConstants.NumBarriers; index++)
{
switch (randomBarrier)
{
case 0:
barrierName = "Models/cube10uR";
break;
case 1:
barrierName = "Models/cylinder10uR";
break;
case 2:
barrierName = "Models/pyramid10uR";
break;
}
barriers[index] = new Barrier();
barriers[index].LoadContent(Content, barrierName);
randomBarrier = random.Next(3);
}
PlaceFuelCellsAndBarriers();
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.Black);
//tuy theo man` ma` draw
switch (currentGameState)
{
case GameState.Loading:
DrawSplashScreen();
break;
case GameState.Running:
DrawGameplayScreen();
break;
case GameState.Won:
DrawWinOrLossScreen(GameConstants.StrGameWon);
break;
case GameState.Lost:
DrawWinOrLossScreen(GameConstants.StrGameLost);
break;
};
base.Draw(gameTime);
}
/// <summary>
/// Draws the game terrain, a simple blue grid.
/// </summary>
/// <param name="model">Model representing the game playing field.</param>
private void DrawTerrain(Model model)
{
foreach (ModelMesh mesh in model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.EnableDefaultLighting();
effect.PreferPerPixelLighting = true;
effect.World = Matrix.Identity;
// Use the matrices provided by the game camera
effect.View = gameCamera.ViewMatrix;
effect.Projection = gameCamera.ProjectionMatrix;
}
mesh.Draw();
}
}
//man gioi thieu
private void DrawSplashScreen()
{
float xOffsetText, yOffsetText;
Vector2 viewportSize = new Vector2(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
Vector2 strCenter;
graphics.GraphicsDevice.Clear(Color.SteelBlue);
xOffsetText = yOffsetText = 0;
Vector2 strInstructionsSize = statsFont.MeasureString(GameConstants.StrInstructions1);
Vector2 strPosition;
strCenter = new Vector2(strInstructionsSize.X / 2, strInstructionsSize.Y / 2);
yOffsetText = (viewportSize.Y / 2 - strCenter.Y);
xOffsetText = (viewportSize.X / 2 - strCenter.X);
strPosition = new Vector2(xOffsetText, yOffsetText);
spriteBatch.Begin();
spriteBatch.DrawString(statsFont, GameConstants.StrInstructions1, strPosition, Color.White);
strInstructionsSize = statsFont.MeasureString(GameConstants.StrInstructions2);
strCenter = new Vector2(strInstructionsSize.X / 2, strInstructionsSize.Y / 2);
yOffsetText = (viewportSize.Y / 2 - strCenter.Y) + statsFont.LineSpacing;
xOffsetText = (viewportSize.X / 2 - strCenter.X);
strPosition = new Vector2(xOffsetText, yOffsetText);
spriteBatch.DrawString(statsFont, GameConstants.StrInstructions2, strPosition, Color.LightGray);
spriteBatch.End();
//re-enable depth buffer after sprite batch disablement
GraphicsDevice.RenderState.DepthBufferEnable = true;
GraphicsDevice.RenderState.AlphaBlendEnable = false;
GraphicsDevice.RenderState.AlphaTestEnable = false;
GraphicsDevice.SamplerStates[0].AddressU = TextureAddressMode.Wrap;
GraphicsDevice.SamplerStates[0].AddressV = TextureAddressMode.Wrap;
}
//thang hay thua
private void DrawWinOrLossScreen(string gameResult)
{
float xOffsetText, yOffsetText;
Vector2 viewportSize = new Vector2(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
Vector2 strCenter;
xOffsetText = yOffsetText = 0;
Vector2 strResult = statsFont.MeasureString(gameResult);
Vector2 strPlayAgainSize = statsFont.MeasureString(GameConstants.StrPlayAgain);
Vector2 strPosition;
strCenter = new Vector2(strResult.X / 2, strResult.Y / 2);
yOffsetText = (viewportSize.Y / 2 - strCenter.Y);
xOffsetText = (viewportSize.X / 2 - strCenter.X);
strPosition = new Vector2(xOffsetText, yOffsetText);
spriteBatch.Begin();
spriteBatch.DrawString(statsFont, gameResult, strPosition, Color.Red);
strCenter = new Vector2(strPlayAgainSize.X / 2, strPlayAgainSize.Y / 2);
yOffsetText = (viewportSize.Y / 2 - strCenter.Y) + (float)statsFont.LineSpacing;
xOffsetText = (viewportSize.X / 2 - strCenter.X);
strPosition = new Vector2(xOffsetText, yOffsetText);
spriteBatch.DrawString(statsFont, GameConstants.StrPlayAgain, strPosition, Color.AntiqueWhite);
spriteBatch.End();
//re-enable depth buffer after sprite batch disablement
GraphicsDevice.RenderState.DepthBufferEnable = true;
GraphicsDevice.RenderState.AlphaBlendEnable = false;
GraphicsDevice.RenderState.AlphaTestEnable = false;
GraphicsDevice.SamplerStates[0].AddressU = TextureAddressMode.Wrap;
GraphicsDevice.SamplerStates[0].AddressV = TextureAddressMode.Wrap;
}
//playerScreen
private void DrawGameplayScreen()
{
//draw model
DrawTerrain(ground.Model);
foreach (FuelCell fuelCell in fuelCells)
{
if (!fuelCell.Retrieved)
{
fuelCell.Draw(gameCamera.ViewMatrix, gameCamera.ProjectionMatrix);
}
}
foreach (Barrier barrier in barriers)
{
barrier.Draw(gameCamera.ViewMatrix, gameCamera.ProjectionMatrix);
}
fuelCarrier.Draw(gameCamera.ViewMatrix, gameCamera.ProjectionMatrix);
DrawStats();
}
private void DrawStats()
{
float xOffsetText, yOffsetText;
string str1 = GameConstants.StrTimeRemaining;
string str2 = GameConstants.StrCellsFound + retrievedFuelCells.ToString() + " of " + GameConstants.NumFuelCells.ToString();
Rectangle rectSafeArea;
str1 += (roundTimer.Seconds).ToString();
//Calculate str1 position
rectSafeArea = GetTitleSafeArea(GraphicsDevice.Viewport);
xOffsetText = rectSafeArea.X;
yOffsetText = rectSafeArea.Y;
Vector2 strSize = statsFont.MeasureString(str1);
Vector2 strPosition = new Vector2(xOffsetText + 10, yOffsetText);
spriteBatch.Begin();
spriteBatch.DrawString(statsFont, str1, strPosition, Color.White);
strPosition.Y += strSize.Y;
spriteBatch.DrawString(statsFont, str2, strPosition, Color.White);
spriteBatch.End();
//re-enable depth buffer after sprite batch disablement
GraphicsDevice.RenderState.DepthBufferEnable = true;
GraphicsDevice.RenderState.AlphaBlendEnable = false;
GraphicsDevice.RenderState.AlphaTestEnable = false;
GraphicsDevice.SamplerStates[0].AddressU = TextureAddressMode.Wrap;
GraphicsDevice.SamplerStates[0].AddressV = TextureAddressMode.Wrap;
}
private Rectangle GetTitleSafeArea(Viewport viewport)
{
Rectangle retval = new Rectangle(viewport.X, viewport.Y, viewport.Width, viewport.Height);
#if XBOX
retval = viewport.TitleSafeArea;
#endif
return retval;
}
}
}
Source: http://www.mediafire.com/?2qodaznmizm
Similar topics
» Thông báo tuyển quân thành lập team phát triển Game! va Free Open Source game
» networking cho game xna 2d
» Game rắn săn mồi đêeeeee!!!!
» Hỏi về cài đặt XNA game studio 4.0
» chơi game làm bởi xna như thế nào?
» networking cho game xna 2d
» Game rắn săn mồi đêeeeee!!!!
» Hỏi về cài đặt XNA game studio 4.0
» chơi game làm bởi xna như thế nào?
Trang 1 trong tổng số 1 trang
Permissions in this forum:
Bạn không có quyền trả lời bài viết