Hello, i try to move my camera just inside my city sprite’s border. Player’s device dimensions can change but should stay inside city borders each time.
My camera is orthograpic fixed and my code is below.
i tested my code both on mobile phone(1080x2340) and on desktop(1920x1080). it works but i tried so many things to make it work and i am not sure if this code works for most of devices? Is there any problem you see it can be code or logic flow. I also added a window listener if desktop user changes window size. My priority is that the camera works flawlessly on most screen types, meaning there are no black dead zones in the corners of the map. If I’ve missed anything, I’m open to suggestions.
Note: The camera sometimes jumps a little while panning. I’m working on that issue.
-- Default for mobile 720 x 1280
local half_view_width = 360
local half_view_height = 640
-- Camera border limits because my background image is whole world and dimensions 3840 x 2160 px
local MIN_X, MIN_Y = -1920, -1080
local MAX_X, MAX_Y = 1920, 1080
local is_locked = false
--Callback
local function window_callback(self, event, data)
if event == window.WINDOW_EVENT_RESIZED then
print("Window resized: ", data.width, data.height)
half_view_width = data.width / 2
half_view_height = data.height / 2
end
end
function init(self)
--if window resize i listen event
window.set_listener(window_callback)
--To adjust camera width and height i read device dimensions
local width, height = window.get_size()
half_view_width = width /2
half_view_height = height / 2
--Getting camera position
self.pos = go.get_position()
--Variables for camera movement
self.dragging = false
self.last_x = 0
self.last_y = 0
end
function on_input(self, action_id, action)
if is_locked then
-- Nevermind this section
self.dragging = false
return
end
if action.pressed then
-- Nevermind this section
self.dragging = true
self.last_x = action.x
self.last_y = action.y
return
end
if action.released then
self.dragging = false
return
end
if self.dragging then
local dx = action.x - self.last_x
local dy = action.y - self.last_y
self.last_x = action.x
self.last_y = action.y
local new_x = self.pos.x - dx
local new_y = self.pos.y - dy
self.pos.x = new_x
self.pos.y = new_y
-- Checking if camera is in allowed zone.
if self.pos.x - half_view_width < MIN_X then self.pos.x = MIN_X + half_view_width end
if self.pos.x + half_view_width> MAX_X then self.pos.x = MAX_X - half_view_width end
if self.pos.y - half_view_height < MIN_Y then self.pos.y = MIN_Y + half_view_height end
if self.pos.y + half_view_height > MAX_Y then self.pos.y = MAX_Y - half_view_height end
go.set_position(self.pos)
end
end
function on_message(self, message_id, message, sender)
if message_id == hash("lock_camera") then
is_locked = message.command
if is_locked then
-- Nevermind this section
self.dragging = false
self.last_x = 0
self.last_y = 0
end
end
end
