418383/418587 ภาคปลาย 2553/การเขียนเกมสามมิติด้วย XNA 4.0
Model
- ใน XNA มีีคลาส Model สำหรับโมเดลสามมิติพื้นฐาน
- Content pipeline ที่ติดมากับ XNA สามารถอ่านไฟล์ .x (ไฟล์ของ DirectX) และไฟล์ .fbx (ไฟล์ของ Adobe ที่สามารถ export ได้จาก Maya และ 3D Studio Max) ได้
- ตัวอย่างการอ่านไฟล์
<geshi lang="C#">
public class Game1 : Microsoft.Xna.Framework.Game
{
Model model;
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
model = Content.Load<Model>("teapot");
}
}
</geshi>
- เวลาแสดงโมเดลให้ใช้โค้ดต่อไปนี้
<geshi lang="C#">
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
Matrix viewMatrix = Matrix.CreateLookAt(new Vector3(0, 0, 5), new Vector3(0, 0, 0), new Vector3(0, 1, 0));
Matrix projectMatrix = Matrix.CreatePerspectiveFieldOfView((float)Math.PI / 4, 1.0f, 0.1f, 100.0f);
// Copy any parent transforms.
Matrix[] transforms = new Matrix[model.Bones.Count];
model.CopyAbsoluteBoneTransformsTo(transforms);
foreach (ModelMesh mesh in model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.EnableDefaultLighting();
effect.World = transforms[mesh.ParentBone.Index];
effect.View = viewMatrix;
effect.Projection = projectMatrix;
}
// Draw the mesh, using the effects set above.
mesh.Draw();
}
base.Draw(gameTime);
}
</geshi>