I have a player scene that shoot bullets every 2 seconds. I want to apply rotation to each bullet as in the image.
Here is the code in Player. I used some from a tutorial by KidsCanCode on Youtube:
var shoot_direction = Vector2.UP
var bullet_num = 3
func shoot(pbullet_num):
var main = get_tree().current_scene
var dir = shoot_direction.rotated(shoot_position.global_rotation)
var spread = 0.2
if pbullet_num > 1:
for i in range(pbullet_num):
var bullet = bullet_scene.instance()
var a = -spread + i * (2 * spread)/ (pbullet_num-1)
bullet.initialize(shoot_position.global_position,
shoot_speed, dir.rotated(a))
main.add_child(bullet)
else:
var bullet = bullet_scene.instance()
bullet.initialize(shoot_position.global_position,
shoot_speed, dir)
main.add_child(bullet)
Here is the Bullet scene:
var speed = 0
var velocity = Vector2.ZERO
var direction = Vector2.UP
func initialize (start_position, pspeed, pdirection):
position = start_position
speed = pspeed
velocity = pdirection * speed
func _process(delta):
position += velocity * delta
You can change the rotation
of any Node2D
to rotate it. This is the angle in radians. The best place to set the it is in the initialize
function of the Bullet scene, where you're also setting the other attributes:
rotation = pdirection.angle() + PI / 2
The angle()
method of Vector2
computes the angle in radians clockwise from the X axis (pointing right) to the given vector. Since your sprites are pointing "up" when they are not rotated, instead of right, we need to add a quarter turn, which is PI / 2
in radians.