what I did is create a table with each keyboard command, then call it from my love.keypressed function:
My Input.lua file looks like this:
Code: Select all
Input = {
["up"] = function(v)
Player:setSpeed(Player.ctlFwdSpeed * v)
end,
["down"] = function(v)
Player:setSpeed(Player.ctlBackSpeed * v)
end,
["left"] = function(v)
Player:setturnSpeed(-Player.ctlTurnSpeed * v)
end,
["right"] = function(v)
Player:setturnSpeed(Player.ctlTurnSpeed * v)
end,
}
and in love.keypressed, something like
Code: Select all
function love.keypressed( key, scancode, isrepeat )
if Input[key] then
Input[key](1)
end
LastKey=key
end
function love.keyreleased(key)
if Input[key] then
Input[key](0)
end
LastKey = ""
end
So the idea is that a key down event calls the relevant function in Input, with a 1 in the parameter. This turns the movement or rotation on.
Then when the user releases the key, this calls the same function, but with 0 as the parameter. This turns off the movement or rotation.
And, as has been suggested above, it might be wise to use scancodes to actually accomplish this. What I plan to do in the long run is allow the player to map keys, and I'll do some quick function assignments to map the actions to keypresses, kind of like this:
Input[UpKey] = Input["up"]
I have to test whether this actually works, but I think it will do what I'm hoping. If that doesn't work, I can use loadstring to accomplish the same thing, by building a function at runtime that basically just calls the relevant action.
Also, as this is a prototype, I'll probably better encapsulate the functions, so instead of the Input file above, my functions would look like:
Code: Select all
["up"] = function(v)
Player:foward(v)
end,
Then the "forward" action can change dynamically, if the Player object changes. (this actually will change in this game, as the player will switch between different vehicles and on foot requiring different driving and movement controls.)