This code works fine, and it's doing basically the same thing as your first clip, which makes me think that the problem is somewhere else in your project. You might try using global_position as well as to_local().
extends Node2D
var ys
func _ready() -> void:
ys = YSort.new()
ys.position = Vector2.ONE * 200
add_child(ys)
func _input(event: InputEvent) -> void:
if event.is_pressed() and event is InputEventMouseButton:
print(event.global_position)
var sp = Sprite.new()
sp.texture = preload('res://icon.png')
sp.position = ys.to_local(event.global_position)
ys.add_child(sp)
By the way, if you put "~~~" around your code, it will format better.