Monday, August 12, 2019

2d - Implementing a camera on HTML5 canvas?


I am trying to work out the best way of implementing a camera in my simple 2d game.


The way it is structured at the moment is my game objects all have draw functions, which are passed a canvas instance to draw themselves to (at whatever position they are currently at).


I now need to add a camera to the mix, so that i can have a bigger world, but i'm not sure of the best way to implement it.


The way I see it, I can either translate the whole canvas and let the objects carry on drawing themselves at whatever position they are at, eg:


canvas.translate(camera.position);
player.draw(canvas);

This seems easy enough, but doesn't seem right somehow. Alternatively, I could pass the camera in to the objects with the canvas, and let the objects calculate a relative screen position before drawing, eg:


player.draw(canvas, camera);

// inside the draw function:
var position = this.position.subtract(camera.position);
canvas.drawStuff(stuff, position);

But that seems wrong too. How do other 2d engines handle this? Is there an established best way of doing it, or any pitfalls I should avoid?




No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...