Hi, I’m making a simple program to make a train move across the screen. At the moment the train moves only when I hold down my mouse button. Would anyone be able to help me make the train move when I press the mouse button once, and then stop once I click it again?
Thanks!
Train t;
Chimney c;
void setup() {
size(600, 400);
t = new Train();
c = new Chimney();
}
void draw() {
background(0, 0, 200);
t.display();
t.reset();
c.display();
c.reset();
if (mousePressed) {
t.move();
c.move();
}
}
class Chimney {
float xChimney, yChimney;
float xSpeed;
Chimney() {
xChimney = 380;
yChimney = 100;
xSpeed = 3;
}
void display() {
fill(0, 200, 0);
rect(xChimney, yChimney, 20, 50);
}
void move() {
xChimney = xChimney + xSpeed;
}
void reset() {
if (xChimney > width) {
xChimney = -200;
}
}
}
class Train {
float x, y;
float xSpeed;
Train() {
x = 200;
y = 150;
xSpeed = 3;
}
void display() {
noStroke();
fill(200, 0, 0);
rect(x, y, 200, 100);
}
void move() {
x = x + xSpeed;
}
void reset() {
if (x > width) {
x = -200;
}
}
}
Then you can have a state variable (let’s call it move) that is a boolean.
Every time you enter the mouseClicked function, you turn on or off the move variable.
In draw you then simply need to check the value of the move variable. If it is true you move your train otherwise you do nothing.