2
我正在用Javascript製作一個遊戲引擎,我想要一個可以旋轉的相機對象。當相機旋轉時,整個2D場景也會在相機的位置旋轉。每個視覺實體也可以旋轉,這是他們如何做到的:畫布是否支持嵌套上下文保存?
context.save(); //As we are about to change the context's state, we need to save it so it can be restored.
context.translate(entity.position.x + entity.width/2, entity.position.y + entity.height/2); //Translate to the center of the entity so the context can be rotated with the desired effect.
context.rotate(entity.rotation); //In radii.
context.drawImage(entitiy.image, -entity.width/2, -entity.height/2);
context.restore(); //Restore the previous context state so it can be used later by other entities.
我想以類似的方式實現相機旋轉。基本上,前通過所有實體會和渲染他們,我這樣做:
if (camera.rotation != 0)
{
renderer.context.save();
renderer.context.rotate(camera.rotation);
}
//Loop through entities and render.
然後,後實體已經完成(以及保存和恢復同樣的背景下無數次),我想恢復上下文它的渲染,就像在此之前的狀態:
if (camera.phi != 0)
{
renderer.context.restore();
}
說我有2個實體這兩者都是由某種程度的旋轉,而且還旋轉的攝像頭,過程是這樣的:
- 保存
- 保存
- 平移和旋轉
- 從2
- 恢復保存
- 平移和旋轉
- 從5
- 恢復恢復從1
是這種行爲得到支持?我實施了它,它似乎工作,雖然有錯誤,所以我無法正確評估情況...
是的,「嵌套」概念是堆棧行爲。在OP的示例中,堆棧變爲空 - > 1 - > 1 2 - > 1 - > 1 - > 1 - >空。 – pimvdb 2012-07-10 21:33:01