ポリゴンにテクスチャーを貼る
概要
ポリゴンにテクスチャーを貼って描画しています。
動作環境
必須環境
| 対応 XNA バージョン | 
 | 
| 対応プラットフォーム | 
 | 
| Windows 必須頂点シェーダ バージョン | 2.0 | 
| Windows 必須ピクセルシェーダ バージョン | 2.0 | 
動作確認環境
| プラットフォーム | 
 | 
内容
テクスチャーについて
テクスチャーをポリゴンに貼り付けるには、頂点データに「テクスチャー座標」という情報を持たせなければいけません。テクスチャー座標とは「頂点にテクスチャーのどの位置を合わせるか」を表したものです。作成されたテクスチャーにはテクスチャー座標が下のように定義されています。
四角形ポリゴンのテクスチャー座標にテクスチャーのテクスチャー座標と同じように設定することにより、ポリゴンにぴったりテクスチャーが貼り付けられるわけです。
テクスチャーの準備
テクスチャーを使用するにはコンテンツパイプラインから読み込むので予めプロジェクトに画像ファイルを追加しておいてください。
フィールド
 <summary>
 頂点バッファ
 </summary>
private VertexBuffer vertexBuffer = null;
 <summary>
 基本エフェクト
 </summary>
private BasicEffect basicEffect = null;
 <summary>
 テクスチャー
 </summary>
private Texture2D texture = null;
頂点バッファなどのほかに「Texture2D」をフィールドとして宣言しておきます。読み込んだ画像ファイルの情報はこの変数に格納されます。
作成
// エフェクトを作成
this.basicEffect = new BasicEffect(this.GraphicsDevice);
// テクスチャーの使用を許可する
this.basicEffect.TextureEnabled = true;
BasicEffect を作成した際に「BasicEffect.TextureEnabled」を true に設定してテクスチャーを使用できるようにします。
// 頂点バッファ作成
this.vertexBuffer = new VertexBuffer(this.GraphicsDevice,
    typeof(VertexPositionTexture), 4, BufferUsage.None);
// 頂点データを作成する
VertexPositionTexture[] vertices = new VertexPositionTexture[4];
vertices[0] = new VertexPositionTexture(new Vector3(-2.0f, 2.0f, 0.0f),
                                        new Vector2(0.0f, 0.0f));
vertices[1] = new VertexPositionTexture(new Vector3(2.0f, 2.0f, 0.0f),
                                        new Vector2(1.0f, 0.0f));
vertices[2] = new VertexPositionTexture(new Vector3(-2.0f, -2.0f, 0.0f),
                                        new Vector2(0.0f, 1.0f));
vertices[3] = new VertexPositionTexture(new Vector3(2.0f, -2.0f, 0.0f),
                                        new Vector2(1.0f, 1.0f));
