Next, copy the CSS and JS files from here. This code hides the scrollbar, makes the canvas fill the screen, and includes basic function declarations.
Then, write the Ball class in the JS file as follows.
Now, you can create a ball through the Ball class constructor and draw it by calling ball.draw(). Additionally, implement a function within the class to update the ball's position, enabling it to bounce off walls.
Now, let's create balls on the canvas. The following code generates balls with random positions, speeds, and sizes, and draws them on the canvas.
When opened in a browser, you will see balls moving against a black background.
2. Implementing Collision Detection
Next, let's implement collision detection. Add the following method to the Ball constructor.
Then, call the collisionDetect method for each ball within the loop function.
You will see the balls change color when they collide on screen.
3. Enhancing the Example
3.1. User-Controlled Features
Let's add a user-controlled ball that disappears when it touches the balls. Additionally, let's improve the class design.
First, define a general Shape class that will be inherited by both the user-controlled ball and regular balls. The Shape class will contain only the shared properties of position and velocity for the Ball and EvilCircle classes.
Then, modify the Ball class to inherit from Shape and adjust the constructor. Also, add an exists property that indicates whether the ball exists (becomes false if eaten by the user-controlled ball) and modify the collision detection function to check only when it exists.
Now, let's define the user-controlled ball and the EvilCircle that eats the balls. The EvilCircle will inherit from Shape and add a method to eat the balls. Although there will only be one of these, we will use a class for practice. Follow the example as directed.
Then, create the evilCircle and add it to the loop function.
3.2. Displaying the Number of Balls
Finally, let's display the number of balls on the screen. Place a <p> tag below the <h1> element. Copy the styling from the example.
Then, update the content of the <p> tag by counting the balls during each call to the loop function.
When you run this in a browser, you will see a white circle that the user can control using the keys W, A, S, D, and the number of balls decreases as they are eaten.