Function within mousePressed function doesn't work

Hello. I am still kind of new to processing. I have been trying to create a game with moving platform(I called it plank), balls which shoot down bricks. I am currently creating the platform and I want it to move on the x axis with my cursor when my mouse is pressed, but it does not. I would really appreciate help.

Plank myPlank;

void setup(){
  size(500,500);
  myPlank = new Plank();
}
  

void draw(){
  background(0);
  myPlank.display();
}

class Plank{
  int xpos;
  int ypos;
  int l;
  int w;
  int col;
  
  Plank(){
   xpos = width/2;
   ypos = height-(height*1/5);
   l = width/10;
   w = height/100;
   col = 255;
  }
  
   void display() {
     rectMode(CENTER);
     fill(col);
     rect(xpos,ypos,l,w);
   }
   void mousePressed(){
     myPlank.move();     
   }
   void move(){
     xpos = mouseX;
     if(xpos<0+l/2||xpos>width-l/2){
       xpos+=l/2;
     }
   }
}

This inside the class won’t work

It’s hidden inside the class

Make a mousePressed outside the class and call the function mousePressed that is in the class from there

1 Like

Remark

Other than

void mousePressed() {
  myPlank.move();
}

we want a mousePressed that works throughout and not only once every click.

This is done with a variable of the same name mousePressed (the name that also the function has) :

void draw() {
  background(0);
  myPlank.display();

  if (mousePressed) {
    myPlank.move();
  }
}

Remark

not sure what you do here, but add something to the pos is different for left and right side.

    if (xpos<0+l/2||xpos>width-l/2) {
      xpos+=l/2;

maybe:

if (xpos<0+l/2) {
      xpos+=l/2; // left side 
}
if (xpos>width-l/2) {
      xpos-=l/2; // right side 
}

(I did not work on this further)

Sketch


Plank myPlank;

void setup() {
  size(500, 500);
  myPlank = new Plank();
}

void draw() {
  background(0);
  myPlank.display();

  if (mousePressed) {
    myPlank.move();
  }
}

// ============================================================================

class Plank {
  int xpos;
  int ypos;
  int l;
  int w;
  int col;

  Plank() {
    xpos = width/2;
    ypos = height-(height*1/5);
    l = width/10;
    w = height/100;
    col = 255;
  }

  void display() {
    rectMode(CENTER);
    fill(col);
    rect(xpos, ypos, l, w);
  }

  void move() {
    xpos = mouseX;
    if (xpos<0+l/2||xpos>width-l/2) {
      xpos+=l/2;
    }
  }
}
//

2 Likes

Appreciate your help. Everything is working now. Thanks :wink:

2 Likes