Monwarp InputManager example

by monteslu

HTML

<canvas id="canvas" style="border: 1px solid black;"  width="300" height="300"></canvas>

JavaScript

require({
  packages: [
    { name: 'mwe', location: 'https://raw.github.com/monteslu/monwarp/master/src/mwe/' }
  ]

}, [
  'mwe/GameCore'
], function(GameCore){
    
    //position and velocities
    var sprite = {
        x:100, y:100, maxVelocity: 0.2, dx: 0, dy:0
    };
    
    var keys = dojo.keys;
    
    var game = new GameCore({
      canvasId: 'canvas',
      loadResources: function(rm){
        //will have game wait until image is loaded
        sprite.img = rm.loadImage('http://lorempixel.com/50/50/');
        this.backgroundImg = rm.loadImage('http://lorempixel.com/300/300/');
      },
      initInput: function(im){
        im.addKeyAction(keys.LEFT_ARROW);
        im.addKeyAction(keys.RIGHT_ARROW);
        im.addKeyAction(keys.UP_ARROW);
        im.addKeyAction(keys.DOWN_ARROW);
      },
      handleInput: function(im){
        if(im.keyActions[keys.LEFT_ARROW].isPressed()){
           sprite.dx = sprite.maxVelocity * -1;
        }
        else if(im.keyActions[keys.RIGHT_ARROW].isPressed()){
           sprite.dx = sprite.maxVelocity;
        }else{
           sprite.dx = 0;   
        }
          
        if(im.keyActions[keys.UP_ARROW].isPressed()){
           sprite.dy = sprite.maxVelocity * -1;
        }
        else if(im.keyActions[keys.DOWN_ARROW].isPressed()){
           sprite.dy = sprite.maxVelocity;
        }else{
           sprite.dy = 0;   
        }
      },
      update: function(timeElapsed){
        sprite.x+= sprite.dx * timeElapsed;
        sprite.y+= sprite.dy * timeElapsed;
      },
      draw: function(ctx){
        ctx.drawImage(this.backgroundImg, 0, 0);
        ctx.drawImage(sprite.img, sprite.x, sprite.y);
      }    
    });

    game.run();
    
});