Change Animation key value per instance

Godot 4.0.2

How can I change animation key values to a different value per instance?

I am trying to spawn in several (potentially a random amount) of bones for killing a squirrel. I have created a very simple animation where the reward “flys” into the air and lands in some random direction. Think of Sonic running into a spike and losing some coins.

Unfortunately, Godot doesnt seem to support resource_local_to_scene for animations, so I am unable to get my three bones to land in different spots.

My code for instancing the bones and playing the animation is as follows:

func _sq_bit(sq_position):
	var bone_scene = load("res://Bone.tscn")
	for n in range(0, 3, 1):
		randomize()
		var bone_instance = bone_scene.instantiate()
		call_deferred("add_child", bone_instance)
		bone_instance.position = Vector2(sq_position)
		
		var a = bone_instance.get_node("CollisionShape2D/Sprite2D/AnimationPlayer").get_animation("sq_death")
		var rng = RandomNumberGenerator.new()
		var x = rng.randf_range(-1, 1)
		var y = rng.randf_range(-1, 1)
		a.track_set_key_value(2, 1, Vector2(x, y).normalized()*20)
		bone_instance.get_node("CollisionShape2D/Sprite2D/AnimationPlayer").play("sq_death")

sq_position is simply where the origin of the bones should be.

The issue is that everytime this for loop runs, the animation key value is changed. But, this is the “mother” key value, so all three bones’ animation gets updated and they all do the same thing, rather than going in random direction.

Perhaps Tweens would be better in this case, but I am in fact a total noob.

SOLUTION:
Tweens was in fact my needed solution. I kept my animation “sq_death” as this gave the “bone” the illusion of “flying into the air” (scaling up/down), but used tween for the actual x,y traversal:

        var tween = create_tween()
		tween.tween_property(bone_instance, "position", sq_position + target_position, 1.0)
		bone_instance.get_node("CollisionShape2D/Sprite2D/AnimationPlayer").play("sq_death")

Tween is an option, but in your case, maybe you can work around the limitation and create a “local” animation that is always the same, but change the bone rotation (and scale maybe ?) when you instantiate it ?

1 Like

I thought about this! Several similar issues online came to this suggestion. To me, it felt messy to create/duplicate animations for this specific instance, then delete them when it “dies.”

I managed to get things work how I wanted with Tweens!

Thanks!

        var tween = create_tween()
		tween.tween_property(bone_instance, "position", sq_position + target_position, 1.0)
		bone_instance.get_node("CollisionShape2D/Sprite2D/AnimationPlayer").play("sq_death")