• 2D
  • Getting the absolute position of object following a Path2D

Hello fellow programmers. This is my first post ever on these forums, I didn't know they existed :)

In my game, enemies (called 'mob' in my code) drop a coin when they die (original). I use the enemy's position (mob.position) to set the coin's position:

func _on_Mob_died(mob):
	var coin = make_coin(coin_type.MINI, mob.position)
	self.add_child(coin)

It works great, the coin appearing where the enemy was. I also sometimes use a Path2D and PathFollow2D's points to arrange enemies in a "V" formation (called 'squadron' in my code), and that's where the problem happens; When the enemies in the squadron die, the coins drop at global position (0,0) instead of where the enemy is displayed. I printed the enemies position in the console and indeed, when on the PAth2D the position stays (0,0)

Here is the code for the squadron setup :

func add_mob(mob):
	var point : PathFollow2D = PathFollow2D.new()
	point.rotate = false
	point.loop = false
	# 'path' is the Path2D 
	path.add_child(point)
	point.h_offset = 0
	point.v_offset = 0
	point.add_child(mob)
	mob.face_down()
	_distribute_mobs()

func _distribute_mobs():
	var count = path.get_child_count()
	for i in range(count):
		var c = path.get_child(i)
		c.unit_offset = (i+1)*1.0/(count+1.0)

Is there a way to have the 'position' attribute 'mob' object to reflect its real position (displayed) on screen ? What is the best way to get the object's position ?

Thanks !

Welcome to the forums @cozytom!

You can get the exact position of a Node2D node relative to the origin of the scene using the global_position attribute. If you set the global_position of the coin to the global_position of the mob, then it should be at the right position regardless of whether the mob is on a Path2D or not.

Hello @TwistedTwigleg ! Your solution works like a charm, thank you for telling me about global_position... There are a lot of places where I should really use it instead of position, as most of the time, what I actually want is the position in the scene. Thanks a lot! Maybe one day my little game is good enough that I'll show it off :D