天天看點

XNA系列—3d模型的導入

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.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace My3DGame
{
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        Model terrain;   //地形的模型
        Vector3 terrainPosition; //地形的世界坐标位置

        Matrix cameraViewMatrix;   //照相機視圖矩陣
        Matrix cameraProjectionMatrix;  //照相機投影矩陣

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }


        protected override void Initialize()
        {
            base.Initialize();
        }

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            terrain = Content.Load<Model>("Models\\terrain");
            terrainPosition = Vector3.Zero;

           
            //初始化錄影機的視圖矩陣  參數: 錄影機位置,錄影機目标位置,看的方向
            cameraViewMatrix = Matrix.CreateLookAt(
                 new Vector3(0f, 60f, 160f),
                 new Vector3(0f, 50f, 0f),
                 Vector3.Up);
            //初始化錄影機的投影矩陣 參數:錄影機看的範圍、螢幕的比例、照相機看的最近的距離、照相機看的最遠的距離
            cameraProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.PiOver4,
                graphics.GraphicsDevice.Viewport.AspectRatio,
                1f,
                10000f);

        }

        protected override void UnloadContent()
        {
        }

        protected override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
        }


        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            foreach (ModelMesh mesh in terrain.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.EnableDefaultLighting();
                    effect.PreferPerPixelLighting = true;

                    effect.World = Matrix.CreateTranslation(terrainPosition);  //将世界坐标轉化成矩陣坐标
                    effect.View = cameraViewMatrix;
                    effect.Projection = cameraProjectionMatrix;
                }
                mesh.Draw();
            }
            base.Draw(gameTime);
        }
    }
}
           

繼續閱讀