Help with mousePressed

#1

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? :slight_smile:

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;
    }
  }
}
1 Like

#2

Hi,

Check out the mouseClicked function:
https://processing.org/reference/mouseClicked_.html

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.

2 Likes

#3

Hi, thanks for the reply. I’m still kind of stuck, this is what I have so far…

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();
}

void mouseClicked() {
  if (move == true){
  t.move();
  c.move();
  }
}

0 Likes

#4

Consider this simple sketch and try to understand how it works.

The principle will be the same in your case:

boolean lightOn;

void setup() {
  size(500, 500);
  lightOn = true;
}


void draw() {
  if (lightOn) {
    background(230);
  } else {
    background(20);
  }
}

void mouseClicked() {
  lightOn = !lightOn;
}
3 Likes

#5

Thanks very much! I understand it now (I think haha) :slight_smile:

This is my finished code.

Train t;
Chimney c;

boolean move = false;

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 (move) {
   t.move();
   c.move();
 }
 
}

void mouseClicked() {
 move = !move;
}

3 Likes