In this lesson, we head back to LightningBeam.gd
to instantiate lightning jolts.
We need the script to update the effect’s target point and create as many jolts we desire. To that end, we define several variables:
extends RayCast2D # Dictates how many jolt instances are created when the weapon fires. export (int, 1, 10) var flashes := 3 # Time interval between flashes in seconds. export (float, 0.0, 3.0) var flash_time := 0.1 # Lightning jolt scene. Here, we use preload to have it load at compile time. export var lightning_jolt: PackedScene = preload("res://LightningBeam/LightningJolt.tscn") # End point of the jolt. var target_point := Vector2.ZERO
We update the target point every physics frame. If we collide with a static body, we set the target point to the collision point. Otherwise, the target point is the cast_to
position we defined when setting up the scene. Keep in mind that our weapon may rotate, so we use to_global()
to take this into account.
func _physics_process(delta) -> void: target_point = to_global(cast_to) if is_colliding(): target_point = get_collision_point()
When called, the shoot()
function creates multiple instances of the lightning_jolt
scene based on the number of flashes
. We create a timer and yield()
to wait for it to finish before continuing with the loop.
func shoot() -> void: # `in flashes` is a shorthand for `in range(flashes)` for flash in flashes: var jolt = lightning_jolt.instance() add_child(jolt) jolt.create(global_position, target_point) # Pause the function for `flash_time` seconds. yield(get_tree().create_timer(flash_time), "timeout")
Now, if you rerun the PlayerShip scene and press space, you should see lightning!
We now have a basic lightning effect you can use in your projects. In the next lesson, we’ll add a chain lightning effect to bounce between multiple static objects.
extends RayCast2D export (int, 1, 10) var flashes := 3 export (float, 0.0, 3.0) var flash_time := 0.1 export var lightning_jolt: PackedScene = preload("res://LightningBeam/LightningJolt.tscn") var target_point := Vector2.ZERO func _physics_process(delta) -> void: target_point = to_global(cast_to) if is_colliding(): target_point = get_collision_point() func shoot() -> void: for flash in flashes: var jolt = lightning_jolt.instance() add_child(jolt) jolt.create(global_position, target_point) yield(get_tree().create_timer(flash_time), "timeout")