dragging an object with fixed distant and direction

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By wakry

I am totally new to game developing and I am just trying to learn. I am sorry if I lack some terms, but I will try to explain what I want.

I was trying to figure out how to pick up an object and move it along with the mouse (drag and drop logic)

I found a code online that helped me with this, but it sets the position of the object (KinematicBody2D) to “get_viewport().get_mouse_position()” to make it move along with the mouse. I want to maintain the distance and the direction between the object and the mouse. For example, If I pressed and hold on the left corner of the object and dragged up the object will move in a parallel line.

object move relatively with the mouse

My code looks like this:

func _process(delta):
if (mouse_in && Input.is_action_pressed("left_mouse_click")):
	dragging = true
if (dragging && Input.is_action_pressed("left_mouse_click")):

	var newPosition = Vector2()
	if(position.x < get_viewport().get_mouse_position().x):
		newPosition.x = get_viewport().get_mouse_position().x - x
	else:
		newPosition.x = get_viewport().get_mouse_position().x + x
	if(position.y < get_viewport().get_mouse_position().y):
		newPosition.y = get_viewport().get_mouse_position().y - x
	else:
		newPosition.y = get_viewport().get_mouse_position().y + x
	position = newPosition
	set_position(position)

else:
	dragging = false

-X is suppose to be the fixed distance between the initial mouse click and the object position. I didn’t know how to obtain that so I use an int 16.

-mouse_in is set to true in mouse entered event and false in mouse existed.

This code seems to be doing what I want but if I move the mouse slowly and if I go fast the position of the object start changing to the right or left of the mouse position.

I would appreciate the help

Thank you

:bust_in_silhouette: Reply From: wakry

I fixed this issue with the following code. However, I am not very sure why this worked (mathematically) I just had one of this moment of (oh it worked!). Please if you can explain it I would appreciate it
Code:

func _input(event):
if event is InputEventMouseButton:
	if event.is_pressed() && mouse_entered:
		print("clicked")
		draggingDistance = position.distance_to(get_viewport().get_mouse_position())
		dir = (get_viewport().get_mouse_position() - position).normalized()
		click_on = true
		dragging = true
	else:
		print("unclicked")
		dragging = false
		click_on = false
elif event is InputEventMouseMotion:
	if dragging && click_on:
		position = get_viewport().get_mouse_p

Events:

func _on_Player_mouse_entered():
mouse_entered = true
pass # replace with function body

func _on_Player_mouse_exited():
mouse_entered = false
pass # replace with function body

No need for the bool “click_on”. I think I just left it there by mistake.

wakry | 2019-03-09 20:58