For this bouncing ball exercise, I include the sound file to make the bounce more interesting, but I face this problem which my rectanglar won’t rotate around the circle.
https://editor.p5js.org/LunaChen/full/sGJG7qhKf
First set up the variables that I might need, I definitly added some afterwards.
Sound file and animate is what new to me.
let r, g, b, x, y, xspeed, yspeed, soundFile;
let animate = false;
const radius = 25;
let angle=0;
For this function, I just copied from the example, and add the sound file I found on internet in the folder I created called assets.
function preload() {
soundFormats('mp3', 'ogg');
soundFile = loadSound('assets/toy-button.mp3');
}
In setup function, I create canvas and identify the value of every variable.
function setup() {
createCanvas(640, 360);
x = width / 2;
y = height / 2;
xspeed = random(3, 10);
yspeed = random(3, 10);
r = random(255);
g = random(255);
b = random(255);
angleMode(DEGREES);
}
Mouse pressed function used to stop the animation, the ! sign means “don’t”
function mousePressed() {
animate = !animate;
soundFile.stop();
}
function draw() {
background(0);
noStroke();
fill(r, g, b);
circle(x, y, radius*2);
translate(x, y);
rotate(-angle*3);
fill(r,g,b);
rect(30, 30, 30, 30);
if (animate) {
x += xspeed;
y += yspeed;
}
In the draw function, draw the circle and rectangular with random color. Then include animate program.
//When hit the wall, speed=-1,color change
if (x <= radius || x >= width - radius) {
xspeed = xspeed * -1;
r = random(255);
g = random(255);
b = random(255);
soundFile.play();
}
if (y <= radius || y >= height - radius) {
yspeed = yspeed * -1;
r = random(255);
g = random(255);
b = random(255);
soundFile.play();
}
}
Finally include the function when the circle hit the wall, make it bounce back include sound and change color at the same time. Use if function.