Register
handmade.network»Forums»is void keyPressed() and void mousePressed etc. bad practise?
Doeke
31 posts

None

is void keyPressed() and void mousePressed etc. bad practise?
4 months, 2 weeks ago Edited by Doeke on March 21, 2020, 9:27 a.m. 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

None
Mārtiņš Možeiko
2107 posts / 1 project
is void keyPressed() and void mousePressed etc. bad practise?
4 months, 2 weeks ago
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.
38 posts / 1 project
is void keyPressed() and void mousePressed etc. bad practise?
2 months, 2 weeks ago
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.