最小化时位置复位

时间:2015-11-03 17:15:29

标签: c# monogame

当我启动应用程序时,对象会在给定位置(给定向量)产生。但是当我最小化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

inputDirectionVector2

最后,在我的Update方法中,position += direction我还会检查播放器是否触摸屏幕边框(他无法移出屏幕)。 )。

1 个答案:

答案 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 WidthHeight是否大于零来修复它:

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.IsActiveUpdate来电的开头添加Draw支票:

public override void Update(GameTime gt)
{
    if(!IsActive) return;
    //etc...
}

或者如果使用游戏组件,您的组件更新/绘制将如下所示:

public override void Update(GameTime gt)
{
    if(!Game.IsActive) return;
    //etc...
}