So let's say we have a bullet that have a wide and random spray pattern in a 2D space. When we shot it flies until one second is passed, then returns to start position. Here is the code for this
var velocity = Vector2()
var shot
func _physics_process(delta):
if Input. is_action_pressed("ui_right") and not shot:
velocity.x = 1000
velocity.y = rand_range(-250,250)
shot = true
$Timer.start()
velocity = move_and_slide(velocity)
func _on_Timer_timeout():
shot = false
position = Vector2(500, 250)
velocity = Vector2(0,0)
Here is the problem: when bullet flies to a random point it needs to face this point.
I want it to change directions according to the place it moves to so I need help. How can I do this?
You can use velocity.angle()
(see Vector2::angle()) to get the direction of the movement, then set the rotation of your sprite (Node2D) to this value.
Note that your way of getting a random direction for the bullet has the side effect that the speed is larger when the bullet moves sideways. You could use Vector2::rotate(angle) instead to avoid this.
var angle = randf_range(-PI/4,PI/4)
velocity = Vector2(1000,0).rotate(angle)
When done this way, you already have an angle to use for the sprite rotation.