Handmade Network»Forums
Doeke
33 posts
None
is void keyPressed() and void mousePressed etc. bad practise?
Edited by Doeke on Reason: Initial post
I don't really know where to address this question, I thought the handmade network would give me the best advice.

I'm using processing, and they have functions like `mousePressed` and `keyPressed`:

1
2
3
4
5
6
7
    void mousePressed() {
      if (value == 0) {
        value = 255;
      } else {
        value = 0;
      }
    }


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
void keyPressed() {
  if (key == 'r' || key == 'R') {
    Shape s = get(root, mouseX, mouseY);

    if (s != null && s.parent != null) {
       rotate(s.parent, s.parent.rotation_step());
    }
  }
  if (key == 's' || key == 'S') {
    save_pdf = true;
  }
}


While they can be convenient, I have the feeling it's bad practise seen from a game designer perspective.
One reason is that it can scatter logic over multiple places.
Also, it's unclear at what point `mousePressed` is being called (start of frame?, end of frame?, any point?).

Is it a good practise to only have input logic in the same scope that is using that logic?

For small projects it does not really matter, but I don't want to create bad habits.

Hope someone can share their thoughts.




https://processing.org/reference/keyPressed_.html

https://processing.org/reference/mousePressed_.html
Mārtiņš Možeiko
2559 posts / 2 projects
is void keyPressed() and void mousePressed etc. bad practise?
There is nothing wrong with such functions for simple frameworks. In fact, popular GL windowing framework GLFW has almost exactly same callback functions.

As Processing is written in Java, you need to understand how Java delivers events to know when these functions will be called. keyCode documentation at https://processing.org/reference/keyCode.html links to KeyEvent java reference where you should start reading and following its source code to understand how that works, if you are interested in that.
183 posts / 1 project
is void keyPressed() and void mousePressed etc. bad practise?
If you have a "processEvents" method or similar in a framework, you can define exactly in which order these will happen. If you don't want to scatter logic too much, you can put all component event lambdas in your initialization method.