Reputation: 10713
I have been working through a tutorial (http://glacialflame.com/category/tutorial/) to build an Isometric game engine, but I would like the map to move with the character as the focus point.
So, when you move - the map centres on the character.
I have a little PasteBin here: http://pastebin.com/U75Pz4Yy
See it in action here: http://www.wikiword.co.uk/release-candidate/canvas/newEngine/index.html
Have a fiddle, by request! http://jsfiddle.net/neuroflux/vUxYg/2/
Note: This is for HTML5 and Canvas browsers only, don't moan if you are using IE6 ;)
Any ideas and help would be appreciated, I thought I could do it by updating each of the "tiles" in the array by +1 or -1 respectively, but I can't seem to do a ForEach loop for the tile images already on the canvas.
Cheers in advance!
Upvotes: 4
Views: 2991
Reputation: 63812
Moving the map should be as simple as translating the context by the players position.
As the player moves by X or Y, so should the canvas translate by the same amount (or by negative that amount)
I didnt bother finding the right offset to make the bunny always in the center of the screen, but it should give you the idea of how it is done.
Upvotes: 2
Reputation: 328614
There are several ways to attack this:
You can move the whole canvas, delete the elements which became invisible (eventually). So what if the top left corner is at -257467,374672? It's just one addition for the renderer.
Instead of moving the canvas, you can move the images of the times. So create an array for all the style elements of the map pieces and then, in the loop, move the background-image
styles around. The map elements stay in place, only the image changes.
You can create/delete the DOM nodes plus move the existing ones. But from my experience, that's pretty expensive (since the browser needs to figure out what you changed and then update the DOM tree, flush the render caches, render the part you changes again, lots of objects are created and destroyed, ...)
Upvotes: 3
Reputation: 30496
I can give one idea, instead of having only one canvas you could manage 3 canvas and set them in 3 divs with absolute positioning, so that each div is built on top of the previous with transparent background.
The canvas would be bigger than the visible playground (could be managed with overflow css settings). The player would always be on the center of the playground. When moving, instead of redrawing background and top layer you just have to handle div position, the browser will make the graphic job.
After that there's the problem of loading new background tiles, that could be handled with some hidden canvas preload. And this way of layering canvas can be applied for other layers (active markers layer, other players layers, etc), it's a 'sprite-layer-in-div' where the browser grapĥic engine do most of the final screen picture rendering.
Upvotes: 0