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