Help with making bullet spread with vector 2

Godot Version

4.2

Question

I want to add bullet spread to my shotgun in my top down game but most tutorials use rotations and what not to make the bullet spread but im using a raycast target position which uses vector 2 but I dont know how to translate that into rotation so i can get the bullet spread or where to start.

Heres the shotgun code:

@onready var raycast = $"../../RayCast2D"
@export var bulletCount : int = 1
@export_range(0,360) var Arc : float = 0

func Shoot():
	
	for i in bulletCount:	
		var bullet = bullet.instantiate()
		bullet.position = $"../../RayCast2D".global_position
		var arcRad = deg_to_rad(Arc)
		var incremement = arcRad / (bulletCount -1)
		raycast.rotation = (raycast.rotation + incremement * i - arcRad/2)
		bullet.direction = (raycast.target_position).normalized()
		get_parent().add_child(bullet)

Hi,

If I understand correctly, you’re looking for a way to convert a Vector2 to a rotation? In that case, the right vector corresponding to the default rotation in radians, you can use:

# If angle is in radians:
Vector2.RIGHT.rotated(angle)

# If angle is in degrees:
Vector2.RIGHT.rotated(deg_to_rad(angle))

which, in your code, would be:

bullet.direction = Vector2.RIGHT.rotated(raycast.rotation)

Let me know if that works.

1 Like

I am afraid this did not work

But I realized that I was going on about this in the wrong way, I was basically needing to change a vector 2 to an angle and change those angles back to a vector.

And I got it to work now

Thank you so much for your time though.

That’s what I understood, so I’m curious to see your final working code, if you may? :smile:
You could mark it as the solution for this post, too.

I think what you want here is Vector2.angle_to_point().

Sure thing!

@onready var raycast = $"../../RayCast2D"
@export var bulletCount : int = 1
@export_range(0,360) var Arc : float = 0
func Shoot():
	for i in bulletCount:	
		var bullet = bullet.instantiate()
		bullet.position = $"../../RayCast2D".global_position
		var arcRad = deg_to_rad(Arc)
		var incremement = arcRad / (bulletCount -1)
	
		var targetRotation = (raycast.target_position.angle() + incremement * i - arcRad/2)
		print(raycast.target_position.angle())
		var direction = Vector2(cos(targetRotation), sin(targetRotation))
		bullet.direction = direction
		get_parent().add_child(bullet)
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.