My camera doesn't work!

When pressing two button consecutively (up, down, left, right), the script seems to go either infinitely up or down. Also, my zoom button just doesn’t work however it is in line with the input bindings.

Here is the code:

function init(self)
	msg.post("#camera", "acquire_camera_focus")
	msg.post(".", "acquire_input_focus")

	self.ALLOWED = false -- Flag to allow camera movement
	self.camera_speed = 600 -- Camera movement speed
	self.zoom_speed = 1 -- Speed of zooming in and out
	self.camera_zoom = 1 -- Current zoom level

	-- Track the current movement direction
	self.keys_pressed = {
		up = 0,
		down = 0,
		left = 0,
		right = 0,
	}
end

function on_input(self, action_id, action)
	-- Update key states based on the current action value
	if self.ALLOWED then
		if action_id == hash("up") then
			self.keys_pressed.up = action.value or 0
		elseif action_id == hash("down") then
			self.keys_pressed.down = action.value or 0
		elseif action_id == hash("left") then
			self.keys_pressed.left = action.value or 0
		elseif action_id == hash("right") then
			self.keys_pressed.right = action.value or 0
		elseif action_id == hash("scroll_up") and action.pressed then
			-- Zoom in
			self.camera_zoom = self.camera_zoom + self.zoom_speed * 0.1
			self.camera_zoom = math.min(self.camera_zoom, 2) -- Clamp to max zoom level
		elseif action_id == hash("scroll_down") and action.pressed then
			-- Zoom out
			self.camera_zoom = self.camera_zoom - self.zoom_speed * 0.1
			self.camera_zoom = math.max(self.camera_zoom, 0.5) -- Clamp to min zoom level
		end
	end
end

function on_message(self, message_id, message)
	if message_id == hash("go") then
		if not self.ALLOWED then
			msg.post(".", "acquire_input_focus")
		end
		self.ALLOWED = true -- Enable camera movement
	end
end

function update(self, dt)
	if self.ALLOWED then
		-- Get current camera position
		local camera_pos = go.get_position("/camera")

		-- Calculate movement based on key states
		camera_pos.y = camera_pos.y + self.keys_pressed.up * self.camera_speed * dt
		camera_pos.y = camera_pos.y - self.keys_pressed.down * self.camera_speed * dt
		camera_pos.x = camera_pos.x - self.keys_pressed.left * self.camera_speed * dt
		camera_pos.x = camera_pos.x + self.keys_pressed.right * self.camera_speed * dt

		-- Set the updated camera position
		go.set_position(camera_pos, "/camera")

		-- Apply zoom level
		local zoom = vmath.vector3(self.camera_zoom, self.camera_zoom, 1)
		go.set_scale(zoom, "/camera")
	end
end

Thank you for any help.

try to reset self.keys_pressed each update

2 Likes