problem with dragging KinematicBody2D

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

Hello everybody,

I’m working on a interface with draggable apples, where I’m meant to be able to click on something, at the moment a button node, and get an apple kinematic body that I can drag and drop somewhere, and if “dropped” moves down simulating gravity with move_and_collide.

My problem is that the button spawned apple has a translated drag-anchor point compared to the in-scene positioned apple that I places mayself as testing double. Both attach to mouse pointer by clicking inside the collision shape, but the ones spawned by the button attach far to the left top, kind of like 0,0 coordinates of something.

here is the script for the apple node (istanced)

extends KinematicBody2D

var mouse_in = false
var dragging = false

func _ready():
mouse_in = true

func _process(delta):
if (mouse_in && Input.is_action_pressed("left_click")):
	dragging = true
if (dragging && Input.is_action_pressed("left_click")):
	var position = get_viewport().get_mouse_position()
	dragging = false

func _physics_process(delta):
    move_and_collide(Vector2(0, 1))

func _on_Apple_mouse_entered():
 mouse_in = true

func _on_Apple_mouse_exited():
mouse_in = false

and here is the button code

extends Button

var spawntimer = OS.get_system_time_secs()
var isdown = false

func _on_AppleButton_button_down():
if (OS.get_system_time_secs() - 2 > spawntimer):
	spawntimer = OS.get_system_time_secs()
	var scene = load("res://Apple.tscn")
	var scene_instance = scene.instance()

there is a timed throttle for the spawning event with OS time.

I don’t understand why the Apple I placed myself behaves like I need it to, and the other does not.

Thanks for any help.

:bust_in_silhouette: Reply From: variablescake

Found the solution myself:


instead of just add_child(scene_instance) in the button script, the Apple center is fixed for the spawned one. Apparently the node was being added as child of the button and getting weird positions from get_viewport().get_mouse_position()

Careful with adding to the root, it is the root viewport, not the current scene, which may give you problems later.

You can do get_tree().current_scene.add_child() to add it to the current scene without guessing the current scene path.

eons | 2018-09-04 09:59