Game Object Follow Mouse Cursor at Certain Speed

In this case you need two things:

  1. A target/destination position for your game object to move towards
  2. Update the target/destination position with the mouse position each time the mouse moves

It would look something like this:

function init(self)
	-- get focus
	msg.post(".", "acquire_input_focus")

	-- speed in pixels/second
	self.speed = 200
	
	-- the target position to move towards
	self.target_position = go.get_position()
end

function update(self, dt)
	local current_position = go.get_position()
	-- get a vector pointing from the current position to the target position
	local diff = self.target_position - current_position
	local distance_to_target = vmath.length(diff)
	if distance_to_target > 0 then
	    local direction = vmath.normalize(diff)
        -- don't overshoot the target by moving too far in a frame
        local distance_to_move = math.min(distance_to_target, self.speed * dt)
        -- update with the new position
        local new_position = current_position + direction * distance_to_move
        go.set_position(new_position)
    end
end

function on_input(self, action_id, action)
	if action.x and action.y then
		-- update target position with mouse coordinates
		self.target_position = vmath.vector3(action.x, action.y, 0)
	end
end
2 Likes