当我启动应用程序时,对象会在给定位置(给定向量)产生。但是当我最小化monogame窗口并重新打开它时,对象就在左上角。
为什么会这样?
注意:这是我的Draw
方法:
public virtual void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
// Position is the object position
spriteBatch.Draw(textureImage, position, new Rectangle(
(currentFrame.X * frameSize.X),
(currentFrame.Y * frameSize.Y),
frameSize.X, frameSize.Y),
Color.White, 0, Vector2.Zero, 2, SpriteEffects.None, 0);
}
如何计算起始位置:
// Vector2 position is the starting position for the object
public PlayerMovement(Texture2D textureImage, Vector2 position, Point frameSize, int collisionOffSet, Point currentFrame, Point startFrame, Point sheetSize, float speed, float speedMultiplier, float millisecondsPerFrame)
: base(textureImage, position, frameSize, collisionOffSet, currentFrame, startFrame, sheetSize, speed, speedMultiplier, millisecondsPerFrame)
{
children = new List<Sprite>();
}
我使用Vector2 direction
来了解精灵面向的方向:
public abstract Vector2 direction
{
get;
}
我在get
课程中使用PlayerMovement
并返回inputDirection * speed
(inputDirection
是Vector2
)
最后,在我的Update
方法中,position += direction
我还会检查播放器是否触摸屏幕边框(他无法移出屏幕)。 )。
答案 0 :(得分:1)
根据我自己的经验,在Game.Window.ClientBounds
调用中使用Update
会导致窗口最小化时出现问题。以下是我项目中的一些示例代码:
Rectangle gdm = Game.Window.ClientBounds;
if (DrawLocation.X < 0) DrawLocation = new Vector2(0, DrawLocation.Y);
if (DrawLocation.Y < 0) DrawLocation = new Vector2(DrawLocation.X, 0);
if (DrawLocation.X > gdm.Width - DrawAreaWithOffset.Width) DrawLocation = new Vector2(gdm.Width - DrawAreaWithOffset.Width, DrawLocation.Y);
if (DrawLocation.Y > gdm.Height - DrawAreaWithOffset.Height) DrawLocation = new Vector2(DrawLocation.X, gdm.Height - DrawAreaWithOffset.Height);
我在最小化时遇到的问题是Game.Window.ClientBounds在-32000
附近返回了一些宽度/高度。这将在恢复窗口时将我的游戏对象重置为某个默认位置。我通过首先检查ClientBounds Width
和Height
是否大于零来修复它:
Rectangle gdm = Game.Window.ClientBounds;
if (gdm.Width > 0 && gdm.Height > 0) //protect when window is minimized
{
if (DrawLocation.X < 0)
DrawLocation = new Vector2(0, DrawLocation.Y);
if (DrawLocation.Y < 0)
DrawLocation = new Vector2(DrawLocation.X, 0);
if (DrawLocation.X > gdm.Width - DrawAreaWithOffset.Width)
DrawLocation = new Vector2(gdm.Width - DrawAreaWithOffset.Width, DrawLocation.Y);
if (DrawLocation.Y > gdm.Height - DrawAreaWithOffset.Height)
DrawLocation = new Vector2(DrawLocation.X, gdm.Height - DrawAreaWithOffset.Height);
}
作为参考,这里有diff of changes修复了我自己项目的最小化问题。
当游戏不是主要的活动窗口时,我正在进行与游戏交互的单独错误。您还可以在Game.IsActive
和Update
来电的开头添加Draw
支票:
public override void Update(GameTime gt)
{
if(!IsActive) return;
//etc...
}
或者如果使用游戏组件,您的组件更新/绘制将如下所示:
public override void Update(GameTime gt)
{
if(!Game.IsActive) return;
//etc...
}