Bullet shooting math code

Godot Version

v4.4.1

Question

Not sure if this is the right forum for this, but I have a question about the easiest way to code shooting out bullets in an arc shape (like a shotgun) here’s a pic to show what I mean.


(green lines just for debug, and blue lines to help show what I’m aiming for)

I currently just shoot 1 red bullet towards the mouse position like this:

func shoot_bullet() -> void:
	var bullet: Test04Bullet = bullet_scene.instantiate()
	bullet.set_position(position)
	bullet_direction = -(position - get_global_mouse_position()).normalized()
	bullet.set_direction(bullet_direction)
	get_parent().add_child(bullet)
# Physics process function
func _physics_process(delta: float) -> void:
	position.x += direction.x * SPEED * delta
	position.y += direction.y * SPEED * delta

And have no idea how to achieve the effect I want based on that. I tried mucking around with the .dot() function, but didn’t really understand it or get anywhere with it.

Anyone got some pointers?

You already have a direction variable, all you need to do is rotate this direction by an angle, e.g. 15 degrees, 30 degrees, -15 degrees and -30 degrees.

var rotated_direction: Vector2 = direction.rotated(deg_to_rad(15))
2 Likes

Perfect, exactly what I was after, I knew it would be simple, thank you very much.

If this helps anyone else here is the exact code I changed:

func shoot_bullet() -> void:
	for i: int in range(-2, 3):
		var bullet: Test04Bullet = bullet_scene.instantiate()
		bullet.set_position(position)
		bullet_direction = -(position - get_global_mouse_position()).normalized()
		var rotated_direction: Vector2 = bullet_direction.rotated(deg_to_rad(i * 15))
		bullet.set_direction(rotated_direction)
		get_parent().add_child(bullet)
1 Like