Asteroids-2026/js/entities/Bullet.js

52 lines
1.3 KiB
JavaScript

const BULLET_SPEED = 700; // pixels/sec
const BULLET_LIFETIME = 1800; // ms
export default class Bullet {
constructor(scene, x, y, angle, owner, group) {
this.scene = scene;
this.owner = owner; // 'player' or 'alien'
this.alive = true;
const textureKey = owner === 'player' ? 'bullet' : 'alien_bullet';
this.sprite = scene.physics.add.sprite(x, y, textureKey);
group.add(this.sprite);
this.sprite.gameEntity = this;
this.sprite.body.setAllowGravity(false);
const rad = Phaser.Math.DegToRad(angle);
this.sprite.setVelocity(
Math.cos(rad) * BULLET_SPEED,
Math.sin(rad) * BULLET_SPEED
);
this.createdAt = scene.time.now;
}
update(time) {
if (!this.alive) return false;
// Expire by lifetime
if (time - this.createdAt > BULLET_LIFETIME) {
this.destroy();
return false;
}
// Expire if far off-screen
const { x, y } = this.sprite;
if (x < -60 || x > 1660 || y < -60 || y > 960) {
this.destroy();
return false;
}
return true;
}
destroy() {
if (!this.alive) return;
this.alive = false;
if (this.sprite && this.sprite.active) {
this.sprite.destroy();
}
}
}