2015-06-13 80 views
0

我在C#和XNA 4.0中制作游戏。它已经完成了,但现在我想添加设置,以便玩家可以根据需要更改窗口大小。目前的设置是这样的:如何缩放游戏的图形?

void Initialize() 
{ 
    //The window size is initally 800x480 
    graphics.PreferredBackBufferWidth = 800; 
    graphics.PreferredBackBufferHeight = 480; 
    graphics.ApplyChanges(); 
} 

void Update() 
{ 
    //If the player completes an action, the window size is changed 
    if (windowSizeChanged) 
    { 
     graphics.PreferredBackBufferWidth = 1024; 
     graphics.PreferredBackBufferHeight = 720; 
     graphics.ApplyChanges(); 
    } 
} 

使用此代码,这是本场比赛的样子在具体决议:

800X480 enter image description here

1024x720 enter image description here

,你可以希望看到,当窗口大小发生变化时,它不会影响游戏的实际图形。所有对象的精灵和hitbox保持相同的大小,所以他们在屏幕的角落里填满了一个小盒子,而不是整个窗口。任何人都可以告诉我如何缩放精灵以填满窗口?我认为我需要使用某种矩阵,但任何人都可以指出我的方向?

编辑:

这里是绘制代码。

void Draw(GameTime gameTime) 
{ 
    GraphicsDevice.Clear(Color.CornflowerBlue); 

    base.Draw(gameTime); 

    spriteBatch.Begin(); 

    //Background texture drawn at default window size 
    spriteBatch.Draw(background, new Rectangle(0, 0, 800, 480), Color.White); 

    //Each object in the level (player, block, etc.) is drawn with a specific texture and a rectangle variable specifying the size and coordinates 
    //E.g. Each block is a size of 64x64 pixels and in this level they are placed at X-coordinates 0, 64, 128 and so on 
    //Each Y-coordinate for the blocks in this level is '480 - 64' (Window height minus block height) 
    foreach (/*Object in level*/) 
    { 
     spriteBatch.Draw(object.Texture, object.TextureSize, Color.White); 
    } 

    spriteBatch.End(); 
} 
+0

发布您的视口代码并绘制调用。 – RadioSpace

+0

您可能会喜欢这篇文章:http://www.david-amador.com/2010/03/xna-2d-independent-resolution-rendering/ –

回答

1

默认情况下,SpriteBatch假定您的世界空间与客户端空间相同,即客户端空间,即窗口的大小。你可以阅读关于SpriteBatch和不同的空间in a post by Andrew Russell

当您调整backbuffer的大小时,窗口大小也会随着它改变世界空间而改变(你不想要)。为了不允许这样做,你应该在变换管道之间插入一个变换矩阵来进行修正。

SpriteBatch.Begin准确地说,在one of its overloads

有很多方法可以实现缩放,但我认为你想要统一缩放,这意味着当长宽比与初始宽高比相比变化时,精灵不会被拉长。以下代码将根据初始屏幕高度调整缩放比例。

... 

const float initialScreenHeight = 480f; 
Matrix transform = Matrix.CreateScale(GraphicsDevice.Viewport.Height/viewportHeightInWorldSpace); 

spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, transform); 

... 

注意,改变分辨率时,使得相对于初始纵横比的纵横比的变化,你会遇到的问题,如拉出屏幕的(向右),或在的右边缘不拉丝屏幕(获得与当前类似的蓝色背景)。

此外,您不希望在Draw方法的每一帧中计算该缩放矩阵,但仅在分辨率发生变化时才计算。