Files
sunny9898/task4/Q2d/index.js
louiscklaw 5637fbf94f update,
2025-02-01 02:07:58 +08:00

87 lines
1.6 KiB
JavaScript

let xpos, ypos, size, numParts;
let last_body_x;
let start_deg;
function setup() {
createCanvas(400, 400);
restartRight();
}
function draw() {
background(220);
last_body_x = caterpillar(xpos, ypos, size, numParts);
xpos -= 2;
if (last_body_x < 0) {
restartRight();
}
}
// x, y: center point of head
// diam: size of the head
// num: number of body parts
function caterpillar(x, y, diam, num) {
// [Your Code Here]
last_body_x = 0;
last_body_x = body(x + diam * 0.8, y, diam * 0.8, num);
head(x, y + sin(start_deg) * 20, diam);
start_deg = start_deg + 0.1;
return last_body_x;
}
function restartRight() {
// [Your Code Here]
xpos = 400;
ypos = Math.floor(random(20, 200 - 20));
size = Math.floor(random(20, 50));
numParts = Math.floor(random(5, 20));
start_deg = 0;
}
function body(x, y, diam, repeat) {
invert = 0;
last_body_x = 0;
for (i = 0; i < repeat; i++) {
if (invert == 0) {
fill("rgb(0,200,0)");
invert = 1;
} else {
fill("rgb(0,255,0)");
invert = 0;
}
last_body_x = x + i * diam * 0.8;
circle(last_body_x, y + sin(start_deg + i) * 20, diam);
}
return last_body_x;
}
// x, y: the center of the head
// diam: the diameter of the head
function head(x, y, diam) {
// [Your Code Here]
fill("rgb(0,255,0)");
circle(x, y, diam);
// eyes
x_factor = diam * 0.15;
y_factor = diam * 0.1;
fill("rgb(0,0,0)");
circle(x - x_factor, y - y_factor, x_factor);
fill("rgb(0,0,0)");
circle(x + x_factor, y - y_factor, x_factor);
noFill();
arc(x, y + y_factor, x_factor * 2, x_factor * 2, 0, PI);
}