在monogame中克隆和绘制对象
Posted
技术标签:
【中文标题】在monogame中克隆和绘制对象【英文标题】:Cloning and drawing Objects in monogame 【发布时间】:2021-12-18 08:47:27 【问题描述】:我如何克隆一个对象,然后选择一个随机位置,然后绘制它。
这是我的对象代码:
public class Trash : ICloneable
private Texture2D _texture;
private float _rotation;
public Vector2 Position;
public Vector2 Origin;
public float RotationVelocity = 3f;
public float LinearVelocity = 4f;
public Trash(Texture2D texture)
_texture = texture;
public void Update()
// Do epic stuff here
public void Draw(SpriteBatch spriteBatch)
spriteBatch.Draw(_texture, Position, null, Color.White, _rotation, Origin, 1, SpriteEffects.None, 0f);
public object Clone()
return this.MemberwiseClone();
这是我目前在 Game1.cs 中的代码:
public class Game1 : Game
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
private SeaJam.Objects.Trash Trash;
public Game1()
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
// TODO: Add your initialization logic here
base.Initialize();
protected override void LoadContent()
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
var texture = Content.Load<Texture2D>("Prototype");
Trash = new Objects.Trash(texture)
Position = new Vector2(100, 100),
Origin = new Vector2(texture.Width / 2, texture.Height - 25),
;
protected override void Update(GameTime gameTime)
Trash.Update();
base.Update(gameTime);
protected override void Draw(GameTime gameTime)
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
Trash.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
private void AddTrash()
var rnd = new System.Random();
var NewTrash = Trash.Clone();
问题是每当我尝试在 AddTrash() 方法中为克隆提供随机位置时,我只会得到错误,例如“'object'不包含'Position'的定义并且没有可以找到接受“object”类型的第一个参数的可访问扩展方法“Position”(您是否缺少 using 指令或程序集引用?)”
【问题讨论】:
【参考方案1】:你的构造函数:
public Trash(Texture2D texture)
_texture = texture;
需要使用所需的可变参数进行扩展。在您的情况下,它需要添加Position
和Origin
作为参数,然后将其作为值应用。
像这样:
public Trash(Texture2D texture, Vector2 position, Vector2 origin)
_texture = texture;
Position = position;
Origin = origin;
还要改变你在 game1.cs 中的调用方式,它们需要像 texture
一样工作:
var texture = Content.Load<Texture2D>("Prototype");
var position = new Vector2(100, 100),
var origin = new Vector2(texture.Width / 2, texture.Height - 25),
Trash = new Objects.Trash(texture, position, origin);
作为提示:保持字段名称的一致性,在一个字段中混合下划线和小写字母,而在另一个字段中混合使用大写字母会让人难以理解。特别是当参数也需要与字段不同的名称时。我更喜欢将它们全部保留第一个字母大写。
【讨论】:
以上是关于在monogame中克隆和绘制对象的主要内容,如果未能解决你的问题,请参考以下文章
使用 XNA/Monogame 从 spritesheet 中绘制一个 sprite