Sync Projectile with animation (2d Game)

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By whoisda

Hi,

I’m trying to create a simple bullet shoot. While the bullet is shooting, I don’t know how to sync it with the right frame of the animation. Right now it shoots just a user presses a key but the animation follows up 3 frames later.

How do I get the bullet to shoot at the right time?

It might help if you provide your code and an image or video. I don’t see why your animation would be delayed if you start it in the same frame the user pushes the shoot-button.

njamster | 2020-03-23 17:15

I wanted to delay the projectile until a certain frame in the animation and sync the bullet with that.

I have found a workaround, it’s a bit hackish and I might get stuck somewhere in the future but this is what I’m doing for now:

if Input.is_action_just_pressed("Attack"):
	animationPlayer.play("Attack")

func _on_Sprite_frame_changed():
if $Sprite.frame == 35:
	shootBullet()

func shootBullet():
	var bullet= Bullet.instance()
	bullet.set_bullet_direction(sign($Bullet2D.position.x))
	get_parent().add_child(bullet)
	bullet.position = $Position2D.global_position

So basically, I call the animation to play and then look for a change in the animation. When the frame reaches the frame I want, it shoots the bullet.

I love to find a better way if there is one.

whoisda | 2020-03-23 17:47

Your solution looks fine to me. :slight_smile: If you want to avoid checking every frame, you can connect to the animation_finished-signal instead. If your animation does not end after frame 35, just split it into two parts! After the first part (containing only the first 35 frames) is finished, shoot the bullet and start playing the second part.

njamster | 2020-03-23 17:54

This also seems like a better solution. For now, I’ll be using the Call Method Track but I’ll keep this solution in mind as well.

Thanks a lot!

whoisda | 2020-03-24 05:48

:bust_in_silhouette: Reply From: jgodfrey

As another possibility, you can add a Call Method Track to your animation. Using that, you can call a method at a specific frame in your animation. Just use the Add Track | Call Method Track item in the AnimationPlayer. Using that, you could simply call your shootBullet() method at frame 35 of the animation.

Wow!! This works perfectly!

Thanks a lot!

whoisda | 2020-03-24 05:43