Hi everyone,

I'm new here and new to Godot. I've done a couple of basic tutorials. The last being Heartbeast's ARPG Youtube series. I am wanting to add things to this demo to start becoming more familiar with programming and the engine.

What I want to do is have a Sword (an Areas2D scene with sprite and collision2D) on the map and have my player run into it and then pick up the item. I've been able to run into it and trigger an output that proves this, but want the item when triggered to follow the player. I know my script pushes the Sword towards 0,0 when I touch it, but is there not an easy way to tell it to push it towards the player's coordinates?

Here is the script:

extends Area2D

onready var sword_pos = $SwordImage

func _on_Sword_body_entered(body):
	print("sword touched")
	var speed = 5 # Change this to increase it to more units/second
	
	position = position.move_toward(Vector2(0,0), speed)

Thanks in advance!

Chris

  • Yes, you can get the player node by the node path. For example (this may not work, depending on where your player is in the tree).

    var player = get_node(".../Player")
    position = position.move_toward(player.position, speed)

    See here:
    https://kidscancode.org/godot_recipes/basics/getting_nodes/

So there are two ways to do this. You can use remove_child() to take the sword out of its current parent and then use add_child() to add it to the player. Then it will just follow the player at a fixed position since it is a child. The other option would be to have a separate sprite drawing/animation that already has a sword. When you touch the sword item it simply disappears (either by calleding queue_free() or simply setting visible = false and then you switch the player sprite to the one with the sword. The second option is what is done in most games, though the first one would be a good choice if you are just learning.

    cybereality Thank you for that suggestion. I remember experimenting with child nodes following the player one time. I'll do more research and figure out how to do that. The game design I'm following (its a an old Atari 2600 game) had the items like the Sword be persistent that were carried around with you with no change to the sprites.

    But is there an easy way to reference the players coordinates in a child node?

    Yes, you can get the player node by the node path. For example (this may not work, depending on where your player is in the tree).

    var player = get_node(".../Player")
    position = position.move_toward(player.position, speed)

    See here:
    https://kidscancode.org/godot_recipes/basics/getting_nodes/

      cybereality Thank you for your help. Your answers and links gave me the info I needed to learn enough to get to the next problem. :-)