The way I've done it is using a RigidBody2D, I have a script on the RigidBody2D.
In the Inspector tab for the RigidBody2D set CollisionObject2D -> Input -> Pickable
as true.
Then make a connection for the signal input_event
on the RigidBody2D
If you made the connection through the Scene tab in the editor it should make a function in the script with something like this:
func _on_RigidBody2D_input_event( viewport, event, shape_idx ):
pass
With this you'll be able to get input events only when they are clicked on the RigidBody2D.
What I do is have a var that checks if the object is being held or not.
var is_held = false
func _on_RigidBody2D_input_event( viewport, event, shape_idx ):
if event.type == InputEvent.MOUSE_BUTTON and event.pressed and event.button_index == BUTTON_LEFT:
is_held = true
And to release the RigidBody2D we will need to use the normal input event.
var is_held = false
func _ready():
set_process_input(true)
func _input(event):
if event.type == InputEvent.MOUSE_BUTTON and not event.pressed and event.button_index == BUTTON_LEFT:
is_held = false
func _on_RigidBody2D_input_event( viewport, event, shape_idx ):
if event.type == InputEvent.MOUSE_BUTTON and event.pressed and event.button_index == BUTTON_LEFT:
is_held = true
Now to make the object actually move. Since it's a RigidBody2D we can use the _integrate_forces()
function.
var is_held = false
func _ready():
set_process_input(true)
func _integrate_forces(state):
var lv = state.get_linear_velocity()
if is_held:
lv = (get_viewport().get_mouse_pos() - get_pos()) * 16
state.set_linear_velocity(lv)
func _input(event):
if event.type == InputEvent.MOUSE_BUTTON and not event.pressed and event.button_index == BUTTON_LEFT:
is_held = false
func _on_RigidBody2D_input_event( viewport, event, shape_idx ):
if event.type == InputEvent.MOUSE_BUTTON and event.pressed and event.button_index == BUTTON_LEFT:
is_held = true
And that should do it. The Object will be picked up when you click and hold on to it. And it will follow your mouse around until you let go.
You can see an example usage of this in a game I made for a jam, here: Pet Rock