Better way to instance shotgun pellets.

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

I have a very long script for my shotgun shoot func because i want it to fire multiple bullets in one shot so currently this is how it looks like

func shoot():
play("Shoot")
$Shoot.play()
var bullet1 = BULLET.instance()
var bullet2 = BULLET.instance()
var bullet3 = BULLET.instance()
var bullet4 = BULLET.instance()
var bullet5 = BULLET.instance()
get_parent().get_parent().get_parent().call_deferred("add_child", bullet1)
get_parent().get_parent().get_parent().call_deferred("add_child", bullet2)
get_parent().get_parent().get_parent().call_deferred("add_child", bullet3)
get_parent().get_parent().get_parent().call_deferred("add_child", bullet4)
get_parent().get_parent().get_parent().call_deferred("add_child", bullet5)
bullet1.set_position($Position2D.get_global_position())
bullet1.damage = DAMAGE
bullet1.accuracy = ACCURACY
bullet2.set_position($Position2D.get_global_position())
bullet2.damage = DAMAGE
bullet2.accuracy = ACCURACY
bullet3.set_position($Position2D.get_global_position())
bullet3.damage = DAMAGE
bullet3.accuracy = ACCURACY
bullet4.set_position($Position2D.get_global_position())
bullet4.damage = DAMAGE
bullet4.accuracy = ACCURACY
bullet5.set_position($Position2D.get_global_position())
bullet5.damage = DAMAGE
bullet5.accuracy = ACCURACY
recovering = true
AMMO -= 1

its not that pretty, is there a simplified way to spawn in multiple bullets with a shorter script?

:bust_in_silhouette: Reply From: jgodfrey

Yeah, that can be cleaned up a lot. Any time you find yourself repeating the same code over and over, there’s likely a better way… Really, you just need to do each step once and wrap it in a loop to create any number of bullets…

Note, the below code was created (by modifying your code) directly in this post and is untested, so it may not be perfect, but you should get the idea.

func shoot():
   var numBullets = 5
   play("Shoot")
   $Shoot.play()
   var parent = get_parent().get_parent().get_parent()
   for i in range(numBullets):
      var bullet = BULLET.instance()
      parent.call_deferred("add_child", bullet)
      bullet.set_position($Position2D.get_global_position())
      bullet.damage = DAMAGE
      bullet.accuracy = ACCURACY
   recovering = true
   AMMO -= 1

Also, that get_parent().get_parent().get_parent() call is pretty ugly. There’s likely a better way to get that reference, but without additional details, I just went with it.

Thanks for the help it works great and yeah the get_parent thing is a bit long
my nodes look like this
World
-Player
–Position2d
—Gun

im making the gun call the player parent i tried using get_owner but it returns null so i just did the long way.

Newby | 2020-02-09 05:04