Jogo Xadrez
// Variáveis para o jogo
let bola;
let plataforma;
function setup() {
createCanvas(400, 400);
bola = new Bola();
plataforma = new Plataforma();
}
function draw() {
background(220);
bola.atualizar();
bola.exibir();
plataforma.exibir();
plataforma.mover();
// Verifica colisão entre a bola e a plataforma
if (bola.colideCom(plataforma)) {
bola.velocidade.y *= -1; // Inverte a direção Y da bola
}
}
class Bola {
constructor() {
this.posicao = createVector(width / 2, height / 2);
this.velocidade = createVector(2, -2);
this.raio = 20;
}
atualizar() {
this.posicao.add(this.velocidade);
// Checa se a bola colidiu com as bordas da tela
if (this.posicao.x < 0 || this.posicao.x > width) {
this.velocidade.x *= -1;
}
if (this.posicao.y < 0) {
this.velocidade.y *= -1;
}
}
exibir() {
fill(255, 0, 0);
noStroke();
ellipse(this.posicao.x, this.posicao.y, this.raio * 2);
}
colideCom(plataforma) {
let bolaColideComPlataforma =
this.posicao.x > plataforma.posicao.x &&
this.posicao.x < plataforma.posicao.x + plataforma.largura &&
this.posicao.y + this.raio > plataforma.posicao.y &&
this.posicao.y - this.raio < plataforma.posicao.y + plataforma.altura;
return bolaColideComPlataforma;
}
}
class Plataforma {
constructor() {
this.posicao = createVector(width / 2 - 50, height - 20);
this.largura = 100;
this.altura = 20;
this.velocidade = 5;
}
exibir() {
fill(0, 0, 255);
noStroke();
rect(this.posicao.x, this.posicao.y, this.largura, this.altura);
}
mover() {
if (keyIsDown(LEFT_ARROW)) {
this.posicao.x -= this.velocidade;
}
if (keyIsDown(RIGHT_ARROW)) {
this.posicao.x += this.velocidade;
}
// Impede que a plataforma saia da tela
this.posicao.x = constrain(this.posicao.x, 0, width - this.largura);
}
}