Having keyPressed() in multiple classes

I am having some problems with void keypress() function. If i use it in the main class it works, but if i then try to call a class where i do the maths and then draw() which works in that class and draw on canvas created in main class, but the keypress function doesn’t trigger when i type in that class. I tried to add another setup() in that class but it didn’t change anything.
The problem is also that if i want to change things from main class by keypress is that i have to always create a new clusters class or i can’t call it’s functions but i don’t want to do that. I want to change the class that i already created.
< code:
class clusters (){
void draw(){
draws on canvas…
}
void keyPressed(){
print(key);
switch(key){
case ‘x’:
zoom+=0.5;
firstdraw=true;
break;
case ‘y’:
zoom-=0.5;
firstdraw=true;
break;
}
}
} <

Yeah, keys are not automatically passed to the class(es) - you have to call your keyPressed located inside the class from the main keyPressed. I can make an example if you want.

in the main part of the Sketch

void keyPressed() {
   player.keyPressed(); 
}

in the Player class :

void keyPressed() {

    switch(key) {
    case '1':
      //
      break; 
    }//switch 
}//method

Not sure if I understand you there. To make a new class or new objects from the class is not the right way. Instead you change its values by saying player.x++, (call this ouside the class) or make a method moveRight() in the class and call it like player.moveRight();

Hey, and welcome to the forum!

Great to have you here!

Warm regards,

Chrisir :wink:

P.S.

Here is a full example:



Clusters c = new Clusters();  

void setup() {
  // init
  size(1300, 700);
} // func 

void draw() {
  // runs on and on 
  background(0);
  c.draw();
}

void keyPressed() {
  c.keyPressed();
}

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

class Clusters {

  float x=300, y=300; 

  void draw() {
    //draws on canvas…
    ellipse(x, y, 18, 18);
  }

  void keyPressed() {
    print(key);
    switch(key) {
    case 'x':
      x+=5;
      //firstdraw=true;
      break;
    case 'y':
      y-=0.5;
      //firstdraw=true;
      break;
    }//switch
  }//func
}//class 
//

Well u get errors saying the sketch path is not set.
And then about 20 lines where it crashes and at the end runtimeexception: java.lang.reflect.invocationtargetexception.

FIXED IT:
needed to only initialize the variable above setup as <player p and then in setup() p=new player() > maybe because i had arguments that i put to class that the error had acoured.

1 Like