Jump to content

Keyboard and Mouse Events

Averice

3,366 views

I think I posted this module on the forums in order to help someone a few weeks ago, but I thought It'd get more use if I created a blog post so it doesn't get diluted down in the forums.

 

I've written this event module to make it easy to add keyboard and mouse button binds and it's come in handy to me for quite a few little scripts.

 

Once again excuse the poor spacing as copy and paste here seems to remove my tabs.

 

event.lua

-- Event module written by Averice

event = {}
event.inputBinds = {}
event.mouseBinds = {}

function event.CheckInput()
local succ, err;
for key,tab in pairs(event.inputBinds) do
if( App.window:KeyHit(key) ) then
for k, v in pairs(tab) do
if( not v.Held ) then
succ, err = pcall(v.Func, unpack(v.Args));
if not succ then
print("Event Error[Key]["..k.."]: "..err);
end
end
end
end
if( App.window:KeyDown(key) ) then
for k, v in pairs(tab) do
if( v.Held ) then
succ, err = pcall(v.Func, unpack(v.Args));
if not succ then
print("Event Error[Key]["..k.."]: "..err);
end
end
end
end
end
for but, tab in pairs(event.mouseBinds) do
if( App.window:MouseDown(but) ) then
for k, v in pairs(tab) do
succ, err = pcall(v.Func, unpack(v.Args));
if not succ then
print("Event Error[Mouse]["..k.."]: "..err);
end
end
end
end
end

function event.AddInputBind(key, name, held, func, ...)
local newInput = {
Func = func,
Args = {...},
Held = held or false
}
event.inputBinds[key] = event.inputBinds[key] or {};
event.inputBinds[key][name] = newInput;
end

function event.AddMouseBind(but, name, func, ...)
local newInput = {
Func = func,
Args = {...}
}
event.mouseBinds[but] = event.mouseBinds[but] or {}
event.mouseBinds[but][name] = newInput;
end

function event.RemoveInputBind(key, name)
if( event.inputBinds[key] and event.inputBinds[key][name] ) then
event.inputBinds[key][name] = nil;
end
end

function event.RemoveMouseBind(but, name)
if( event.mouseBinds[but] and event.mouseBinds[but][name] ) then
event.mouseBinds[but][name] = nil;
end
end

 

It's usage is really straight forward, you import the script, and in your App.loop you'll put

event.CheckInput();

This will check for your binds and run them if needed so you don't have to fill your App.loop with key binds.

 

To add a keyboard bind "event.AddInputBind(key, name, held, function, args);

local function printStuff(...)
print("Hello", ...);
end

event.AddInputBind(Key.A, "RandomName", false, printStuff, "How", "are", "you") -- varargs once again.
--when the A key is pushed it should output, "Hello How are you";
-- if 'held' is true it will keep printing while it's held.

--To remove it we use it's name and key.
event.RemoveInputBind(Key.A, "RandomName");

-- Mouse bind functions are the same, just use event.AddMouseBind and event.RemoveMouseBind
-- mouse bind functions are considered always held. Add a check to your function if you only
-- want it done per click.

 

A quick snippet that I use in my splash screen with my StateManager module to cancel the splash if escape is pushed.

event.AddInputBind(Key.Escape, "__SHARDSPLASH", false, function() StateManager:Pop() end);



5 Comments


Recommended Comments

This should be very useful thank you!

 

One question that isn't apparent to me just looking at the code and examples. If one wanted to for example show a HUD item only when a key was held. Would that use a combination of both true/false versions of held with AddInputBind, with the 'release' trigger using false? Or is that outside the scope of what can be accomplished with this as-is?

 

TYVM!

 

EDIT: HUD items may not have been the best choice of example as now that I think about it, if they are drawn while the key is held, then they won't be drawn when the key is not held. But there are other cases not involving rendering where certain states could be desired to be triggered on/off based on held/released.

Share this comment


Link to comment

I can add an onrelease mechanic to this tomorrow as I'm on my phone right now and typing code is difficult on this. It's not too hard just an extra variable for the loop on each key.

Share this comment


Link to comment

Thank you for this elegant lib.

 

A remark: there is no MouseHit event binding. I mean, it's easy to write it using what you've written so far. Do you consider adding it?

 

I'm asking this because I would like to use an "official" version :) in case you update it.

