Godot Version
Godot 4.2
Question
How do I make an Area2D move in a random direction? I want to make an Asteroids clone, but I’m having difficulties figuring that out for my asteroid scene.
Godot 4.2
How do I make an Area2D move in a random direction? I want to make an Asteroids clone, but I’m having difficulties figuring that out for my asteroid scene.
give it a random direction and then apply constant speed:
var speed: float = 100
func _ready():
rotation = randi_range(-180, 180)
func _physics_process(delta: float):
global_position += speed * delta
That returns an invalid operands error
I tried this approach
var SPEED = 200;
var ranx;
var rany;
func _ready():
randomize()
rotation_degrees = randi_range(0, 360)
ranx = randf_range(-1, 1)
rany = randf_range(-1, 1)
func _physics_process(delta):
# Move asteroid in random direction
position += Vector2(ranx, rany) * SPEED * delta;
but it doesn’t work exactly how I want. The speed isn’t always consistent
oh yeah it has to be a vector2:
var speed: Vector2 = Vector2.RIGHT * 100
func _ready():
rotation = randi_range(-180, 180)
func _physics_process(delta: float):
global_position += speed * delta
Your code should be consistent for each asteroid scene. Different asteroids will have different speeds though. If you want them all to have the same speed you can normalize the direction vector:
var SPEED = 200;
var ranx;
var rany;
var random_direction: Vector2
func _ready():
randomize()
rotation_degrees = randi_range(0, 360)
ranx = randf_range(-1, 1)
rany = randf_range(-1, 1)
random_direction = Vector2(ranx, rany).normalized()
func _physics_process(delta):
# Move asteroid in random direction
position += random_direction * SPEED * delta;
Ok gotcha. And just to make sure I’m understanding things correctly, normalizing a Vector means you’re making the direction length the same no matter where the direction is pointing, right?
Yes. It basically extends or reduces its length to exactly 1 while keeping the direction
This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.