MonoGameで直線を描画する
スプライトを引き伸ばす
MonoGameには昔ながらの「スプライト」の概念があるので「1ピクセルのスプライト(1ピクセルのテクスチャ)を作って引き伸ばす」という手法が使える。
public static void DrawLine(this SpriteBatch spriteBatch, Vector2 point1, Vector2 point2, Color color, flaot thickness = 1)
{
// 1ピクセルのテクスチャを用意しておく
var pixel = new Texture2D(spriteBatch.GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
pixel.SetData(new[] { Color.White });
// 2点間の距離と角度を求める
var length = = Vector2.Distance(point1, point2);
var angle = (float)Math.Atan2(point2.Y - point1.Y, point2.X - point1.X);
// 描画する
spriteBatch.Draw(
texture: pixel,
position: point,
sourceRectangle: null,
color: color,
rotation: angle,
origin: Vector2.Zero,
scale: new Vector2(length, thickness),
effect: SpriteEffects.None,
layerDepth: 0);
}