メインメニューを開く

差分

MonoGameでマウスを使用する

3,088 バイト追加, 2017年11月22日 (水) 07:52
ページの作成:「MonoGameでマウスを使用する。 主にMouseクラスのGetStateメソッドを使ったサンプル。 このサンプルではC3.MonoGame.Primitives2Dを使用...」
MonoGameでマウスを使用する。
主にMouseクラスのGetStateメソッドを使ったサンプル。

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


<source>
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);
}
}
}
</source>

== 関連項目 ==
* [[MonoGameでマウスカーソルを表示する]]

[[category: MonoGame]]
匿名利用者