摘要:
我們知道在windows phone 7中xna遊戲預設的幀頻是30fps(pc和xbox360中是60fps),可是實際遊戲開發過程中這個值未必都能滿足我們的需求。下面我們就一塊看一下在xna遊戲開發過程中如何調整遊戲的速度。
内容:
在game類中有一個屬性targetelapsedtime,用來表示每一幀之間的時間間隔,例如預設為1/30秒,也就是幀頻為30fps。如果仔細看一下你會發現在vs自動生成的game1類的構造函數中給targetelapsedtime屬性指派為timespan.fromticks(333333) ,也就是時間間隔為 0.0333… 秒,幀頻 30fps 。既然如此我們就可以修改這個值達到我們想要的結果,例如我們修改為 333333*2 就可以将速度放慢一倍(當然也可以不使用刻度為機關,例如使用 timespan.fromseconds(1/15) )。
這種方法看似可行,但是多數情況下我們沒有辦法這麼做,因為如果修改了targetelapsedtime屬性就表示整個遊戲的幀頻都進行了修改。通常遊戲中不可能都是某種固定幀頻,一般都是遊戲中有些元素運動得快,有些元素運動的慢,是以很難用某種統一的速度來設定。這個時候我們怎麼辦呢?
我們知道遊戲的動畫速度取決于update中動态變量變化的程度,如果我們可以控制變量的變化速度就可以修改遊戲的速度。此時我們注意到update方法有一個gametime類型的參數,它有一個屬性elapsedgametime ,表示從上一幀到這一幀的時間間隔。有了它我們隻需要設定一個變量用來記錄時間間隔,隻有間隔到達我們需要的值時才在update中修改動态變量,這樣的話就可以變形的修改動畫速度了。例如下面一個通過動态更改圖檔來形成動畫效果demo(圖檔在對應的content中,分别為1.png、2.png、3.png、4.png、5.png),原來的代碼如下:

using system;
using system.collections.generic;
using system.linq;
using microsoft.xna.framework;
using microsoft.xna.framework.audio;
using microsoft.xna.framework.content;
using microsoft.xna.framework.gamerservices;
using microsoft.xna.framework.graphics;
using microsoft.xna.framework.input;
using microsoft.xna.framework.input.touch;
using microsoft.xna.framework.media;
namespace windowsphonegamedemo
{
public class game1 : microsoft.xna.framework.game
graphicsdevicemanager graphics;
spritebatch spritebatch;
dictionary<int, texture2d> dicimgs = new dictionary<int, texture2d>();
texture2d currentimg = null;
int index = 1;
public game1()
graphics = new graphicsdevicemanager(this);
content.rootdirectory = "content";
targetelapsedtime = timespan.fromticks(333333);//此處可修改全局幀頻
}
protected override void initialize()
base.initialize();
currentimg = dicimgs[1];//設定預設值
protected override void loadcontent()
spritebatch = new spritebatch(graphicsdevice);
for (int i = 1; i <= 4; ++i)
dicimgs.add(i, this.content.load<texture2d>(i.tostring()));
protected override void unloadcontent()
protected override void update(gametime gametime)
if (gamepad.getstate(playerindex.one).buttons.back == buttonstate.pressed)
this.exit();
if (index > 4)
index = 1;
currentimg = dicimgs[index];
index++;
base.update(gametime);
protected override void draw(gametime gametime)
graphicsdevice.clear(color.cornflowerblue);
spritebatch.begin();
spritebatch.draw(currentimg,new vector2(320,135), color.white);
spritebatch.end();
base.draw(gametime);

經過修改後:

int timesincelastframe = 0;//記錄更新間隔
int millisecondsperframe = 330;//設定時間間隔
timesincelastframe += gametime.elapsedgametime.milliseconds;
if (millisecondsperframe <= timesincelastframe)//隻有小于等于指定的時間間隔才進行圖檔切換
timesincelastframe -= millisecondsperframe;

下面我們對比一下這個動畫的修改前後的效果:
ok,今天就到這裡吧!