Asteroids-2026/js/entities/Bullet.js

54 lines
1.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const PLAYER_BULLET_SPEED = 700; // pixels/sec
const ALIEN_BULLET_SPEED = 350; // pixels/sec noticeably slower than player shots
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 speed = owner === 'player' ? PLAYER_BULLET_SPEED : ALIEN_BULLET_SPEED;
const rad = Phaser.Math.DegToRad(angle);
this.sprite.setVelocity(
Math.cos(rad) * speed,
Math.sin(rad) * 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();
}
}
}