
This is a follow up of my recently published Grab the game object with the mouse or screen touch tutorial, where I explained how to rotate a Player or an Object with the mouse during the gameplay.
Here I won't be showing the Scene setup, the Scene tree and some other details I already went trough in the PART I. I will only explain the coding needed for the mouse pointer to be able to drag an Object and move it to a different position. If you need a detailed step by step process from the very beginning I recommend you read the first tutorial.
The idea is simple: you hover the cursor over something, click and while the mouse button's clicked that game object has to follow the mouse cursor if you move it. Once you release the button - the object stays and the cursor moves as usual. It looks like this:

So, my Player has a child Button Node. I made it transparent with the Theme Override (Control cagetory) in the Inspector panel. The Button sends two signals: button_down and button_up connected to the Scene's script.
The first one makes active variable true and the second - false. Here I do the same as in the previous tutorial - trigger a variable which gets checked under the _process() function.
When I click on my Player the Button sends button_down signal which triggers a function and makes active = true. Obviously, to be dragged the Player's position has to change relatively to the cursor's position, but taking into account the initial difference the moment that click just happened. Every time the difference vector will vary because I can click anywhere within the Button rectangle.

Here is my script in Godot:
var active = false
var dif = Vector2(0, 0)
func _ready():
pass
func _process(_delta):
var mouse_position = get_viewport().get_mouse_position()
if active:
$Player.global_position = mouse_position + dif
func _on_Button_button_down():
dif = $Player.get_global_position() - get_viewport().get_mouse_position()
active = true
func _on_Button_button_up():
active = falseThe most important 2 lines here is the one which calculates the distance and the angle between the clicked position and the Object's position:
dif = $Player.get_global_position() - get_viewport().get_mouse_position()And the one that assigns new coordinates to the Player's position under the _process() function:
$Player.global_position = mouse_position + difThat's it. This is one of the ways it can be done.
Actually, being able to move things with the mouse or by tapping the touchscreen is the necessary part of many projects and games. I hope you guys learned something from this post. Follow me on Instagram for more tips and learning materials.