xxxxxxxxxx
88
let surfer; // Variable to hold the surfer image
let surferX = 300; // Surfer's horizontal position
let surferY; // Surfer's vertical position
let surferSpeed = 5; // Surfer's movement speed
let waves = []; // Array to hold wave objects
let waveCount = 5; // Number of waves to create
function preload() {
surfer = loadImage('01.png'); // Load surfer image
}
function setup() {
createCanvas(650, 500);
// Initialize wave objects with random parameters
for (let i = 0; i < waveCount; i++) {
waves.push(new Wave(i * (width / waveCount))); // Position waves across the canvas
}
}
function draw() {
background('#F8F1B0');
// Draw all waves
for (let wave of waves) {
wave.update();
wave.display();
}
// Set surfer's Y position based on the average wave height at surferX
surferY = getWaveHeight(surferX) - surfer.height / 29; // Center the surfer on the wave
// Draw surfer
image(surfer, surferX, surferY, 50, 50);
// Surfer movement control
if (keyIsDown(LEFT_ARROW)) {
surferX -= surferSpeed;
}
if (keyIsDown(RIGHT_ARROW)) {
surferX += surferSpeed;
}
// Boundaries for surfer movement
surferX = constrain(surferX, 0, width - 50);
}
// Function to get the average height of the waves at a specific x position
function getWaveHeight(x) {
let totalHeight = 0;
for (let wave of waves) {
totalHeight += wave.getWaveHeight(x);
}
return totalHeight / waves.length; // Average height of all waves
}
// Wave class to create wave objects
class Wave {
constructor(xOffset) {
this.xOffset = xOffset; // Offset for this wave
this.waveAmplitude = random(30, 70); // Random wave height
this.waveFrequency = random(0.02, 0.05); // Random frequency
this.waveSpeed = random(0.02, 0.1); // Random speed
this.offset = random(TWO_PI); // Random phase offset
}
update() {
this.offset += this.waveSpeed; // Move the wave over time
}
display() {
fill(118, 170, 206);
beginShape();
for (let x = 0; x <= width; x += 5) { // Decrease step for smoother waves
let y = height / 1.2 + sin(x * this.waveFrequency + this.offset) * this.waveAmplitude; // Smooth wave using sine function
vertex(x, y);
}
vertex(width, height);
vertex(0, height);
endShape(CLOSE);
}
getWaveHeight(x) {
// Calculate the height of the wave at a specific x position
return height / 2 + sin(x * this.waveFrequency + this.offset) * this.waveAmplitude;
}
}