Mouse movement tracking (SOLVED)

#1

Hello, I faced a problem regarding on_input function.
In my Project i have external crosshair object (it’s movement linked with mouse movement but it isn’t mouse).
My go Player handles player movement and this object movement.

function update(self, dt)
--MOUSE
	if self.past_one==true then
		self.ch_pos = go.get_position('crosshair')
		self.ch_pos = self.ch_pos + self.mouse_change * dt * 50
		go.set_position(self.ch_pos, "crosshair")
	else
		self.past_one=true
	end
	self.mouse_change.x=0
	self.mouse_change.y=0
	print("ch_pos.x: " .. go.get_world_position('crosshair').x)
	print("ch_pos.y: " .. go.get_world_position('crosshair').y)
end


function on_input(self, action_id, action)
	--MOUSE
	self.mouse_change.x=action.x-self.mouse.x
	self.mouse_change.y=action.y-self.mouse.y
	self.mouse.x=action.x
	self.mouse.y=action.y

	print("mouse_change.x: " .. self.mouse_change.x)
	print("mouse_change.y: " .. self.mouse_change.y)

	
	--PLAYER
	if action.pressed then
		if action_id == hash("up") then
			self.up = 1
		elseif action_id == hash("down") then
			self.down = 1
		elseif action_id == hash("left") then
			self.left = 1
		elseif action_id == hash("right") then
			self.right = 1
		end
	elseif action.released then
		if action_id == hash("up") then
			self.up = 0
		elseif action_id == hash("down") then
			self.down = 0
		elseif action_id == hash("left") then
			self.left = 0
		elseif action_id == hash("right") then
			self.right = 0
		end
	end

	
	
end

So, problem is in that when I am using keyboard it doesn’t track mouse movement, is there any solution for this?

0 Likes

#2
  • When the mouse moves, you get an on_input call with an action_id of nil.
  • Other inputs also include the mouse position fields in the action table (for whatever reason).

You’re setting self.mouse_change for every single input, not just mouse movement. When you are holding down an button and moving the mouse, you will get two on_input calls that frame. It just so happens that the mouse movement comes first, and self.mouse_change gets set correctly. But after that, you get the keyboard input, and you set self.mouse_change again, but you have the same exact coordinates, so it gets set to (0, 0).

To fix it, change the first part of your on_input to this:

if not action_id then
	self.mouse_change.x=action.x-self.mouse.x
	self.mouse_change.y=action.y-self.mouse.y
	self.mouse.x=action.x
	self.mouse.y=action.y

	print("mouse_change.x: " .. self.mouse_change.x)
	print("mouse_change.y: " .. self.mouse_change.y)
end

That way you only calculate self.mouse_change when the mouse actually moves.


By the way, there are also action.dx and action.dy fields, so you don’t need to subtract the current and last positions yourself.

4 Likes

#3

Thanks for the advice, didn’t know about two on_input calls.

1 Like

#4

Yeah, the function gets called once for every input, so it can happen many times each frame.

1 Like