在Windows Phone中進行3D開發之三空間

來源:互聯網
上載者:User

       經過前兩節的學習,我們已經具備了建立三維空間的條件了,相信很多人已經躍躍欲試了,接下來,我們就動手開始在Windows Phone中的3D開發之旅。

 

       開啟Visual Studio 2010(什嗎?還沒有Windows Phone的開發環境?唉,自己處理一下吧,有問題問百度),建立一個項目(File->New->Project),在彈出的對話方塊中選擇XNA Game Studio 4.0中的Windows Phone Game,在Name中就命名為“Hello”吧,點擊“OK”確定。介面如所示。

 

       在Solution Explorer視窗中右擊項目名,執行Add->Class功能表項目,如所示。

 

 

       在彈出的對話方塊中按選擇,將類命名為Camera,點擊“Add”按鈕。

 

 

       為Camera類添加兩個屬性:

        public Matrix view{get;protected set;}

        public Matrix projection { get; protectedset; }

 

       修改Camera類的建構函式為:

        public Camera(Game game, Vector3 pos,Vector3 target, Vector3 up, float fieldOfView, float aspectRatio, floatnearPlaneDistance,float farPlaneDistance)

            : base(game)

        {

            view = Matrix.CreateLookAt(pos,target, up);

            projection =Matrix.CreatePerspectiveFieldOfView(fieldOfView,aspectRatio,nearPlaneDistance,farPlaneDistance);

        }

該類的完整代碼見《在Windows Phone中進行3D開發之二攝像機》一文。

 

       開啟Game1類,添加如下成員變數:

        Camera camera;

        Matrix world = Matrix.Identity;

        BasicEffect basicEffect;

 

       在Game1()構造方法中添加代碼:

graphics.IsFullScreen =true;

 

       在LoacContent()方法中添加代碼:

            camera = new Camera(this, newVector3(0, 0, 5), Vector3.Zero, Vector3.Up, MathHelper.PiOver4,GraphicsDevice.Viewport.AspectRatio, 1.0f, 50.0f);

            Components.Add(camera);

            basicEffect = newBasicEffect(GraphicsDevice);

這段代碼中,MathHelper是一個數學上的輔助類,其PiOver4屬性是π/4,即45度角。Viewport.AspectRatio是長寬比。

 

       在Draw()方法中添加代碼:

            basicEffect.World = world;

            basicEffect.View = camera.view;

            basicEffect.Projection =camera.projection;

            foreach (EffectPass pass inbasicEffect.CurrentTechnique.Passes)

            {

                pass.Apply();

            }

       BasicEffect類的作用是控制渲染效果,在3D開發中必不可少。通常用在Draw()方法中進行設定以改變渲染器的行為,後文中我們還將用它控制顏色、光線等很多特效。在前幾節內容中用的較多的就是BasicEffect的三個屬性,即代碼中的World、View、Projection,分別代表世界矩陣、攝像機矩陣、投影矩陣。這裡我們要在座標原點繪製對象,所以World設定了單位矩陣,即Mathix.Identity。

       BasicEffect裡包含一些Technique,每個Technique又由若干EffectPass組成,我們要在每個EffectPass上進行Apply請求,才能在該EffectPass上進行繪製。這個Apply()方法的調用就像我們進行2D時調用SpriteBatch.Begin()一樣,是繪製開始前必須調用的方法。因此在使用BasicEffect時,需要一個foreach迴圈。

 

       完整的Game1類代碼如下:

 

using System;using System.Collections.Generic;using System.Linq;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.Input.Touch;using Microsoft.Xna.Framework.Media;namespace Hello{    /// <summary>    /// This is the main type for your game    /// </summary>    public class Game1 : Microsoft.Xna.Framework.Game    {        GraphicsDeviceManager graphics;        Camera camera;        Matrix world = Matrix.Identity;        BasicEffect basicEffect;        public Game1()        {            graphics = new GraphicsDeviceManager(this);            Content.RootDirectory = "Content";            // Frame rate is 30 fps by default for Windows Phone.            TargetElapsedTime = TimeSpan.FromTicks(333333);            // Extend battery life under lock.            InactiveSleepTime = TimeSpan.FromSeconds(1);            graphics.IsFullScreen = true;        }        /// <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()        {            // TODO: Add your initialization logic here            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()        {            camera = new Camera(this, new Vector3(0, 0, 5), Vector3.Zero, Vector3.Up, MathHelper.PiOver4, GraphicsDevice.Viewport.AspectRatio, 1.0f, 50.0f);            Components.Add(camera);            basicEffect = new BasicEffect(GraphicsDevice);        }        /// <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();            // TODO: Add your update logic here            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)        {            GraphicsDevice.Clear(Color.CornflowerBlue);            basicEffect.World = world;            basicEffect.View = camera.view;            basicEffect.Projection = camera.projection;            foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)            {                pass.Apply();            }            base.Draw(gameTime);        }    }}

       運行程式,開啟模擬器,運行結果如所示。

 

 

       不用懷疑,雖然螢幕上什麼都沒有,但事實上螢幕上所表現的已經是一個三維空間,我們有一個攝像機位於(0,0,5)位置,也就是螢幕外,攝像機方向指向了原點,使用了45度視角和螢幕的寬高比進行成像,近平面是1,遠平面是50。在下節中,我們就將在其中加入物體。

 

——歡迎轉載,請註明出處 http://blog.csdn.net/caowenbin ——

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.