Skip to content

Instantly share code, notes, and snippets.

@mrosati84
Created June 11, 2024 07:14
Show Gist options
  • Save mrosati84/70f05c493f868de235cd73f8f13df73f to your computer and use it in GitHub Desktop.
Save mrosati84/70f05c493f868de235cd73f8f13df73f to your computer and use it in GitHub Desktop.
-- controls if a player is controllable with input.
-- other multiplayer clients are not controllable.
go.property("controllable", true)
-- ------------------------------------------------------------
-- needed only by the authority. The client moves via messages.
-- ------------------------------------------------------------
--#IF HEADLESS
local moving_x = 0
local moving_y = 0
--#ENDIF
function init(self)
if self.controllable then
msg.post(".", "acquire_input_focus")
end
end
function update(self, dt)
-- -------------------------------------------------
-- physics movement only performed by game server!!!
-- -------------------------------------------------
--#IF HEADLESS
local lv = go.get("#collisionobject", "linear_velocity")
local new_lv = lv + vmath.vector3(moving_x, moving_y, 0) * dt * 100
go.set("#collisionobject", "linear_velocity", new_lv)
--#ENDIF
end
function fixed_update(self, dt)
--#IF HEADLESS
local lv = go.get("#collisionobject", "linear_velocity")
local pos = go.get_position()
msg.post("/network#network", "linear_velocity", {
linear_velocity = {
x = lv.x,
y = lv.y
},
position = {
x = pos.x,
y = pos.y
},
moving_x = moving_x,
moving_y = moving_y,
goid = go.get_id()
})
--#ENDIF
end
function on_message(self, message_id, message, sender)
-- ------------------------------
-- MOVEMENT HANDLING VIA MESSAGES
-- ------------------------------
--#IF HEADLESS
if message_id == hash("moving") then
local x = message.moving_x
local y = message.moving_y
moving_x = x
moving_y = y
end
--#ELSE
if message_id == hash("linear_velocity") then
go.set("#collisionobject", "linear_velocity", vmath.vector3(message.linear_velocity.x, message.linear_velocity.y, 0))
end
--#ENDIF
end
function on_input(self, action_id, action)
-- ------------------
-- KEY PRESS HANDLING
-- ------------------
if action_id == hash("left") then
if action.pressed then
msg.post("/network#network", "pressed_left")
elseif action.released then
msg.post("/network#network", "released_left")
end
end
if action_id == hash("right") then
if action.pressed then
msg.post("/network#network", "pressed_right")
elseif action.released then
msg.post("/network#network", "released_right")
end
end
if action_id == hash("up") then
if action.pressed then
msg.post("/network#network", "pressed_up")
elseif action.released then
msg.post("/network#network", "released_up")
end
end
if action_id == hash("down") then
if action.pressed then
msg.post("/network#network", "pressed_down")
elseif action.released then
msg.post("/network#network", "released_down")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment