xxxxxxxxxx
89
// Fruit Class: Manages the creation, movement, and display of fruit objects
class Fruit {
constructor(x, y, initialSpeed, xSpeed) {
this.x = x;
this.y = y;
this.radius = random(30, 60); // Random size for each fruit
this.initialSpeed = initialSpeed; // Initial upward speed of the fruit
this.ySpeed = initialSpeed; // The vertical speed affected by gravity
this.xSpeed = xSpeed; // Horizontal drift
this.gravity = 0.1; // Gravity applied to fruit's upward motion
// Randomly assign a fruit type (e.g., pineapple, watermelon, etc.)
let rand = random();
if (rand < 0.2) {
this.type = 'pineapple';
} else if (rand < 0.4) {
this.type = 'watermelon';
} else if (rand < 0.6) {
this.type = 'banana';
} else if (rand < 0.8) {
this.type = 'coconut';
} else {
this.type = 'orange';
}
}
// Update fruit's position
update() {
this.x += this.xSpeed; // Move fruit horizontally
this.y -= this.ySpeed; // Move fruit upward (affected by gravity)
this.ySpeed -= this.gravity; // Apply gravity to slow the fruit down and make it fall
// Reset the fruit when it falls below the screen
if (this.y > height + this.radius) {
this.reset();
}
}
// Display the fruit based on its type
display() {
noStroke();
if (this.type === 'pineapple') {
image(pineappleImg, this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2);
} else if (this.type === 'watermelon') {
image(watermelonImg, this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2);
} else if (this.type === 'banana') {
image(bananaImg, this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2);
} else if (this.type === 'coconut') {
image(coconutImg, this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2);
} else if (this.type === 'orange') {
image(orangeImg, this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2);
}
}
// Check if the fruit has been sliced by the user
isSliced(mx, my) {
return dist(mx, my, this.x, this.y) < this.radius; // Check if the mouse position is within the fruit's radius
}
// Reset fruit position and type after it goes below the screen
reset() {
this.x = random(50, 350);
this.y = height + this.radius;
this.ySpeed = random(8, 10); // Reassign upward speed
this.xSpeed = random(-2, 2); // Horizontal drift
// Randomly assign a new fruit type and size
let rand = random();
if (rand < 0.2) {
this.type = 'pineapple';
} else if (rand < 0.4) {
this.type = 'watermelon';
} else if (rand < 0.6) {
this.type = 'banana';
} else if (rand < 0.8) {
this.type = 'coconut';
} else {
this.type = 'orange';
}
this.radius = random(30, 60); // Random fruit size
}
// Check if the fruit was missed by the user
missed() {
return this.y < -this.radius; // Fruit is missed when it moves off the screen
}
}