extends Spatial
var e1_hotlist = []
var e2_hotlist = []
var teleport = []
export var door: NodePath

func _ready():
	var e = $e1.connect("body_entered", self, "e1_enter")
	assert(e == OK)
	e = $e1.connect("body_exited", self, "e1_exit")
	assert(e == OK)
	e = $e2.connect("body_entered", self, "e2_enter")
	assert(e == OK)
	e = $e2.connect("body_exited", self, "e2_exit")
	assert(e == OK)

func e1_enter(body):
	if !body.is_in_group("characters"):
		return
	if body in e1_hotlist:
		return
	var pv1 = body.global_transform.basis[2]
	var pv2 = -($e2.global_transform.origin - $e1.global_transform.origin).normalized()
	if (pv1 - pv2).length() > 0.8:
		return
	if door:
		var door_obj = get_node(door)
		if door_obj.rotation.y <= 0.0:
			door_obj.rotation.y = PI / 2.0
	e2_hotlist.push_back(body)
	teleport.push_back([body, $e2.global_transform.origin])
func e1_exit(body):
	if body in e1_hotlist:
		e1_hotlist.erase(body)
func e2_enter(body):
	if !body.is_in_group("characters"):
		return
	if body in e2_hotlist:
		return
	var pv1 = body.global_transform.basis[2]
	var pv2 = -($e1.global_transform.origin - $e2.global_transform.origin).normalized()
	if (pv1 - pv2).length() > 0.8:
		return
	e1_hotlist.push_back(body)
	if door:
		var door_obj = get_node(door)
		if door_obj.rotation.y <= 0.0:
			door_obj.rotation.y = PI / 2.0
	teleport.push_back([body, $e1.global_transform.origin])
func e2_exit(body):
	if body in e2_hotlist:
		e2_hotlist.erase(body)
func _physics_process(_delta):
	while teleport.size() > 0:
		var item = teleport.pop_front()
		item[0].global_transform.origin = item[1]