// 頂点データを頂点バッファに書き込む
this.vertexBuffer.SetData(vertices);
頂点データの作成コードです。今回は頂点の色を使用するのではなく、テクスチャーの色を使用してポリゴンを描画するため、頂点データを定義する構造体が「VertexPositionTexture」になります。この構造体は「位置」と「テクスチャー座標」のデータを持ちます。
四角形ポリゴンの4つの頂点のテクスチャー座標をテクスチャーのテクスチャー座標と同じ値にセットします。これで画像データがポリゴンにぴったり収まります。
VertexPositionTexture コンストラクタ
位置とテクスチャー座標の頂点データを持つ構造体「VertexPositionTexture 」のインスタンスを作成します。
| position | Vector3 | 頂点の位置 | 
| textureCoordinate | Vector2 | 頂点のテクスチャー座標 | 
// テクスチャーの読み込み
this.texture = this.Content.Load<Texture2D>("Texture");
// エフェクトにテクスチャーをセットする
this.basicEffect.Texture = this.texture;
ContentManager.Load メソッドでテクスチャーを読み込みます。今回テクスチャーは1枚しか使用しないので、ここでエフェクトにテクスチャーをセットしてしまっています。
描画
// 頂点バッファをセットします
this.GraphicsDevice.SetVertexBuffer(this.vertexBuffer);
// パスの数だけ繰り替えし描画
foreach (EffectPass pass in this.basicEffect.CurrentTechnique.Passes)
{
    // パスの開始
    pass.Apply();
    // ポリゴン描画する
    this.GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2);
}
ここは特に変わった点はなく、四角形ポリゴンを描画するときとまったく同じコードになります。ただし描画するテクスチャーが毎回切り替わる場合は、その都度エフェクトにテクスチャーをセットする必要があります。
全コード
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.Media;
#if WINDOWS_PHONE
using Microsoft.Xna.Framework.Input.Touch;
#endif
namespace TextureOnPolygon
{
     <summary>
     ゲームメインクラス
     </summary>
    public class GameMain : Microsoft.Xna.Framework.Game
    {
         <summary>
         グラフィックデバイス管理クラス
         </summary>
        private GraphicsDeviceManager graphics = null;
         <summary>
         スプライトのバッチ化クラス
         </summary>
        private SpriteBatch spriteBatch = null;
         <summary>
         頂点バッファ
         </summary>
        private VertexBuffer vertexBuffer = null;
         <summary>
         基本エフェクト
         </summary>
        private BasicEffect basicEffect = null;
         <summary>
         テクスチャー
         </summary>
        private Texture2D texture = null;
         <summary>
         GameMain コンストラクタ
         </summary>
        public GameMain()
        {
            // グラフィックデバイス管理クラスの作成
            this.graphics = new GraphicsDeviceManager(this);
            // ゲームコンテンツのルートディレクトリを設定
            this.Content.RootDirectory = "Content";
#if WINDOWS_PHONE
            // Windows Phone のデフォルトのフレームレートは 30 FPS
            this.TargetElapsedTime = TimeSpan.FromTicks(333333);
            // バックバッファサイズの設定
            this.graphics.PreferredBackBufferWidth = 480;
            this.graphics.PreferredBackBufferHeight = 800;
            // フルスクリーン表示
            this.graphics.IsFullScreen = true;
#endif
        }
         <summary>
         ゲームが始まる前の初期化処理を行うメソッド
         グラフィック以外のデータの読み込み、コンポーネントの初期化を行う
         </summary>
        protected override void Initialize()
        {
            // TODO: ここに初期化ロジックを書いてください
            // コンポーネントの初期化などを行います
            base.Initialize();
        }
         <summary>
         ゲームが始まるときに一回だけ呼ばれ
         すべてのゲームコンテンツを読み込みます
         </summary>
        protected override void LoadContent()
        {
            // テクスチャーを描画するためのスプライトバッチクラスを作成します
            this.spriteBatch = new SpriteBatch(this.GraphicsDevice);
            // エフェクトを作成
            this.basicEffect = new BasicEffect(this.GraphicsDevice);
            // テクスチャーの使用を許可する
            this.basicEffect.TextureEnabled = true;
            // ビューマトリックスをあらかじめ設定 ((5, 2, 10) から原点を見る)
            this.basicEffect.View = Matrix.CreateLookAt(
                    new Vector3(5.0f, 2.0f, 10.0f),
                    Vector3.Zero,
                    Vector3.Up
                );
            // プロジェクションマトリックスをあらかじめ設定
            this.basicEffect.Projection = Matrix.CreatePerspectiveFieldOfView(
                    MathHelper.ToRadians(45.0f),
                    (float)this.GraphicsDevice.Viewport.Width /
                        (float)this.GraphicsDevice.Viewport.Height,
                    1.0f,
                    100.0f
                );
            // 頂点バッファ作成
            this.vertexBuffer = new VertexBuffer(this.GraphicsDevice,
                typeof(VertexPositionTexture), 4, BufferUsage.None);
            // 頂点データを作成する
            VertexPositionTexture[] vertices = new VertexPositionTexture[4];
            vertices[0] = new VertexPositionTexture(new Vector3(-2.0f, 2.0f, 0.0f),
                                                    new Vector2(0.0f, 0.0f));
            vertices[1] = new VertexPositionTexture(new Vector3(2.0f, 2.0f, 0.0f),
                                                    new Vector2(1.0f, 0.0f));
            vertices[2] = new VertexPositionTexture(new Vector3(-2.0f, -2.0f, 0.0f),
                                                    new Vector2(0.0f, 1.0f));
            vertices[3] = new VertexPositionTexture(new Vector3(2.0f, -2.0f, 0.0f),
                                                    new Vector2(1.0f, 1.0f));
            // 頂点データを頂点バッファに書き込む
            this.vertexBuffer.SetData(vertices);
            // テクスチャーの読み込み
            this.texture = this.Content.Load<Texture2D>("Texture");
            // エフェクトにテクスチャーをセットする
            this.basicEffect.Texture = this.texture;
        }
         <summary>
         ゲームが終了するときに一回だけ呼ばれ
         すべてのゲームコンテンツをアンロードします
         </summary>
        protected override void UnloadContent()
        {
            // TODO: ContentManager で管理されていないコンテンツを
            //       ここでアンロードしてください
        }
         <summary>
         描画以外のデータ更新等の処理を行うメソッド
         主に入力処理、衝突判定などの物理計算、オーディオの再生など
         </summary>
         <param name="gameTime">このメソッドが呼ばれたときのゲーム時間</param>
        protected override void Update(GameTime gameTime)
        {
            // Xbox 360 コントローラ、Windows Phone の BACK ボタンを押したときに
            // ゲームを終了させます
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                this.Exit();
            }
            // TODO: ここに更新処理を記述してください
            // 登録された GameComponent を更新する
            base.Update(gameTime);
        }
         <summary>
         描画処理を行うメソッド
         </summary>
         <param name="gameTime">このメソッドが呼ばれたときのゲーム時間</param>
        protected override void Draw(GameTime gameTime)
        {
            // 画面を指定した色でクリアします
            this.GraphicsDevice.Clear(Color.CornflowerBlue);
            // 頂点バッファをセットします
            this.GraphicsDevice.SetVertexBuffer(this.vertexBuffer);
            // パスの数だけ繰り替えし描画
            foreach (EffectPass pass in this.basicEffect.CurrentTechnique.Passes)
            {
                // パスの開始
                pass.Apply();
                // ポリゴン描画する
                this.GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2);
            }
            // 登録された DrawableGameComponent を描画する
            base.Draw(gameTime);
        }
    }
}