這樣我們就得到了需要計(jì)算的區(qū)域的信息。可以通過(guò)查詢對(duì)象的HasMoved屬性來(lái)判斷它是否發(fā)生了移動(dòng)。這些對(duì)象移入的區(qū)域可以通過(guò)計(jì)算每個(gè)對(duì)象當(dāng)前的繪制矩形來(lái)得到;對(duì)象通過(guò)GetRenderRectangle函數(shù)來(lái)返回該矩形。如果我們使用CombineRectangles函數(shù),那么可以將所有這些矩形合并為一個(gè)大的繪制矩形。然后就形成了所有移動(dòng)對(duì)象的移入?yún)^(qū)域。
要得到對(duì)象移出區(qū)域也很容易。我們只需要將每個(gè)對(duì)象的PreviousRenderRect對(duì)象進(jìn)行合并,就如同掃描它們一樣。得到這些信息后,將對(duì)象的當(dāng)前繪制矩形復(fù)制到先前的繪制矩形中,為下一次獲取該信息做好準(zhǔn)備。
所有這些操作都由FindCurrentRenderRectangle函數(shù)處理,如程序清單4-17所示。
程序清單4-17 查找需要在其中進(jìn)行繪制的矩形
/// <summary>
/// Calculate the bounds of the rectangle inside which all of the moving
/// objects reside.
/// </summary>
/// <returns></returns>
private Rectangle FindCurrentRenderRectangle()
{
Rectangle renderRect = new Rectangle();
Rectangle objectRenderRect;
// Loop through all items, combining the positions of those that have
// moved or created into the render rectangle
foreach (CGameObjectGDIBase gameObj in GameObjects)
{
// Has this object been moved (or created) since the last update?
gameObj.CheckIfMoved();
if (gameObj.HasMoved)
{
// The object has moved so we need to add the its rectangle to the
// render rectangle. Retrieve its current rectangle
objectRenderRect = gameObj.GetRenderRectangle();
// Add to the overall rectangle
renderRect = CGameFunctions.CombineRectangles(renderRect, objectRenderRect);
// Include the object's previous rectangle too.
// (We can't rely on its LastX/Y position as it may have been updated
// multiple times since the last render)
renderRect = CGameFunctions.CombineRectangles(renderRect,
gameObj.PreviousRenderRect);
// Store the current render rectangle into the object as its
// previous rectangle for the next call.
gameObj.PreviousRenderRect = objectRenderRect;
// Clear the HasMoved flag now that we have observed this object's
// movement
gameObj.HasMoved = false;
}
// This object has now been processed so it is no longer new
gameObj.IsNew = false;
}
return renderRect;
}