MonoGameで直線を描画する

提供: MonoBook
2019年7月11日 (木) 05:05時点における124.87.119.49 (トーク)による版
ナビゲーションに移動 検索に移動

MonoGameに限らずMetalVulkanWebGLもそうだが最近は何でもかんでもシェーダーでやる風潮だ。たかだか直線を引くだけでもシェーダーを叩けとか面倒くさすぎだろ。

スプライトを引き伸ばす

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

関連項目