Menù

Top 5

Cannone spara proiettili

Creo un cannone che spara proiettili al click del mouse

class Bullet {
    constructor(pos, angle, ctx) {
        this.ctx = ctx;
        this.angle = angle;
        this.pos = pos;
        this.speed = 10
        this.radius = 3

    }
    update() {
        this.pos.x -= Math.cos(this.angle) * this.speed;
        this.pos.y -= Math.sin(this.angle) * this.speed;
        this.draw();
    }
    draw() {
        this.ctx.beginPath();
        this.ctx.arc(this.pos.x, this.pos.y, this.radius, 0, Math.PI * 2);
        this.ctx.fill();
    }
}

canvas.width = 400;
canvas.height = 400;
const ctx = canvas.getContext("2d");
let angolo = 1.5;
const raggio = 50;
const arcX = canvas.width / 2;
const arcY = canvas.height;
const bullets = [];
animate();

function animate() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    ctx.beginPath();
    ctx.arc(arcX, arcY, raggio / 2, 0, Math.PI * 2);
    ctx.fill();

    const x = arcX + raggio * Math.cos(angolo);
    const y = arcY + raggio * Math.sin(angolo);

    ctx.beginPath();
    ctx.moveTo(arcX, arcY);
    ctx.lineWidth = 15;
    ctx.lineTo(x, y);
    ctx.stroke();

    bullets.forEach((bullet, i) => {
        bullet.update(ctx);
        if (bullet.pos.x > canvas.width || bullet.pos.x < 0 || bullet.pos.y < 0) {
            bullets.splice(i, 1);
        }
    });

    requestAnimationFrame(animate);
}

canvas.addEventListener("mousemove", (e) => {
    const dx = e.offsetX - arcX;
    const dy = e.offsetY - arcY;
    angolo = Math.atan2(dy, dx);
});

canvas.addEventListener("mousedown", (e) => {
    const dy = arcY - e.offsetY;
    const dx = arcX - e.offsetX;
    const angle = Math.atan2(dy, dx);
    bullets.push(new Bullet({ x: arcX, y: arcY }, angle, ctx));
});

criric

Mi sono appassionato di programmazione web a 34 anni, un pò tardi, da allora però non perdo mai occasione per imparare qualcosa di nuovo in questi campi.

Javascript - Html - Css - Php - Mysql

Inserisci un commento

Codice antispam

Categorie

Comunicazioni

Puoi utilizzare questo modulo per qualsiati tipo di segnalazione.

Codice antispam

 

I dati di questo modulo non verranno pubblicati.