Move character sprite on canvas and change image [closed]

9

Well, I would like to know how I could implement a sprite on my canvas, I am very lay with canvas, the idea is, by pressing arrow -> he runs the sprite 1.png, the squeeze arrow < - he runs the sprite 2.png, and when left click he performs sprite3.png but when n has not even one squeeze it is in the default sprite. So the idea would be to run right and left and attack with the mouse button.

My canvas is as follows link how would I add it?

var iw = 2000; //Image width
var ih = 643; //Image height
var sw = 968; //Canvas width
var sh = 643; //Canvas height
var cw = 80; //Character width
var ch = 80; //Character height
var speed = 10; //Character speed

var img = new Image(iw, ih);
var character = new Image(iw, ih);

img.src = "http://i.imgur.com/QnBufq4.jpg";
character.src = "http://i.imgur.com/QnBufq4.jpg";


var ctx = canvas.getContext("2d");
var pos = {x: 0, y: ih - 160};
var camera = {x: 0, y: 0}

function draw() {
 //Faz a esquerda da camera comecar meia tela antes do personagem, mas so se tiver imagem suficiente pra isso
 camera.x = Math.min(iw - sw, Math.max(0,pos.x - sw/2));
 //Reseta as transformacoes do canvas
 ctx.setTransform(1,0,0,1,0,0);
 //Limpa o canvas
 ctx.clearRect(0, 0, canvas.width, canvas.height);
 //Desloca o mundo inteiro, simulando uma camera
 ctx.translate(-camera.x, -camera.y);
 //Desenha o fundo
 ctx.drawImage(img, 0, 0, sw, sh, 0, 0, iw, ih);
 //Desenha o personagem
 ctx.fillRect(pos.x, pos.y, cw, ch);

 window.requestAnimationFrame(draw);
}

document.addEventListener('keydown', function(e) {
 var key = e.which || e.key || e.keyCode;
 switch(key) {
  case 37: pos.x-=speed; break;
  case 39: pos.x+=speed; break;
 }
 pos.x = Math.max(0, Math.min(iw - cw,pos.x));
});

window.requestAnimationFrame(draw);
<canvas id="canvas" width="968" height="643" style="border;background:rgb(233,233,233)">
            O seu navegador não suporta o canvas
            </canvas>

    
asked by anonymous 19.06.2016 / 01:00

1 answer

0

The sprites should not have the same area between the animations, this your sprite is very varied, until you defined height and width as 80px

I made a base adjustment on your file in Fiddle and at least I was able to call the example image

link

a look in this file maybe a light of what you are trying link

    
18.07.2016 / 22:17