Ok nice try for a beginner. There is just one major mistake you made:
The key
variable stores the key that was most recently pressed. So when A is pressed, the first circle starts moving, but then when you press B, the key
variable now holds ‘b’ and not ‘a’ anymore. So the first circle stops moving.
A way to fix this problem (and also the other one that d stops all circles) is to give each each ball a variable that tells wether they are currently moving or not. The datatype we’d use for this is boolean
, since it is either true
or false
. You can name those for example
boolean circlexMoving;
boolean circleyMoving;
boolean circlexyMoving;
These will automatically be set to false
when the sketch is started. (Btw, the second line in your code in void setup()
is actually not necessary, since floats and ints always start at a value of 0).
The next change you need to make is that when the buttons a, b or c are being pressed, instead of moving the balls in the corresponding direction, you set the corresponding boolean to true.
For example:
if (key == 'a') {
circlexMoving = true;
}
Now you shouldn’t delete the code that makes the balls move. Instead you should replace the condition in the if statements with the corresponding booleans.
For example:
if (circlexMoving) {
circleX = circleX + xspeed;
if(circleX > width || circleX < 0) {
xspeed = xspeed * -1.0;
}
}
Just so that you know, if (circlexMoving)
is the same as if (circlexMoving == true)
And finally, it’s time to implement the last feature. This is now very simple, as you can just add a condition that checks if D is being pressed and if it is, then set all ballMoving variables to false.
This should look something like this:
if (key == 'd') {
circlexMoving = false;
circleyMoving = false;
circlexyMoving = false;
}
Here’s what the final code looks like:
float circleX;
float xspeed = 1;
boolean circlexMoving;
float circleY;
float yspeed = 1;
boolean circleyMoving;
float circleXY;
float xyspeed = 1;
boolean circlexyMoving;
void setup() {
size(640, 360);
}
void draw() {
background(51);
fill(48, 90, 206);
stroke(255);
ellipse(circleX, 180, 32, 32);
if (key == 'a') {
circlexMoving = true;
}
if (circlexMoving) {
circleX = circleX + xspeed;
if (circleX > width || circleX < 0) {
xspeed = xspeed * -1.0;
}
}
fill(255, 0, 2);
ellipse(300, circleY, 32, 32);
if (key == 'b') {
circleyMoving = true;
}
if (circleyMoving) {
circleY = circleY + yspeed;
if (circleY > height || circleY < 0) {
yspeed = yspeed * -1.0;
}
}
fill(0, 400, 0);
ellipse(circleXY, circleXY, 32, 32);
if (key == 'c') {
circlexyMoving = true;
}
if (circlexyMoving) {
circleXY = circleXY + xyspeed;
if (circleXY > height || circleXY < 0) {
xyspeed = xyspeed * -1.0;
}
}
if (key == 'd') {
circlexMoving = false;
circleyMoving = false;
circlexyMoving = false;
}
}