MonoGameでマウスを使用する

提供: MonoBook
ナビゲーションに移動 検索に移動

MonoGameマウスを使用する。 主にMouseクラスのGetStateメソッドを使ったサンプル。マウスで「ぷにコン」みたいのを表示してみる。少し改造して TouchPanelクラスに置き換えればAndroidなどでぷにコンもどきになると思われる。

このサンプルではC3.MonoGame.Primitives2Dを使用し、そのSpriteBatchクラス拡張メソッド群で円や直線の描画を行っている。 C3.MonoGame.Primitives2DにNuGetパッケージはないのでGitHubからソースコードをダウンロードして入れよう。


using System;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;

using C3.MonoGame;

namespace MonoGameSamples
{
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Vector2? startPosition = null;
        Vector2? deltaPosition = null;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        protected override void Initialize()
        {
            // マウスカーソルを表示する
            this.IsMouseVisible = true;

            base.Initialize();
        }

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
        }

        protected override void Update(GameTime gameTime)
        {

#if !__IOS__ && !__TVOS__
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();
#endif

            var mouse = Mouse.GetState();
            if (mouse.LeftButton == ButtonState.Pressed)
            {
                if (startPosition == null)
                {// ドラッグ開始
                    startPosition = mouse.Position.ToVector2();
                }
                else
                {// ドラッグ中
                    deltaPosition = mouse.Position.ToVector2();
                }
            }
            else
            {
                startPosition = null;
                deltaPosition = null;
            }


            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            graphics.GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();
            {
                if (startPosition != null)
                {// 始点描画
                    spriteBatch.DrawCircle(startPosition.Value, 20, 16, Color.Red);
                }

                if (deltaPosition != null)
                {// 現在点描画
                    spriteBatch.DrawLine(startPosition.Value, deltaPosition.Value, Color.White);
                    spriteBatch.DrawCircle(deltaPosition.Value, 20, 16, Color.Red);
                }
            }
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}

関連項目