January 12, 2014

Bind Multiple Inputs To An Action In Leadwerks Indie Edition

It is generally considered poor form to have key bindings buried in the middle of a class.  This code will let you keep your key and mouse bindings separate from your Leadwerks Lua classes, and also let you bind multiple inputs to a single action.

Create a new script in your Scripts folder named ActionMap.lua.  Add the following code:

ActionMap = {}
ActionMap.forward = { "W" }
ActionMap.back = { "S" }
ActionMap.left = { "A" }
ActionMap.right = { "D" }
ActionMap.fire = { 1 }
ActionMap.jump = { "Space" }
ActionMap.reload = { "R" }

ActionMap.use = { "E", 2 }
ActionMap.debugPhysics = { "P" }

function ActionMap:IsHit(action)
    local i=1
    local window=Window:GetCurrent()
    while action[i]~=nil do
        if (type(action[i]) == "string") then
            if window:KeyHit(Key[action[i]]) then
                return true
            end
        end
        if (type(action[i]) == "number") then
            if window:MouseHit(action[i]) then
                return true
            end
        end
        i=i+1
    end
    return false
end

function ActionMap:IsDown(action)
    local i=1
    local window=Window:GetCurrent()
    while action[i]~=nil do
        if (type(action[i]) == "string") then
            if window:KeyDown(Key[action[i]]) then
                return true
            end
        end
        if (type(action[i]) == "number") then
            if window:MouseDown(action[i]) then
                return true
            end
        end
        i=i+1
    end
    return false
end


Now open your FPSPlayer.lua folder.  At the top, add:

import "Scripts/ActionMap.lua"

Now search for the following code:

if window:KeyHit(Key.E) then

Change it to the following code:

if ActionMap:IsHit(ActionMap.use) then

Now run your game.  You'll notice you can still use "E" to trigger the Use method, but you can also right-click to trigger the Use method.

When you populate your ActionMaps, a number is a mouse button, and a string is one of the constants from the Key object.  Adding saving/loading key bindings to a file and allowing your customers to rebind their keys is left as an exercise for the reader.

No comments: