Game Object Follow Mouse Cursor at Certain Speed

Hi, I’m new to Defold.

I see in the docs how to get a game object to follow the mouse cursor.

How would I set mouse movement up where the game object follows the mouse cursor at a certain speed?

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

	-- speed in pixels/second
	self.speed = 200
	
end

function on_input(self, action_id, action)
	if action.x and action.y then
		-- let game object follow mouse/touch movement
		local pos = vmath.vector3(action.x, action.y, 0)
		go.set_position(pos)
	end
end

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

Thanks @britzl , worked brilliant! This example will help me a lot to get a grasp of how Defold and mouse movement works.

One small typo… had to change:

to:

local new_position = current_position + direction * distance_to_move

Ah, thanks. Updated the example.

1 Like