After a year of studying and experimenting through trial-and-error, I feel that I am starting to understand JavaScript a bit more. So, now, I wanna try my hand at writing a simple 2D platform game (think Super Mario World or Sonic the Hedgehog). For this, I'll be employing the EaselJS library.
I am trying to figure out how I can move/pan the 'world' within a canvas by use of the left and right arrow keys. I know how I can run a function upon a keydown
of the arrow key, but I'm not too sure how I should approach the moving/panning.
Should I adjust the position/coordinates of every single thing within the canvas when a key is pressed? Or should I perhaps put everything in a container and move the position/coordinates of the container?
I'll appreciate anything that nudges me into the right direction. Tyvm :)
Updated with answer The chosen answer below confirmed that I indeed had to put everything in a container so that I can set the position of that container. This is the code I drafted, and it works.
// Canvas
var stage = new createjs.Stage('game');
createjs.Ticker.addEventListener('tick', tick);
function tick(event) {
stage.update();
}
// Cave
var cave = new createjs.Bitmap('img/cave.png');
cave.x = cave.y = 0;
// World
// Pans World if the left or right arrow keys are pressed
var world = new createjs.Container();
world.x = 0;
world.y = 0;
world.addChild(cave);
stage.addChild(world);
$(window).keydown(function(e){
switch (e.which || e.keyCode){
case 39: // right arrow key
world.regX += 10;
break;
case 37: // left arrow key
world.regX -= 10;
break;
}
});
I tried updating world.x
as well as world.regX
. Somehow, world.regX
seems to go smoother.
I think the best way is to put all display objects which will be scrolled into a scrollableObjectContainer (perhaps you have static elements like lifebar).
So when you move, just update scrollableObjectContainer.regX.
You can use tweenJS for a smoother scroll.
Just an idea... but take a look at the canvas translate function and use it at the beginning of each redraw to set the context from which to draw everything else.
http://www.html5canvastutorials.com/advanced/html5-canvas-transform-translate-tutorial/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With