Apertar os botões para mover o quadrado vermelho:
Adicionar alguns obstáculos
Agora queremos adicionar obstáculos SOM para o nosso jogo.
Adicionar um novo componente para a área de jogo. Torná-lo verde, 10px de largura, 200px de altura, e colocá-lo 300px para a direita e 120px para baixo.
atualizar também o componente obstáculo em cada quadro:
Exemplo
var myGamePiece;
var myObstacle;
function class="notranslate">startGame() {
myGamePiece = new
component(30, 30, class="notranslate">"red" , 10, 120);
myObstacle
= new component(10, 200, class="notranslate">"green" , 300, 120);
myGameArea.start();
}
function class="notranslate">updateGameArea() {
myGameArea.clear();
myObstacle.update();
myGamePiece.newPos();
myGamePiece.update();
}
Tente você mesmo " Hit The Obstacle = Game Over
No exemplo acima, nada acontece quando você bate o obstáculo. Em um jogo, isso não é muito gratificante.
Como sabemos se o nosso quadrado vermelho atinge o obstáculo?
Criar um novo método no construtor do componente, que chekcs se as falhas de componentes com outro componente. Este método deve ser chamado cada vez que as atualizações quadros, 50 vezes por segundo.
Também adicionar um stop()
método para o myGameArea
objeto, que limpa o intervalo de 20 milissegundos.
Exemplo
var myGameArea = {
canvas :
document.createElement("canvas"),
start : class="notranslate">function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
},
clear : class="notranslate">function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
} ,
stop : class="notranslate">function() {
clearInterval(this.interval);
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = class="notranslate">function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = class="notranslate">function() {
this.x += this.speedX;
this.y
+= this.speedY;
}
this.crashWith = function(otherobj) {
var myleft = this.x;
var
myright = this.x + (this.width);
var mytop = this.y;
var
mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var
otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if
((mybottom < othertop) ||
(mytop > otherbottom) ||
(myright < otherleft) ||
(myleft > otherright)) {
crash = false;
}
return crash;
}
}
function class="notranslate">updateGameArea() {
if
(myGamePiece.crashWith(myObstacle)) {
myGameArea.stop();
} else {
myGameArea.clear();
myObstacle.update();
myGamePiece.newPos();
myGamePiece.update();
}
}
Tente você mesmo " Obstáculo em movimento
O obstáculo não é de perigo quando ele é estático, por isso queremos que ele se mova.
Alterar o valor da propriedade de myObstacle.x
em cada atualização:
Exemplo
function class="notranslate">updateGameArea() {
if
(myGamePiece.crashWith(myObstacle)) {
myGameArea.stop();
} else {
myGameArea.clear();
myObstacle.x += -1;
myObstacle.update();
myGamePiece.newPos();
myGamePiece.update();
}
}
Tente você mesmo " Obstáculos múltiplos
Como sobre como adicionar vários obstáculos?
Por que precisamos de uma propriedade para quadros de contagem, e um método para executar algo a uma determinada taxa de quadros.
Exemplo
var myGameArea = {
canvas : document.createElement("canvas"),
start : class="notranslate">function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context =
this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 20);
},
clear :
class="notranslate">function() {
this.context.clearRect(0, 0, this.canvas.width,
this.canvas.height);
},
stop :
class="notranslate">function() {
clearInterval(this.interval);
}
}
function everyinterval(n) {
if
((myGameArea.frameNo / n) % 1 == 0) {return true;}
return false;
}
A função everyinterval retorna true se o frameNumber atual corresponde com o intervalo dado.
Para definir vários obstáculos, primeiro declarar a variável obstáculo como uma matriz.
Em segundo lugar, precisamos fazer algumas alterações na função updateGameArea.
Exemplo
var myGamePiece;
var myObstacles = [];
function
class="notranslate">updateGameArea() {
var x, y;
for (i = 0; i <
myObstacles.length; i += 1) {
if (myGamePiece.crashWith(myObstacles[i])) {
myGameArea.stop();
return;
}
}
myGameArea.clear();
myGameArea.frameNo += 1;
if
(myGameArea.frameNo == 1 || everyinterval(150)) {
x = myGameArea.canvas.width;
y = myGameArea.canvas.height - 200
myObstacles.push(new component(10, 200, class="notranslate">"green" ,
x, y));
}
for (i = 0; i <
myObstacles.length; i += 1) {
myObstacles[i].x += -1;
myObstacles[i].update();
}
myGamePiece.newPos();
myGamePiece.update();
}
Tente você mesmo " No updateGameArea
função que deve passar por cada obstáculo para ver se há um acidente. Se houver um acidente, o updateGameArea
função irá parar, e não mais desenho é feito.
O updateGameArea
função conta quadros e adiciona um obstáculo para cada quadro 150.
Obstáculos da Random Size
Para tornar o jogo um pouco mais difícil, e divertido, nós enviará em obstáculos de tamanhos aleatórios, de modo que o quadrado vermelho deve se mover para cima e para baixo para não falhar.
Exemplo
function class="notranslate">updateGameArea() {
var x, height, gap,
minHeight, maxHeight, minGap, maxGap;
for (i = 0; i < myObstacles.length; i +=
1) {
if
(myGamePiece.crashWith(myObstacles[i])) {
myGameArea.stop();
return;
}
}
myGameArea.clear();
myGameArea.frameNo += 1;
if
(myGameArea.frameNo == 1 || everyinterval(150)) {
x = myGameArea.canvas.width;
minHeight = 20;
maxHeight = 200;
height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
minGap = 50;
maxGap = 200;
gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
myObstacles.push(new component(10, height, class="notranslate">"green" , x, 0));
myObstacles.push(new component(10, x - height - gap, class="notranslate">"green" , x,
height + gap));
}
for
(i = 0; i < myObstacles.length; i += 1) {
myObstacles[i].x += -1;
myObstacles[i].update();
}
myGamePiece.newPos();
myGamePiece.update();
}
Tente você mesmo "