physics: Add sanity checks and minor optimizations (#650)
- Throw error if an unsupported attribute is encountered. - Throw errors for invalid function arguments. - Optimize out attributes with a value of 1.
This commit is contained in:
parent
ec06b8edde
commit
7793e76890
1 changed files with 34 additions and 13 deletions
|
@ -1,6 +1,11 @@
|
|||
physics = {}
|
||||
|
||||
local players = {}
|
||||
local default_overrides = {
|
||||
speed = 1,
|
||||
jump = 1,
|
||||
gravity = 1
|
||||
}
|
||||
|
||||
minetest.register_on_joinplayer(function(player)
|
||||
players[player:get_player_name()] = {}
|
||||
|
@ -13,11 +18,7 @@ end)
|
|||
local function update(name)
|
||||
assert(players[name])
|
||||
local player = minetest.get_player_by_name(name)
|
||||
local override = {
|
||||
speed = 1,
|
||||
jump = 1,
|
||||
gravity = 1
|
||||
}
|
||||
local override = table.copy(default_overrides)
|
||||
|
||||
for _, layer in pairs(players[name]) do
|
||||
for attr, val in pairs(layer) do
|
||||
|
@ -28,20 +29,40 @@ local function update(name)
|
|||
player:set_physics_override(override)
|
||||
end
|
||||
|
||||
function physics.set(pname, name, modifiers)
|
||||
if not players[pname] then
|
||||
function physics.set(name, layer, modifiers)
|
||||
-- Basic sanity checks
|
||||
assert(
|
||||
type(name) == "string" and type(layer) == "string" and type(modifiers) == "table",
|
||||
"physics.set: Invalid function arguments!"
|
||||
)
|
||||
|
||||
if not players[name] then
|
||||
return
|
||||
end
|
||||
|
||||
players[pname][name] = modifiers
|
||||
update(pname)
|
||||
for attr, val in pairs(modifiers) do
|
||||
-- Throw error if an unsupported attribute is encountered
|
||||
assert(default_overrides[attr], "physics: Unsupported attribute!")
|
||||
|
||||
-- Remove an attribute if its value is 1
|
||||
if val == 1 then
|
||||
modifiers[attr] = nil
|
||||
end
|
||||
end
|
||||
|
||||
function physics.remove(pname, name)
|
||||
if not players[pname] then
|
||||
players[name][layer] = modifiers
|
||||
update(name)
|
||||
end
|
||||
|
||||
function physics.remove(name, layer)
|
||||
-- Basic sanity checks
|
||||
assert(type(name) == "string" and type(layer) == "string",
|
||||
"physics.remove: Invalid function arguments!")
|
||||
|
||||
if not players[name] then
|
||||
return
|
||||
end
|
||||
|
||||
players[pname][name] = nil
|
||||
update(pname)
|
||||
players[name][layer] = nil
|
||||
update(name)
|
||||
end
|
||||
|
|
Loading…
Reference in a new issue