How would I make a shotgun scatter bullets in Godot?

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

Hey guys, I’m trying to make a 2D shooter and want to implement a simple shotgun. Unluckily I have found no one online that has posted how they have done it.

I already have my shotgun sprite as a child of my player and I have it point towards my mouse.

How do I make my bullet sprite come out of the shotgun in a spread? Do I use raycasts to do this? I have a sprite for the bullet already. I’m very new to coding and Godot so I apologize if this is a dumb question.

Thanks in advance!

:bust_in_silhouette: Reply From: njamster

Do I use raycasts to do this?

Raycasts are used to check for collisions in a straight (and potentially very long) line. They can figure out the target of an instant-hit-weapon, but won’t help here.

All you need to to do is spawn multiple instances of your bullet-scene in the same location, change their rotation and then let them all travel in a straight line.

  1. Create a bullet-scene, for simplicity I’ll simply assume a Sprite:
extends Sprite

var direction = Vector2(1, 0)
var speed = 400 # pixels / s

func _ready():
    set_as_toplevel(true)

func _physics_process(delta):
    global_position += direction * speed * delta
  1. Create a player scene. For simplicity I’ll again assume a Sprite. Once the player hits the right key, we need to call a shoot-method to spawn the bullets:
extends Sprite

const BULLET_SCENE = preload("res://Bullet.tscn")

var aim_direction = Vector2.RIGHT

func _input(event):
	if event is InputEventKey and event.pressed:
        if event.scancode == KEY_SPACE:
            shoot()
  1. Also we need to ake the aim direction controllable with the mouse:
func _process(delta):
	aim_direction = global_position.direction_to(get_global_mouse_position())
  1. Now we’ve everything we need to implement the shoot-method itself:
func shoot():    	
	for angle in [-45, -22.5, 0, 22.5, 45]:
		var radians = deg2rad(angle)
		var bullet = BULLET_SCENE.instance()
		bullet.direction = aim_direction.rotated(radians)
	bullet.global_position = self.global_position
		add_child(bullet)