JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/molleindustria/p5.play/lib/p5.play.js"></script>
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/addons/p5.sound.min.js"></script>-->
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body></body>
</html>
JavaScript
//let soundFile;
let squareSize = 50; // size of the square
let speed, angle; // speed and angle of movement
let clickCount = 0; // number of clicks on the square
let missCount = 0; // number of misses
//function preload() {
//soundFormats('mp3');
//soundFile = loadSound('https://assets.mixkit.co/active_storage/sfx/1662/1662-preview.mp3');
//}
function setup() {
createCanvas(400, 400);
resetSquare();
}
function draw() {
background(255); // clear the canvas
// move the square
squareX += speed * cos(angle);
squareY += speed * sin(angle);
// check if the square is out of bounds
if (squareX < 0 || squareX > width - squareSize || squareY < 0 || squareY > height - squareSize) {
// change the speed and direction of movement
speed = random(1, 5);
// check if the square is out of bounds
if (squareX < 0) {
// change the angle to reflect off the left edge of the canvas
angle = PI - angle;
} else if (squareX > width - squareSize) {
// change the angle to reflect off the right edge of the canvas
angle = PI - angle;
}
if (squareY < 0) {
// change the angle to reflect off the top edge of the canvas
angle = -angle;
} else if (squareY > height - squareSize) {
// change the angle to reflect off the bottom edge of the canvas
angle = -angle;
}
}
// draw the square
fill(255, 0, 0);
rect(squareX, squareY, squareSize, squareSize);
// display the click and miss counts
fill(0, 0, 255);
...