Scaling the model

Page update date :
Page creation date :

summary

Perform a scale transformation to change the scale of the model.

モデルの拡大縮小

Operating environment

Prerequisites

Supported XNA Versions
  • 4.0
Supported Platforms
  • Windows (XP SP2 or later, Vista, 7)
  • Xbox 360
  • Windows Phone 7
Windows Required Vertex Shader Version 2.0
Windows Required Pixel Shader Version 2.0

Operating environment

platform
  • Windows 7
  • Xbox 360
  • Windows Phone 7 Emulator

How to work with the sample

Works keyboardXbox 360 controllermouse touch
Scaling the model ↑↓←→ Left Stick Left button (auto-scaling, movement switching) -

substance

field

Because scaling can be changed for XYZ, a Vector3 structure is used. Since the original size is (1, 1, 1), it is initialized with "Vector3.One".

/// <summary>
/// モデルのスケール
/// </summary>
private Vector3 scale = Vector3.One;

Scaling the model

Use the keyboard, mouse, or gamepad to change the scale of the model. By the way, the calculation of the scale is appropriate. (The code below is excerpted only from the operation part with the gamepad)

GamePadState gamePadState = GamePad.GetState(PlayerIndex.One);

// ゲームパッドによるモデルの拡大縮小操作
if (gamePadState.IsConnected)
{
    this.scale.X = gamePadState.ThumbSticks.Left.X + 1.0f;
    this.scale.Z = gamePadState.ThumbSticks.Left.Y + 1.0f;
}

Scale Transformations

You can create a scale matrix by passing a Vector3 parameter, which is the scale information, to the "Matrix.CreateScale" method. You can scale the model by setting it to the "BasicEffect.World" effect of the model.

foreach (ModelMesh mesh in this.model.Meshes)
{
    // モデルのスケールを設定
    foreach (BasicEffect effect in mesh.Effects)
    {
        effect.World = Matrix.CreateScale(this.scale);
    }

    // モデルを描画
    mesh.Draw();
}

Matrix.CreateScale method

Create a scale matrix.

scales Vector3 Scale for each XYZ axis
Return Values Matrix Scale matrix

All Codes

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 ScalingModel
{
    /// <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 scale = Vector3.One;

        /// <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, 10.0f, 5.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) % 3;
            }
            this.isMousePressed = mouseState.LeftButton == ButtonState.Pressed;
            
            // キーボードによるモデルの拡大縮小操作
            if (keyState.IsKeyDown(Keys.Left))
            {
                this.scale.X /= 1.1f;
            }
            if (keyState.IsKeyDown(Keys.Right))
            {
                this.scale.X *= 1.1f;
            }
            if (keyState.IsKeyDown(Keys.Up))
            {
                this.scale.Z *= 1.1f;
            }
            if (keyState.IsKeyDown(Keys.Down))
            {
                this.scale.Z /= 1.1f;
            }
            if (this.autoMode == 1)
            {
                this.scale.X = (float)(Math.Sin(gameTime.TotalGameTime.TotalSeconds) + 1);
            }
            if (this.autoMode == 2)
            {
                this.scale.Z = (float)(Math.Sin(gameTime.TotalGameTime.TotalSeconds) + 1);
            }

            // ゲームパッドによるモデルの拡大縮小操作
            if (gamePadState.IsConnected)
            {
                this.scale.X = gamePadState.ThumbSticks.Left.X + 1.0f;
                this.scale.Z = gamePadState.ThumbSticks.Left.Y + 1.0f;
            }
            
            // 登録された GameComponent を更新する
            base.Update(gameTime);
        }

        /// <summary>
        /// 描画処理を行うメソッド
        /// </summary>
        /// <param name="gameTime">このメソッドが呼ばれたときのゲーム時間</param>
        protected override void Draw(GameTime gameTime)
        {
            // 画面を指定した色でクリアします
            this.GraphicsDevice.Clear(Color.CornflowerBlue);

            foreach (ModelMesh mesh in this.model.Meshes)
            {
                // モデルのスケールを設定
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.World = Matrix.CreateScale(this.scale);
                }

                // モデルを描画
                mesh.Draw();
            }

            // スプライトの描画準備
            this.spriteBatch.Begin();

            // テキストをスプライトとして描画する
            this.spriteBatch.DrawString(this.font,
                "X:" + this.scale.X.ToString() + Environment.NewLine +
                "Y:" + this.scale.Y.ToString() + Environment.NewLine +
                "Z:" + this.scale.Z.ToString() + Environment.NewLine +
                "MousePressAutoMode : " + this.autoMode,
                new Vector2(50, 50), Color.White);

            // スプライトの一括描画
            this.spriteBatch.End();

            // 登録された DrawableGameComponent を描画する
            base.Draw(gameTime);
        }
    }
}