如何在 MonoGame 中绘制形状,例如矩形和圆形,而无需将预先绘制的形状保存在 Content 文件夹中?
DrawRectangle() 和 DrawEllipse() 用于 Windows 窗体,在我使用的 OpenGL 中不起作用。
如何在 MonoGame 中绘制形状,例如矩形和圆形,而无需将预先绘制的形状保存在 Content 文件夹中?
DrawRectangle() 和 DrawEllipse() 用于 Windows 窗体,在我使用的 OpenGL 中不起作用。
这是一个带有解释的简单示例
我定义了一个 10x10 的矩形并设置了世界矩阵,使它看起来像一个 2D 投影:
注意:这BasicEffect
是吸引您的原语的原因
protected override void LoadContent()
{
_vertexPositionColors = new[]
{
new VertexPositionColor(new Vector3(0, 0, 1), Color.White),
new VertexPositionColor(new Vector3(10, 0, 1), Color.White),
new VertexPositionColor(new Vector3(10, 10, 1), Color.White),
new VertexPositionColor(new Vector3(0, 10, 1), Color.White)
};
_basicEffect = new BasicEffect(GraphicsDevice);
_basicEffect.World = Matrix.CreateOrthographicOffCenter(
0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 0, 1);
}
然后我画了整个东西:D
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
EffectTechnique effectTechnique = _basicEffect.Techniques[0];
EffectPassCollection effectPassCollection = effectTechnique.Passes;
foreach (EffectPass pass in effectPassCollection)
{
pass.Apply();
GraphicsDevice.DrawUserPrimitives(PrimitiveType.LineStrip, _vertexPositionColors, 0, 4);
}
base.Draw(gameTime);
}
你有你的矩形!
现在这只是冰山一角,
或者如上面的一篇文章中所述,您可以使用着色器来代替......
不久前我需要画一个超椭圆,最后画了这个着色器:
正如您在帖子中看到的那样,Superellipse 不仅可以绘制椭圆,还可以绘制其他形状,甚至可能是圆形(我没有测试过),所以您可能会对它感兴趣。
最终你会想要一些类/方法来隐藏所有这些细节,所以你只需要调用类似DrawCircle()
.
提示:通过发布@https: //gamedev.stackexchange.com/,您可能会获得更多与 Monogame 相关的问题的答案
:D
如果您需要在 2D 中创建一个矩形,您可以这样做:
Color[] data = new Color[rectangle.Width * rectangle.Height];
Texture2D rectTexture = new Texture2D(GraphicsDevice, rectangle.Width, rectangle.Height);
for (int i = 0; i < data.Length; ++i)
data[i] = Color.White;
rectTexture.SetData(data);
var position = new Vector2(rectangle.Left, rectangle.Top);
spriteBatch.Draw(rectTexture, position, Color.White);
在某些情况下,可能比 Aybe 的回答容易一点。这将创建一个实心矩形。
我找到了一个绘制填充和非填充形状的简单解决方案,我不知道它是否耗电,但无论如何它是这样的:
{
//Filled
Texture2D _texture;
_texture = new Texture2D(graphicsDevice, 1, 1);
_texture.SetData(new Color[] { Color.White });
spriteBatch.Draw(_texture, Rect, Color.White);
}
{
//Non filled
Texture2D _texture;
_texture = new Texture2D(graphicsDevice, 1, 1);
_texture.SetData(new Color[] { Color.White });
spriteBatch.Draw(_texture, new Rectangle(Rect.Left, Rect.Top, Rect.Width, 1), Color.White);
spriteBatch.Draw(_texture, new Rectangle(Rect.Right, Rect.Top, 1, Rect.Height), Color.White);
spriteBatch.Draw(_texture, new Rectangle(Rect.Left, Rect.Bottom, Rect.Width, 1), Color.White);
spriteBatch.Draw(_texture, new Rectangle(Rect.Left, Rect.Top, 1, Rect.Height), Color.White);
}