func _process(_delta):
if Input.is_action_just_pressed("ui_right"):
spawn_bullet(Vector2.RIGHT)
elif Input.is_action_just_pressed("ui_left"):
spawn_bullet(Vector2.LEFT)
elif Input.is_action_just_pressed("ui_up"):
spawn_bullet(Vector2.UP)
elif Input.is_action_just_pressed("ui_down"):
spawn_bullet(Vector2.DOWN)
How to mke this code with match
- Edited
You could use a match by doing something like this, but I don't know if it's an improvement:
var action: int = int(Input.is_action_just_pressed("ui_right")) + 2 * int(Input.is_action_just_pressed("ui_left")) + 4 * int(Input.is_action_just_pressed("ui_up")) + 8 * int(Input.is_action_just_pressed("ui_down"))
match action:
0: pass
1: spawn_bullet(Vector2.RIGHT)
2: spawn_bullet(Vector2.LEFT)
4: spawn_bullet(Vector2.UP)
8: spawn_bullet(Vector2.DOWN)
(other values, if desired, for combinations of inputs)
The int() calls convert the bools into ints that are 0 or 1. The factors are powers of 2 (2, 4, 8) to avoid ambiguous results.
- Edited
Here's another way to do it.
func _input(event):
if event.is_pressed():
var v = Input.get_vector('ui_left', 'ui_right', 'ui_up', 'ui_down')
match v:
Vector2(1, 0):
print('right')
Vector2(-1, 0):
print('left')
Vector2(0, -1):
print('up')
Vector2(0, 1):
print('down')
It has the advantage that you could just use the vector "v" as the argument to spawn_bullet.
func _input(event):
if event.is_pressed():
var v = Input.get_vector('ui_left', 'ui_right', 'ui_up', 'ui_down')
spawn_bullet(v)
However, if two buttons are pressed at the same time, you'll get a vector like "(0.7, 0.7)", so you'll have to check that only one coordinate is set [ (1, 0), etc ] in your spawn_bullet() function. Or just use:
func _input(event):
if event.is_pressed():
var v = Input.get_vector('ui_left', 'ui_right', 'ui_up', 'ui_down')
if v and v == v.floor():
spawn_bullet(v)
Edit: Checking for "v and ..." ensures that unrelated mouse-clicks won't fire a bullet.
7 months later
Megalomaniak added the Godot Help tag .