Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Canvas: Moving/panning world with arrow keys in EaselJS

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.

Visualisation

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.

like image 865
AKG Avatar asked Jun 21 '13 18:06

AKG


2 Answers

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.

like image 153
rpg600 Avatar answered Oct 20 '22 05:10

rpg600


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/

like image 29
Samuel Reid Avatar answered Oct 20 '22 04:10

Samuel Reid