행렬 곱셈
페이지 업데이트 :
페이지 생성 날짜 :
요약
이동, 회전 및 크기 조정을 곱하여 행렬을 생성하고 모델을 조작합니다. 샘플에서 상자의 빨간색 면이 앞면으로 작동됩니다.
운영 환경
필수 구성 요소
지원되는 XNA 버전 |
|
지원되는 플랫폼 |
|
Windows 필수 버텍스 셰이더 버전 | 2.0 |
Windows 필수 픽셀 셰이더 버전 | 2.0 |
운영 환경
플랫폼 |
|
샘플로 작업하는 방법
작동 키보드Xbox | 360 컨트롤러마우스 | 터치 | ||
---|---|---|---|---|
모델 이동(모델이 향하는 방향으로 앞, 뒤로 이동) | ↑↓ | 왼쪽 스틱(Y) | 왼쪽 버튼(자동 이동, 이동 전환) | - |
모델을 회전합니다. | ←→ | 왼쪽 스틱(X) | 왼쪽 버튼(자동 회전, 이동 전환) | - |
모델 크기 조정 | ᅡ, Z | 오른쪽 스틱(Y) | 왼쪽 버튼(자동 크기 조정, 이동 전환) | - |
물질
밭
샘플은 모델을 이동, 회전 및 배율 조정합니다. 여러 작업이 수행되기 때문에 단순화를 위해 이동은 X, 회전은 Z, 회전은 Y축만, 스케일은 X, Y, Z입니다.
<summary>
モデルの位置
</summary>
private Vector3 position = Vector3.Zero;
<summary>
モデルの回転(radian)
</summary>
private float rotate = 0.0f;
<summary>
モデルのスケール
</summary>
private float scale = 1.0f;
모델 작업
Game.Update 메서드는 입력 정보에서 각 매개 변수를 조작합니다. 이 경우 각 필드의 값만 변경하면 됩니다. (아래 코드는 게임패드를 사용한 조작 부분에서만 발췌한 것입니다.)
GamePadState gamePadState = GamePad.GetState(PlayerIndex.One);
// 拡大縮小 /////
// ゲームパッドによるモデルの拡大縮小
if (gamePadState.IsConnected)
{
this.scale = gamePadState.ThumbSticks.Right.Y + 1.0f;
}
// 回転 /////
// ゲームパッドによる回転
if (gamePadState.IsConnected)
{
this.rotate -= gamePadState.ThumbSticks.Left.X * 0.1f;
}
// 移動 /////
// 進むべき方向
Vector3 frontDirection =
Vector3.TransformNormal(Vector3.UnitZ, Matrix.CreateRotationY(this.rotate));
// ゲームパッドによるモデルの移動操作
if (gamePadState.IsConnected)
{
this.position += gamePadState.ThumbSticks.Left.Y * frontDirection * 0.1f;
}
이동할 때 이동해야 하는 방향은 현재 회전량에 따라 결정됩니다.
벡터가 회전하지 않을 때 이동 방향을 (0, 0, 1)으로 설정하고 이 벡터에 회전 행렬을 곱하여 "Vector3.TransformNormal" 메서드를 사용하여 회전할 수 있습니다. 구하는 벡터는 "단위 벡터"이기 때문에 이동량을 곱하면 향하는 방향으로 전진할 수 있습니다.
Vector3.TransformNormal
메서드
좌표: 3D 벡터가 행렬에 의해 변환됩니다.
보통 | 벡터3 | 소스 벡터 |
행렬 | 행렬 | 좌표 변환 행렬 |
반환 값 | 벡터3 | 좌표 변환이 있는 단위 벡터 |
좌표 변환
각 파라미터를 기반으로 행렬을 만듭니다. 이러한 행렬을 곱하면 여러 변환을 적용할 수 있습니다. 덧셈이 아니므로 양해 바랍니다.
곱해지는 순서도 고정되어 있다는 점에 유의해야 합니다. 기본적으로 "스케일", "회전", "이동"의 순서로 곱하는 것이 일반적입니다. 순서를 변경할 수도 있지만 결과는 다릅니다. 프로그램을 직접 수정하여 시도해 보십시오.
// 座標変換の初期化
Matrix transform = Matrix.Identity;
// 拡大縮小
transform *= Matrix.CreateScale(this.scale);
// 回転
transform *= Matrix.CreateRotationY(this.rotate);
// 移動
transform *= Matrix.CreateTranslation(this.position);
foreach (ModelMesh mesh in this.model.Meshes)
{
// 座標変換を設定
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = transform;
}
// モデルを描画
mesh.Draw();
}
모든 코드
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 TransformWorldMatrix
{
<summary>
ゲームメインクラス
</summary>
public class GameMain : Microsoft.Xna.Framework.Game
{
<summary>
グラフィックデバイス管理クラス
</summary>
private GraphicsDeviceManager graphics = null;
<summary>
スプライトのバッチ化クラス
</summary>
private SpriteBatch spriteBatch = null;
<summary>
スプライトでテキストを描画するためのフォント
</summary>
private SpriteFont font = null;
<summary>
モデル
</summary>
private Model model = null;
<summary>
モデルの位置
</summary>
private Vector3 position = Vector3.Zero;
<summary>
モデルの回転(radian)
</summary>
private float rotate = 0.0f;
<summary>
モデルのスケール
</summary>
private float scale = 1.0f;
<summary>
自動動作フラグ
</summary>
private int autoMode = 0;
<summary>
マウスボタン押下フラグ
</summary>
private bool isMousePressed = false;
<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.font = this.Content.Load<SpriteFont>("Font");
// モデルを作成
this.model = this.Content.Load<Model>("Model");
// 今回はパラメータをあらかじめ設定しておく
foreach (ModelMesh mesh in this.model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
// デフォルトのライト適用
effect.EnableDefaultLighting();
// ビューマトリックスをあらかじめ設定
effect.View = Matrix.CreateLookAt(
new Vector3(0.0f, 20.0f, 2.0f),
Vector3.Zero,
Vector3.Up
);
// プロジェクションマトリックスをあらかじめ設定
effect.Projection = Matrix.CreatePerspectiveFieldOfView(
MathHelper.ToRadians(45.0f),
(float)this.GraphicsDevice.Viewport.Width /
(float)this.GraphicsDevice.Viewport.Height,
1.0f,
100.0f
);
}
}
}
<summary>
ゲームが終了するときに一回だけ呼ばれ
すべてのゲームコンテンツをアンロードします
</summary>
protected override void UnloadContent()
{
// TODO: ContentManager で管理されていないコンテンツを
// ここでアンロードしてください
}
<summary>
描画以外のデータ更新等の処理を行うメソッド
主に入力処理、衝突判定などの物理計算、オーディオの再生など
</summary>
<param name="gameTime">このメソッドが呼ばれたときのゲーム時間</param>
protected override void Update(GameTime gameTime)
{
KeyboardState keyState = Keyboard.GetState();
MouseState mouseState = Mouse.GetState();
GamePadState gamePadState = GamePad.GetState(PlayerIndex.One);
// Xbox 360 コントローラ、Windows Phone の BACK ボタンを押したときに
// ゲームを終了させます
if (gamePadState.Buttons.Back == ButtonState.Pressed)
{
this.Exit();
}
// マウスによる自動動作切り替え
if (this.isMousePressed == false &&
mouseState.LeftButton == ButtonState.Pressed)
{
this.isMousePressed = true;
this.autoMode = (this.autoMode + 1) % 4;
}
this.isMousePressed = mouseState.LeftButton == ButtonState.Pressed;
// 拡大縮小 /////
// キーボードによる拡大縮小
if (keyState.IsKeyDown(Keys.A))
{
this.scale *= 1.01f;
}
if (keyState.IsKeyDown(Keys.Z))
{
this.scale /= 1.01f;
}
// ゲームパッドによるモデルの拡大縮小
if (gamePadState.IsConnected)
{
this.scale = gamePadState.ThumbSticks.Right.Y + 1.0f;
}
if (this.autoMode == 1)
{
this.scale = (float)(Math.Sin(gameTime.TotalGameTime.TotalSeconds) + 1);
}
// 回転 /////
// キーボードによる回転
if (keyState.IsKeyDown(Keys.Left))
{
this.rotate += 0.1f;
}
if (keyState.IsKeyDown(Keys.Right))
{
this.rotate -= 0.1f;
}
// ゲームパッドによる回転
if (gamePadState.IsConnected)
{
this.rotate -= gamePadState.ThumbSticks.Left.X * 0.1f;
}
if (this.autoMode == 2)
{
this.rotate += (float)gameTime.ElapsedGameTime.TotalSeconds;
}
// 移動 /////
// 進むべき方向
Vector3 frontDirection =
Vector3.TransformNormal(Vector3.UnitZ, Matrix.CreateRotationY(this.rotate));
// キーボードによるモデルの移動操作
if (keyState.IsKeyDown(Keys.Up))
{
this.position += frontDirection * 0.1f;
}
if (keyState.IsKeyDown(Keys.Down))
{
this.position -= frontDirection * 0.1f;
}
// ゲームパッドによるモデルの移動操作
if (gamePadState.IsConnected)
{
this.position += gamePadState.ThumbSticks.Left.Y * frontDirection * 0.1f;
}
if (this.autoMode == 3)
{
this.position += frontDirection * (float)(Math.Sin(gameTime.TotalGameTime.TotalSeconds)) * 0.1f;
}
// 登録された GameComponent を更新する
base.Update(gameTime);
}
<summary>
描画処理を行うメソッド
</summary>
<param name="gameTime">このメソッドが呼ばれたときのゲーム時間</param>
protected override void Draw(GameTime gameTime)
{
// 画面を指定した色でクリアします
this.GraphicsDevice.Clear(Color.CornflowerBlue);
// 座標変換の初期化
Matrix transform = Matrix.Identity;
// 拡大縮小
transform *= Matrix.CreateScale(this.scale);
// 回転
transform *= Matrix.CreateRotationY(this.rotate);
// 移動
transform *= Matrix.CreateTranslation(this.position);
foreach (ModelMesh mesh in this.model.Meshes)
{
// 座標変換を設定
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = transform;
}
// モデルを描画
mesh.Draw();
}
// スプライトの描画準備
this.spriteBatch.Begin();
// テキストをスプライトとして描画する
this.spriteBatch.DrawString(this.font,
"[Position]" + Environment.NewLine +
" X:" + this.position.X.ToString() + Environment.NewLine +
" Y:" + this.position.Y.ToString() + Environment.NewLine +
" Z:" + this.position.Z.ToString() + Environment.NewLine +
"[Rotate]" + Environment.NewLine +
" " + this.rotate.ToString() + Environment.NewLine +
"[Scale]" + Environment.NewLine +
" " + this.scale.ToString() + Environment.NewLine +
"MousePressAutoMode : " + this.autoMode,
new Vector2(50, 50), Color.White);
// スプライトの一括描画
this.spriteBatch.End();
// 登録された DrawableGameComponent を描画する
base.Draw(gameTime);
}
}
}