That’s a nice-looking hero!
Why would you duplicate the player and not the weapon? If you’re not familiar with the concept of inheritance in programming, this is a good time to look it up/learn. There may be a tutorial specific to Godot, but if not, do this long tutorial, it does go over it at some point: https://www.youtube.com/watch?v=nAh_Kx5Zh5Q&t=1s
- Do not add CollisionShape2D to Sword in your Player scene. The collision shape should be part of Sword scene. If you want Player class to handle the event of sword hitting something, just have weapon emit a signal, such as:
signal hit(obj)
where “obj” is the object the weapon hit, and Player then just connects to that signal.
- You need to remember reference to currently-equipped weapon. So at the top of Player class, have this:
var weapon: Node2D # if your weapons all inherit from Weapon class or smth (as they should), you can put Weapon instead of Node2D.
Back to your situation - let’s say you have 2 weapon scenes, Sword.tscn and, dunno, Mace.tscn.
For the sake of simplicity let’s say you store paths to weapon scenes in Player class, also declared at the top:
var weapons: Dictionary = { "sword" : preload("res://scenes/weapons/sword.tscn"),
"mace": preload(res://scenes/weapons/mace.tscn") }
(Really, though, you definitely should be keeping paths to weapon scenes in a resource file, but that’s a separate issue for later.)
Then in w/e place / event where you pick up the new weapon, just do:
func equip_weapon(wp_key: String):
var new_weapon = weapons[wp_key].instantiate()
# unequip current weapon
if weapon:
weapon.queue_free()
# equip new weapon
add_child(new_weapon)
new_weapon.hit.connect(_on_weapon_hit)
weapon = new_weapon # set weapon variable to hold reference to just-equipped weapon
func _on_weapon_hit(obj):
# your code here to process weapon hitting some object "obj"
# for example:
if obj.is_in_group("enemy"):
var dmg = #your code to calculate damage
obj.take_damage(dmg)
# this is just an example... multiple ways to solve this,
# such as enemy actually detecting a weapon hitting it
# and then asking the weapon for dmg it should take.
# The weapon can then tell it or ask some singleton to
# calculate dmg (If things weapon isn't aware of
# need to be taken into account). Anyway, this is
# outside the scope of this thread.
Then remove Sword from the scene tree in editor and just equip it programmatically on load in Player.gd:
func _ready():
equip_weapon("sword")