Now let’s work on creating a new object for our game, “Food.” “Food” objects behave just like the “Balls” do except that they have the ability to be eaten by the Player. However, before we can do this, we need to code the ability for something to be removed from the “CanvasPanel”
Go back to the “CanvasPanel” file and add the code as shown here to create the “removeSprite” function.
This function will remove the given sprite and its shape from the “CanvasPanel,” making it disappear from the game.
Next, open up the “Food” file and complete the code as shown here to create it’s constructor. Don’t forget the extends keyword section on line 5!
Remember, by extending from “Ball” we are inheriting all of its data.
Because of this inheritance, our constructor is very small, since the only change we need here is the diameter change. However, there are in fact a few ways this class will be different, we’ll code those next.
Next, complete the code as shown here to add on the new functions unique to the “Food” class.
First off we have a new “collision” function, we’ll finish this later so we just have it return false for now.
Then, we override the old “move” function of the “Ball”. We tell it to move like it normally would, but if it detects a collision, we tell it to remove itself from its canvas.
Lastly, we override the “getColor” function to make “Food” look different from normal “Balls.”
Now we need a way to add Food into our game, which means another Button, navigate back into the “ControlPanel” file to get started.
First off, let’s create a new class variable to use for this Button.
Then we add the code for what this button will actually do, just like with the others. For the “addFood” button, we’ll also spawn it at a random x,y position.
With all this code done, go ahead and test it out! If the third button doesn’t show up, you might need to resize the window.
If done correctly, there should be a new button that can spawn our new “Food” objects! If not, go back and double check your code for errors.