NPCCutter (class)
Classes in p5.js let you bundle related data (x, y, speed) and behaviors (update, draw) into reusable objects. The constructor runs once when you create a new NPCCutter, setting up all the initial values.
class NPCCutter {
constructor(x, y) {
this.x = x;
this.y = y;
this.targetX = x;
this.targetY = y;
this.speed = random(2, 5); // Random cutting speed for each NPC
this.isCuttingFood = false; // Flag to know if currently cutting food
this.targetFoodIndex = -1; // Index of the specific food emoji this NPC is targeting
this.setNewTarget(); // Set an initial target
}
Line-by-line explanation (8 lines)
🔧 Subcomponents:
constructor(x, y) {
Sets up an individual NPC with starting position, target position, speed, and flags for current state
this.x = x;- Stores the NPC's current horizontal position
this.y = y;- Stores the NPC's current vertical position
this.targetX = x;- Initializes the target position to the current position; will be updated by setNewTarget()
this.targetY = y;- Initializes the target position to the current position; will be updated by setNewTarget()
this.speed = random(2, 5); // Random cutting speed for each NPC- Each NPC gets a unique random speed between 2 and 5 pixels per frame, making movement feel natural and varied
this.isCuttingFood = false; // Flag to know if currently cutting food- A boolean that tracks whether this NPC is currently eating a food emoji (true) or targeting the pumpkin (false)
this.targetFoodIndex = -1; // Index of the specific food emoji this NPC is targeting- Stores which food emoji in the displayedEmojis array this NPC is eating; -1 means no specific food target
this.setNewTarget(); // Set an initial target- Calls setNewTarget() to decide whether to pursue food or pumpkin and set the target position