Share this comment


Link to comment

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Add a comment...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Blog Entries

    • By jen in jen's Blog 3
      I thought I would share my experience on this; if you're working on Multiplayer, you will need to protect your packets. The solution is simple, let's go through how we can achieve this by implementing what Valve calls "challenge codes". (Some reading on the topic from Valve here: https://developer.valvesoftware.com/wiki/Master_Server_Query_Protocol#Challenge_response).
      Disclaimer: this doesn't cover other security techniques like authoritative server or encryption.
      So, I've worked on Border Recon last year (I think) and I needed a way to protect my server/client packets. There was no need for me to re-invent the wheel, I just had to copy what Valve has had for a  long time - challenge  codes.
      The idea behind challenge codes is similar to Captcha, but not exactly. Think of it like this: for every packet submitted to the server, it must be verified - how? By requiring the client to solve challenges our server provides.
      To implement this we need to have the following:
      A randomised formula in the server i.e.: a = b * c / d + e or a = b / c + d - e, be creative - it can be any combination of basic arithmetic or some fancy logic you like and can be however long as you want - do consider that the longer the formula, the more work your server has to do to make the computation.  Copy the same formula to the client. A random number generator.  So the idea here is:
      (Server) Generate a random number (see 3 above) of which the result would become the challenge code, (Server) run it through our formula and record the result. (Client) And then, we hand over the challenge code to the client to solve (an authentic client would have the same formula implemented in its program as we have on the server). For every packet received from the player, a new challenge code is created (and the player is notified of this change by the server in response). For every other packet, a new challenge code is created. (Client) Every packet sent to the server by the client must have a challenge code and its answer embedded.  (Server receives the packet) Run the challenge code again to our formula and compare the result to the answer embedded on the client's packet. (Server) If the answers are different, reject the packet, no changes to the player's state. The advantage(s) of this strategy in terms of achieving the protection we need to secure our server:
      - For every packet sent, new challenge code is created. Typically, game clients (especially FPS) will update its state in a matter of ms so even if a cheater is successful at sniffing the answer to a challenge code it would be invalidated almost instantaneously. 
      - Lightweight solution. No encryption needed. 
      Disadvantage(s):
      - The formula to answering the challenge code is embedded to the client, a cheater can de-compile the client and uncover the formula. Luckily, we have other anti-cheat solutions for that; you can implement another anti-cheat solution i.e. checking file checksums to verify the integrity of your game files and more (there are third-party anti cheat solutions out there that you can use to protect your game files).
       
       
       
    • By Josh in Josh's Dev Blog 4
      New commands in Turbo Engine will add better support for multiple monitors. The new Display class lets you iterate through all your monitors:
      for (int n = 0; n < CountDisplays(); ++n) { auto display = GetDisplay(n); Print(display->GetPosition()); //monitor XY coordinates Print(display->GetSize()); //monitor size Print(display->GetScale()); //DPI scaling } The CreateWindow() function now takes a parameter for the monitor to create the window on / relative to.
      auto display = GetDisplay(0); Vec2 scale = display->GetScale(); auto window = CreateWindow(display, "My Game", 0, 0, 1280.0 * scale.x, 720.0 * scale.y, WINDOW_TITLEBAR | WINDOW_RESIZABLE); The WINDOW_CENTER style can be used to center the window on one display.
      You can use GetDisplay(DISPLAY_PRIMARY) to retrieve the main display. This will be the same as GetDisplay(0) on systems with only one monitor.
    • By Josh in Josh's Dev Blog 1
      A huge update is available for Turbo Engine Beta.
      Hardware tessellation adds geometric detail to your models and smooths out sharp corners. The new terrain system is live, with fast performance, displacement, and support for up to 255 material layers. Plugins are now working, with sample code for loading MD3 models and VTF textures. Shader families eliminate the need to specify a lot of different shaders in a material file. Support for multiple monitors and better control of DPI scaling. Notes:
      Terrain currently has cracks between LOD stages, as I have not yet decided how I want to handle this. Tessellation has some "shimmering" effects at some resolutions. Terrain may display a wire grid on parts. Directional lights are supported but cast no shadows. Tested in Nvidia and AMD, did not test on Intel. Subscribers can get the latest beta in the private forum here.

       
       
×
×
  • Create New...