animacao.js
teclado.js
---------------------------------------------------------------------------------
nave.js
function Nave(context, teclado, imagem) {
this.context = context;
this.teclado = teclado;
this.imagem = imagem;
this.x = 0;
this.y = 0;
this.velocidade = 0;
}
Nave.prototype = {
atualizar: function() {
if (this.teclado.pressionada(SETA_ESQUERDA) && this.x > 0)
this.x -= this.velocidade;
if (this.teclado.pressionada(SETA_DIREITA) &&
this.x < this.context.canvas.width
- this.imagem.width)
this.x += this.velocidade;
if (this.teclado.pressionada(SETA_ACIMA) && this.y > 0)
this.y -= this.velocidade;
if (this.teclado.pressionada(SETA_ABAIXO) &&
this.y < this.context.canvas.height
- this.imagem.height)
this.y += this.velocidade;
},
desenhar: function() {
this.context.drawImage(this.imagem, this.x, this.y,
this.imagem.width, this.imagem.height);
}
}
---------------------------------------------------------------------------------------------------------
teste-nave.html
<!DOCTYPE html>
<html>
<head>
<title>Nave Espacial Controlável</title>
<script src="animacao.js"></script>
<script src="teclado.js"></script>
<script src="nave.js"></script>
</head>
<body>
<canvas id="canvas_nave" width="500" height="500"></canvas>
<script>
// Canvas e contexto
var canvas = document.getElementById('canvas_nave');
var context = canvas.getContext('2d');
// Teclado e animação (game engine)
var teclado = new Teclado(document);
var animacao = new Animacao(context);
// Sprite da nave e sua imagem
var imgNave = new Image();
imgNave.src = 'img/nave.png';
imgNave.width=50; // alterar a largura da imagem
imgNave.height=50; //alterar a altura da imagem
var nave = new Nave(context, teclado, imgNave);
animacao.novoSprite(nave);
// Quando carregar a imagem, iniciar a animação
imgNave.onload = function() {
// Centralizada na horizontal, alinhada embaixo na vertical
nave.x = canvas.width / 2 - imgNave.width / 2;
nave.y = canvas.height - imgNave.height;
nave.velocidade = 5;
animacao.ligar();
}
</script>
</body>
</html>
Nenhum comentário:
Postar um comentário