この例ではVertexBufferを作らずにDrawUserPrimitivesメソッドで描画している。
VertexBufferを作りDrawPrimitivesメソッドで描画しても同じ結果になる。
どちらも頂点バッファだけでの描画なのでどちらが優れているかは知らん。可能であればインデックスバッファを使った描画の方が良いと思うぞ。
BasicEffectのVertexColorEnabledプロパティで色付けを有効にしている。これを設定しないと真っ白になり、設定すると頂点カラー間でグラデーションが掛かる。
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace DrawVertex
{
/// <summary>
/// This is the main type for your game.
/// </summary>
public class Game1 : Game
{
GraphicsDeviceManager _graphics;
VertexPositionColor[] _vertices;
Vector3 _cameraPosition = new Vector3(30, 0, 20);
BasicEffect _effect;
public Game1()
{
_graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
// マウスカーソルを表示する
this.IsMouseVisible = true;
// ウインドウサイズを変更する
_graphics.PreferredBackBufferWidth = 800;
_graphics.PreferredBackBufferHeight = 600;
_graphics.ApplyChanges();
// MonoGame標準搭載の固定シェーダーを生成する
_effect = new BasicEffect(_graphics.GraphicsDevice);
// 色を有効にする
_effect.VertexColorEnabled = true;
// 頂点データを作成する
_vertices = new VertexPositionColor[6];
_vertices[0] = new VertexPositionColor(new Vector3(-10, -10, 0), Color.Red);
_vertices[1] = new VertexPositionColor(new Vector3(-10, +10, 0), Color.Green);
_vertices[2] = new VertexPositionColor(new Vector3(+10, -10, 0), Color.Blue);
_vertices[3] = new VertexPositionColor(new Vector3(-10, +10, 0), Color.Green);
_vertices[4] = new VertexPositionColor(new Vector3(+10, +10, 0), Color.White);
_vertices[5] = new VertexPositionColor(new Vector3(+10, -10, 0), Color.Blue);
base.Initialize();
}
protected override void LoadContent()
{
}
protected override void Update(GameTime gameTime)
{
// For Mobile devices, this logic will close the Game when the Back button is pressed
// Exit() is obsolete on iOS
#if !__IOS__ && !__TVOS__
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
#endif
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
_graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
// カメラ
var cameraLookAtVector = Vector3.Zero;
var cameraUpVector = Vector3.UnitZ;
_effect.View = Matrix.CreateLookAt(_cameraPosition, cameraLookAtVector, cameraUpVector);
float aspectRatio = _graphics.PreferredBackBufferWidth / (float)_graphics.PreferredBackBufferHeight;
float fieldOfView = Microsoft.Xna.Framework.MathHelper.PiOver4;
float nearClipPlane = 1;
float farClipPlane = 200;
_effect.Projection = Matrix.CreatePerspectiveFieldOfView(fieldOfView, aspectRatio, nearClipPlane, farClipPlane);
// 描画
foreach (var pass in _effect.CurrentTechnique.Passes)
{
pass.Apply();
_graphics.GraphicsDevice.DrawUserPrimitives(
PrimitiveType.TriangleList,
_vertices,
vertexOffset: 0,
primitiveCount: _vertices.Length / 3);
};
base.Draw(gameTime);
}
}
}