Issues with pinch to zoom

I’m trying to make it so that pinching changes the z coordinate of the camera, making it zoom in and out. Right now, I can pinch to zoom out but I’m not sure how to make it so that I can zoom back in. I know I have it getting the absolute value so the only thing I can do is zoom out right now, but is there a way to determine whether the difference in finger position is increasing or decreasing so that I can use that?

Also, is there a way to make it less choppy? Because right now it doesn’t really zoom as I’m pinching but it instead jolts out.

I know that moving the z coordinate isn’t the usual way to zoom but it’s what works for me.

function on_input(self, action_id, action)

	if action_id == hash("zoom") then
		-- Handle touch points when pressed
		--if action.pressed == true then
			self.touch_positions = {} -- Reset the touch positions table
			for i, touchdata in ipairs(action.touch) do
				local pos = vmath.vector3(touchdata.x, touchdata.y, 0)
				self.touch_positions[i] = pos
			end
			
			print(action.pressed)
			
			print("jeff")
			local pos1_pressed = self.touch_positions[1]
			local pos2_pressed = self.touch_positions[2]
			print("pos1 pressed: " .. pos1_pressed)
			print("pos2 pressed: " .. pos2_pressed)
			local pos_difference = math.abs(pos1_pressed.x - pos2_pressed.x)

			local pos = go.get_position()

			print("Pos z: " .. pos.z)
				
			if pos.z >= 1000 and pos.z <= 4500 then
				pos.z = pos.z + pos_difference
				go.set_position(pos)
				if pos.z > 4500 then
					pos.z = 4500
				elseif pos.z < 1000 then
					pos.z = 1000
				end
			end
-- rest of code

I would do a pinch implementation by recording the two positions of the fingers when they touch the screen and I would calculate the distance between them. You can calculate the distance by calling vmath.length(v1 - v2). I would also store the current zoom at this point in time (your z-value)

For any on_input() updates I would then calculate the new distance of the two touch points.

Next I’d get the ratio between the current distance and the original distance (ie current/original). If the value is larger than 1.0 it would be an “inverse pinch” (ie the fingers are further apart) and if it is less than 1.0 it is a pinch (the fingers are closer).

To zoom in/out I’d calculate the new zoom as:

local factor = 1 -- tweak this for faster/slower zoom
local current_zoom = original_zoom + ratio * factor

I have a Gesture library that can be used for this if you don’t want to implement it yourself:

2 Likes