Should I push keypresses to vehicles when they're pressed, or should vehicles pull keys pressed from the engine?
I have a vehicle object, which has location, velocity and accelleration members (among other things) and an update method, during which it updates its location based on its velocity, and its vevlocity based on its accelleration.
I have a game object which contains the game loop, which calls the update method on the vehicle.
If the player controls the vehicle with the arrow keys, should a keypress set the accelleration (push) and a key-release clear the velocity, or should the vehicle ask the game-engine if the accellerate key is pressed (pull)? I think a push would mean that the keyboard control module would need to know about vehicles, whereas pull would mean a vehicle needs to know specific keyboard controls.
I think a related question would be something like: should all objects know about all other objects, or should there be a strict hierarchy, so objects can ask things / tell things to other objects up the tree, but not down (or vice-versa)?
You should try and follow an Subscribing/Observer pattern. You put all the key capture code into one singleton InputManager and then each object that requires reaction to input registers with the manager.
The manager holds the list of subscribed objects and sends events to them when the keys are pressed/depressed. Just don't forget to unsubscribe when the object is deleted or 'loses focus'.
This avoids the polling problem. There are very few exceptions where a polling solution is desirable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With