Refactoring your Phaser-based NPC classes to be more modular and manageable is an excellent approach, especially as your project scales. By leveraging object-oriented principles such as inheritance and composition, you can reduce code duplication, enhance maintainability, and streamline the addition of new NPC types. Below, I'll guide you through creating a modular structure for your NPCs, integrating it smoothly with React, and ensuring that animation management is efficient.
1. Establish a Base NPC Class
Start by creating a BaseNPC class that encapsulates all common functionalities shared among different NPC types. This class will handle generic behaviors like movement, animations, health management, and interactions.
BaseNPC.js
import { GameObjects, Math as PhaserMath } from "phaser";
class BaseNPC extends GameObjects.Sprite {
constructor({ scene, type, x, y, width, height, features, animations }) {
super(scene, type, x, y, type + "_Idle_anim"); // Default to Idle animation
this.scene = scene;
this.type = type;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.features = features;
this.alive = true;
this.hurting = false;
// Initialize physics body
this.sprite = this.scene.matter.add.sprite(x + width / 2, y, `${type}_Walk_anim`);
this.sprite.setBody({
type: 'rectangle',
width: width * 0.75,
height: height * 0.75,
});
this.sprite.setOrigin(0.5, 0.5);
this.sprite.setFixedRotation();
this.sprite.setFriction(0.005);
this.sprite.setFrictionAir(0.02);
// Health management
this.health = Number(features.health) || 100;
this.firstHealth = this.health;
// Animation setup
this.animations = animations; // Object containing animation keys
this.sprite.anims.play(this.animations.walk);
// Graphics for health bar
this.ctx = this.scene.add.graphics();
this.ctx.setDefaultStyles({
fillStyle: { color: 0xff0000, alpha: 1 },
lineStyle: { width: 1, color: 0x0000ff, alpha: 0.75 }
});
// Time events
this.initTimeEvents();
// Assign attacks if any
this.attacks = [];
if (features.attacks) {
this.attacks = features.attacks;
}
// Health Bar
this.createHealthBar();
}
initTimeEvents() {
// Example: Regular attack or behavior
this.scene.time.addEvent({
delay: 750,
callback: this.behaviorLoop,
callbackScope: this,
loop: true
});
}
createHealthBar() {
this.healthBar = this.scene.add.graphics();
this.updateHealthBar();
}
updateHealthBar() {
if (!this.alive) return;
this.healthBar.clear();
this.healthBar.fillStyle(0xff0000, 1);
this.healthBar.fillRect(
this.sprite.x - this.width / 2,
this.sprite.y - this.height / 2 - 10,
(this.health / this.firstHealth) * this.width,
5
);
}
behaviorLoop() {
if (!this.alive) return;
// Default behavior: To be overridden by subclasses
}
move(velocityX, velocityY = 0) {
if (!this.alive) return;
this.sprite.setVelocityX(velocityX);
this.sprite.setVelocityY(velocityY);
if (velocityX !== 0) {
this.animChange("Walk");
this.sprite.setFlipX(velocityX < 0);
} else {
this.animChange("Idle");
}
}
animChange(animationKey) {
if (this.sprite.anims.currentAnim.key !== this.animations[animationKey]) {
this.sprite.anims.play(this.animations[animationKey]);
}
}
hurt(damage) {
if (!this.alive || this.hurting) return;
this.health -= damage;
this.updateHealthBar();
if (this.health <= 0) {
this.death();
} else {
this.animChange("Hurt");
this.hurting = true;
this.scene.time.addEvent({
delay: 1000,
callback: () => {
if (this.alive) {
this.animChange("Idle");
}
this.hurting = false;
}
});
}
}
death() {
this.animChange("Death");
this.alive = false;
this.scene.time.addEvent({
delay: 1000,
callback: () => {
this.healthBar.destroy();
this.sprite.destroy();
this.destroy();
}
});
}
// Additional common methods can be added here
}
export default BaseNPC;
Key Points:
- Constructor Parameters: Using an object for parameters enhances readability and flexibility.
- Animations: Pass an
animations object that maps behavior types to their corresponding animation keys.
- Health Management: Automatically handles health updates and death.
- Movement & Animation: Centralizes movement and animation changes.
- Health Bar: Graphically represents health, updating dynamically.
2. Create Specific NPC Subclasses
With the BaseNPC in place, you can now create subclasses for each NPC type, inheriting from BaseNPC and overriding or extending functionalities as needed.
BattleMechaRobot.js
import BaseNPC from "./BaseNPC";
import Effects from "./Effects";
class BattleMechaRobot extends BaseNPC {
constructor({ scene, enemy_no, x, y, width, height, features }) {
const animations = {
walk: `battle_mecha${enemy_no}_Walk_anims`,
idle: `battle_mecha${enemy_no}_Idle_anims`,
hurt: `battle_mecha${enemy_no}_Hurt_anims`,
death: `battle_mecha${enemy_no}_Death_anims`,
attack: `battle_mecha${enemy_no}_Attack_anims`,
// Add other animations as needed
};
super({
scene,
type: `battle_mecha${enemy_no}`,
x,
y,
width,
height,
features,
animations
});
// Additional properties specific to BattleMechaRobot
this.attackDetail = features.attackDetail;
this.initBehavior();
}
initBehavior() {
// Override or extend behavior loop
}
behaviorLoop() {
// Implement specific behavior, e.g., attacking, moving towards player
if (!this.alive) return;
// Example: Attack if player is within range
const player = this.scene.player;
const distance = PhaserMath.Distance.Between(
player.x, player.y,
this.sprite.x, this.sprite.y
);
if (distance < this.width) {
this.attack();
} else {
this.moveTowardsPlayer();
}
}
moveTowardsPlayer() {
const player = this.scene.player;
const deltaX = player.x - this.sprite.x;
if (Math.abs(deltaX) > 10) {
const velocity = deltaX > 0 ? 3 : -3;
this.move(velocity);
} else {
this.move(0);
}
}
attack() {
if (this.hurting) return;
this.animChange("Attack");
// Implement attack logic, e.g., dealing damage to the player
this.scene.hurt(this.attackDetail.damage || 10);
// Example: Special effects on attack
new Effects(this.sprite.x, this.sprite.y, { name: "AttackEffect" }, this.scene);
}
// Override hurt or death if behavior differs
}
export default BattleMechaRobot;
WorkerEnemy.js
import BaseNPC from "./BaseNPC";
import Effects from "./Effects";
class WorkerEnemy extends BaseNPC {
constructor({ scene, enemy_no, x, y, width, height, features }) {
const animations = {
walk: `worker${enemy_no}_Walk_anims`,
idle: `worker${enemy_no}_Idle_anims`,
hurt: `worker${enemy_no}_Hurt_anims`,
death: `worker${enemy_no}_Death_anims`,
attack: `worker${enemy_no}_Attack_anims`,
// Add other animations as needed
};
super({
scene,
type: `worker${enemy_no}`,
x,
y,
width,
height,
features,
animations
});
this.attackDetail = features.attackDetail;
}
behaviorLoop() {
// Implement worker-specific behavior
const player = this.scene.player;
const distance = PhaserMath.Distance.Between(
player.x, player.y,
this.sprite.x, this.sprite.y
);
if (distance < this.width / 2 + this.height / 2) {
this.attack();
} else {
this.moveTowardsPlayer();
}
}
moveTowardsPlayer() {
const player = this.scene.player;
const deltaX = player.x - this.sprite.x;
if (Math.abs(deltaX) > 10) {
const velocity = deltaX > 0 ? 2 : -2; // Slower movement
this.move(velocity);
} else {
this.move(0);
}
}
attack() {
if (this.hurting) return;
this.animChange("Attack");
this.scene.hurt(this.attackDetail.damage || 5);
// Example: Special effects on attack
new Effects(this.sprite.x, this.sprite.y, { name: "WorkerAttackEffect" }, this.scene);
}
}
export default WorkerEnemy;
Key Points:
- Animations: Each subclass defines its own set of animations by passing the appropriate keys to the
BaseNPC.
- Behavior Loop: Overrides the
behaviorLoop method to implement type-specific behaviors.
- Attack Logic: Implement custom attack methods as needed, possibly adding special effects or different damage values.
PoliceCharacter.js
import BaseNPC from "./BaseNPC";
import Effects from "./Effects";
class PoliceCharacter extends BaseNPC {
constructor({ scene, enemy_no, x, y, width, height, features }) {
const animations = {
walk: `police${enemy_no}_Walk_anims`,
idle: `police${enemy_no}_Idle_anims`,
hurt: `police${enemy_no}_Hurt_anims`,
death: `police${enemy_no}_Death_anims`,
attack: `police${enemy_no}_Attack_anims`,
// Add other animations as needed
};
super({
scene,
type: `police${enemy_no}`,
x,
y,
width,
height,
features,
animations
});
this.alertSiren = this.scene.sound.add('police_siren');
}
behaviorLoop() {
if (!this.alive) return;
const player = this.scene.player;
const distance = PhaserMath.Distance.Between(
player.x, player.y,
this.sprite.x, this.sprite.y
);
if (player.getData('isGuilty') && distance < (this.width / 2 + this.height / 2) + 20) {
this.attack();
} else {
this.moveTowardsPlayer();
}
}
attack() {
if (this.hurting) return;
this.animChange("Attack");
this.scene.hurt(10);
this.sprite.setData('DangerForPlayer', true);
if (!this.alertSiren.isPlaying) {
this.alertSiren.play();
}
// Example: Special effects on attack
new Effects(this.sprite.x, this.sprite.y, { name: "PoliceAttackEffect" }, this.scene);
}
moveTowardsPlayer() {
const player = this.scene.player;
const deltaX = player.x - this.sprite.x;
if (Math.abs(deltaX) > 10) {
const velocity = deltaX > 0 ? 2.5 : -2.5;
this.move(velocity);
} else {
this.move(0);
}
}
death() {
super.death();
// Additional death logic specific to PoliceCharacter if needed
}
}
export default PoliceCharacter;
3. Manage Animations Efficiently
To streamline animation management, consider adopting a consistent naming convention and centralizing animation definitions. This approach minimizes repetition and ensures that animations are easily accessible based on NPC type and state.
AnimationLoader.js
class AnimationLoader {
constructor(scene) {
this.scene = scene;
}
loadAnimations(npcType, enemy_no) {
const prefixes = ["Walk", "Idle", "Hurt", "Death", "Attack"];
prefixes.forEach(prefix => {
this.scene.anims.create({
key: `${npcType}${enemy_no}_${prefix}_anims`,
frames: this.scene.anims.generateFrameNames(npcType, {
start: 1,
end: 4, // Adjust based on number of frames
prefix: `${prefix}_`,
suffix: '.png'
}),
frameRate: 10,
repeat: -1
});
});
}
}
export default AnimationLoader;
Usage in Scene:
import AnimationLoader from "./AnimationLoader";
class GameScene extends Phaser.Scene {
constructor() {
super({ key: 'GameScene' });
}
preload() {
// Load sprite sheets or individual frames here
}
create() {
const animationLoader = new AnimationLoader(this);
const npcTypes = ["battle_mecha", "worker", "police", "robot"];
npcTypes.forEach(type => {
for (let i = 1; i <= 3; i++) { // Assuming 3 variations
animationLoader.loadAnimations(type, i);
}
});
// Instantiate NPCs here
}
update() {
// Update logic
}
}
Benefits:
- Consistency: Ensures all NPCs follow a standardized animation setup.
- Scalability: Easily add new NPC types and animations without modifying existing code.
- Maintainability: Centralizes animation definitions, making it easier to manage and debug.
4. Integrate with React Using useEffect and useRef
When integrating Phaser with React, it's essential to manage the Phaser game's lifecycle correctly. Using useEffect and useRef hooks can help initialize and clean up the Phaser game instance within React components.
PhaserGameComponent.jsx
import React, { useEffect, useRef } from 'react';
import Phaser from 'phaser';
import GameScene from './GameScene'; // Your Phaser scene
const PhaserGameComponent = () => {
const phaserRef = useRef(null);
useEffect(() => {
const config = {
type: Phaser.AUTO,
width: 800,
height: 600,
parent: phaserRef.current,
physics: {
default: 'matter',
matter: {
gravity: { y: 1 },
debug: false
}
},
scene: [GameScene],
};
const game = new Phaser.Game(config);
return () => {
game.destroy(true);
};
}, []);
return <div ref={phaserRef} />;
};
export default PhaserGameComponent;
Key Points:
useRef: References the div where Phaser will render the game.
useEffect: Initializes the Phaser game on mount and destroys it on unmount to prevent memory leaks.
- Phaser Configuration: Customize the Phaser game configuration as needed (e.g., canvas size, physics settings).
5. Organize Assets Structurally
To maintain order, organize your assets (sprites, animations) in a structured directory format. This organization simplifies asset loading and management.
Directory Structure:
assets/
├── battle_mecha/
│ ├── Walk_1.png
│ ├── Walk_2.png
│ ├── Idle_1.png
│ ├── ...
├── worker/
│ ├── Walk_1.png
│ ├── Idle_1.png
│ ├── ...
├── police/
│ ├── Walk_1.png
│ ├── Idle_1.png
│ ├── ...
├── robot/
│ ├── Attack1.png
│ ├── Attack2.png
│ ├── Idle.png
│ ├── Walk.png
│ ├── ...
Benefits:
- Clarity: Easy to locate and manage assets for different NPC types.
- Scalability: Simplifies adding new assets without cluttering directories.
- Efficiency: Enhances asset loading logic by grouping related assets.
6. Example Integration in a Phaser Scene
Here’s how you might integrate the refactored NPC classes within a Phaser scene, ensuring cohesive behavior and interactions.
GameScene.js
import Phaser from 'phaser';
import AnimationLoader from './AnimationLoader';
import BattleMechaRobot from './BattleMechaRobot';
import WorkerEnemy from './WorkerEnemy';
import PoliceCharacter from './PoliceCharacter';
// Import other NPC classes as needed
class GameScene extends Phaser.Scene {
constructor() {
super({ key: 'GameScene' });
}
preload() {
// Load all assets here
// Example:
this.load.spritesheet('battle_mecha1_Walk_anims', 'assets/battle_mecha/Walk.png', { frameWidth: 64, frameHeight: 64 });
// Load other sprite sheets and assets
}
create() {
const animationLoader = new AnimationLoader(this);
const npcTypes = ["battle_mecha", "worker", "police", "robot"];
npcTypes.forEach(type => {
for (let i = 1; i <= 3; i++) { // Adjust based on NPC variations
animationLoader.loadAnimations(type, i);
}
});
// Instantiate NPCs
this.battleMecha1 = new BattleMechaRobot({
scene: this,
enemy_no: 1,
x: 100,
y: 300,
width: 50,
height: 100,
features: {
health: 150,
attackDetail: { damage: 20 }
}
});
this.worker1 = new WorkerEnemy({
scene: this,
enemy_no: 1,
x: 200,
y: 300,
width: 40,
height: 80,
features: {
health: 80,
attackDetail: { damage: 10 }
}
});
this.police1 = new PoliceCharacter({
scene: this,
enemy_no: 1,
x: 300,
y: 300,
width: 45,
height: 90,
features: {
health: 100
// Add other features as needed
}
});
// Add more NPCs as needed
// Example: Add player
this.player = this.matter.add.sprite(400, 300, 'player_idle');
// Set up player properties, controls, etc.
}
update(time, delta) {
// Update NPCs
this.battleMecha1.behaviorLoop();
this.worker1.behaviorLoop();
this.police1.behaviorLoop();
// Update health bars, player, and other game elements
}
}
export default GameScene;
Key Points:
- Asset Loading: Ensure all necessary assets are loaded in the
preload method.
- NPC Instantiation: Create instances of NPCs by passing required parameters, leveraging the refactored classes.
- Behavior Updates: Call
behaviorLoop or similar methods within the update lifecycle hook to maintain NPC behavior.
7. Handling Variable Attack Animations for Robots
For NPC types like Robot, where attack animations vary (e.g., Attack1.png, Attack2.png, etc.), modify the Robot class to handle dynamic animations.
Robot.js
import BaseNPC from "./BaseNPC";
import Effects from "./Effects";
class Robot extends BaseNPC {
constructor({ scene, robot_no, attackVariants, x, y, width, height, features }) {
const animations = {
walk: `robot${robot_no}_Walk_anim`,
idle: `robot${robot_no}_Idle_anim`,
hurt: `robot${robot_no}_Hurt_anim`,
death: `robot${robot_no}_Death_anim`,
attack: `robot${robot_no}_Attack1_anim`, // Default attack
// Additional attack animations can be managed dynamically
};
super({
scene,
type: `robot${robot_no}`,
x,
y,
width,
height,
features,
animations
});
this.attackVariants = attackVariants; // Array of attack animation keys
this.currentAttackIndex = 0;
}
attack() {
if (this.hurting) return;
// Select attack variant
const attackKey = this.attackVariants[this.currentAttackIndex];
this.animChange(attackKey);
// Cycle to next attack variant for variety
this.currentAttackIndex = (this.currentAttackIndex + 1) % this.attackVariants.length;
// Implement attack logic
this.scene.hurt(5); // Example damage
// Special effects
new Effects(this.sprite.x, this.sprite.y, { name: "RobotAttackEffect" }, this.scene);
}
// Optionally override behaviorLoop if needed
}
export default Robot;
Usage Example:
this.robot1 = new Robot({
scene: this,
robot_no: 1,
attackVariants: [`Attack1_anim`, `Attack2_anim`, `Attack3_anim`, `Attack4_anim`, `Attack5_anim`, `Attack6_anim`, `Attack7_anim`, `Attack8_anim`],
x: 500,
y: 300,
width: 50,
height: 100,
features: {
health: 120
}
});
Key Points:
- Attack Variants: Maintain an array of attack animation keys to cycle through different attacks.
- Dynamic Animation Change: Override the
attack method to select and play different attack animations dynamically.
- Extensibility: Easily add or remove attack variants by modifying the
attackVariants array.
8. Best Practices and Additional Tips
-
Consistent Naming Conventions: Stick to a consistent naming pattern for animations and assets to simplify coding and asset management.
-
Separate Concerns: Keep game logic separated from React components. Let React handle the UI and lifecycle, while Phaser manages the game rendering and logic.
-
Optimize Performance: Only update and process active NPCs. Consider pooling NPCs if you have a large number to manage.
-
Testing: Regularly test each NPC type individually to ensure their specific behaviors and interactions work as intended.
-
Documentation: Document your classes and methods to make future maintenance and onboarding easier.
Conclusion
By abstracting common functionalities into a BaseNPC class and creating specific subclasses for each NPC type, you achieve a modular and scalable architecture. This structure not only reduces code duplication but also makes it straightforward to introduce new NPCs with unique behaviors and animations. Integrating Phaser with React using hooks like useEffect and useRef ensures that your game remains responsive within the React ecosystem. Adopting these practices will significantly enhance the maintainability and extensibility of your game project.