フレームレート設定
携帯端末向けの設定
固定ステップと可変ステップで解説したように、Update() メソッドと Draw() メソッドが呼び出されるフレームの更新間隔を設定できます。ハイエンドな環境である Windows PC や Xbox 360 向けのゲームであれば 60 FPS が標準ですが、パフォーマンスが限られ省電力が求められる小型の携帯端末では 30 FPS が標準的です。ゲーム起動時に Game オブジェクトの TargetElapsedTime プロパティを 1000 / 30 ミリ秒(33.3 ミリ秒)に設定してください。
TargetElapsedTime = new TimeSpan(333333);
また Windows Phone のようた携帯電話は、ゲーム実行中であっても電話がかかってくるなどの通知によって他のアプリケーションに移行する可能性が常にあります。「スタートボタン」を押す、他のアプリケーションが起動されるといった操作でゲームが中断されても、通常はプロセスが直ちに終了することはありません。
中断されたアプリケーションは非アクティブ状態になり、「戻る」ボタンなどで再びアクティブに戻されます。非アクティブの状態では画面には表示されませんが、メモリ上にはプロセスがそのまま残されています。非アクティブな状態ではフレームを頻繁に更新する必要はないので InactiveSleepTime プロパティの値を変更しましょう。
InactiveSleepTime = TimeSpan.FromMilliseconds(1000);
また、通常は非アクティブ状態になるとゲームそのものを一時停止する必要があるでしょう。加えて Windows Phone の場合は、非アクティブにされた時点でシステムに強制終了される可能性があることを考慮してください。
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; public class TestGame : Game { #if WINDOWS || XBOX public static void Main(string[] args) { using (Game game = new TestGame()) game.Run(); } #endif private GraphicsDeviceManager graphicsDeviceManager; private SpriteBatch sprite; private SpriteFont font; private DateTime prevTime; private int framePerSec, frameCount; public TestGame() { graphicsDeviceManager = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; TargetElapsedTime = TimeSpan.FromMilliseconds(33.3333); InactiveSleepTime = TimeSpan.FromMilliseconds(1000); } protected override void Initialize() { prevTime = DateTime.Now; base.Initialize(); } protected override void LoadContent() { sprite = new SpriteBatch(GraphicsDevice); font = Content.Load<SpriteFont>("TestFont"); base.LoadContent(); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); frameCount++; DateTime now = DateTime.Now; TimeSpan t = now - prevTime; if (t.TotalMilliseconds >= 1000) { framePerSec = frameCount; frameCount = 0; prevTime = now; } sprite.Begin(); sprite.DrawString(font, "FPS=" + framePerSec, Vector2.Zero, Color.Black); sprite.End(); base.Draw(gameTime); } }
コード1は Windows Phone 用にフレームの更新を 30 FPS まで落としています。携帯端末の場合、省電力が求められるため不必要に性能を使いすぎないように調整する必要があります。