[Optimization] Cycle through array with frames in-between

Godot Version

Godot version 4.5

Question

Lets say I have six cannons in an array (cannon_positions) which are each identified by a Marker2D.
Every time I press the spacebar, the function shoot() is activated, and a bullet is spawned at one of the cannons.
This means there are a variable amount of frames between them.

Now I want to start with the first cannon, and every input after that I want the next cannon to shoot.
After the last one, the first one starts again.

This code here should work, but I am trying to optimize the code.
Especially the lines where I keep track of where in the array I am.

Could you optimize this code?

extends Node

@export var bullet : PackedScene
@export var cannon_positions : Array[ Marker2D ]

var cannon_active : int

func shoot() -> void:
	var b : Node2D = bullet.instantiate()
	b.global_position = cannon_positions[ cannon_active ].global_position
	add_sibling( b )
	
	cannon_active += 1
	if cannon_active > cannon_positions.size() - 1:
		cannon_active = 0

Nothing to optimize there. You can make it a bit more elegant by using wrapi()

Thank you!
Never heard of wrapi() before.
These are exactly the type of additions I was looking for.

New code:

extends Node2D

@export var bullet : PackedScene
@export var cannon_positions : Array[ Marker2D ]

var cannon_active : int

func shoot() -> void:
	var b : Node2D = bullet.instantiate()
	b.global_position = cannon_positions[ cannon_active ].global_position
	add_sibling( b )
	
	cannon_active = wrapi( cannon_active + 1, 0, cannon_positions.size() )
1 Like