Reputation: 23
I am trying to make a fishing mechanic for practice and run into this problem where i created a function that takes input but i am not sure how to call it. I cant seem to find it anywhere and was wondering if it is possible or i should be writing the code a different way.
var letters: Array[String] = ["Q", "W", "E", "R"]
var cletter: String
var fish = 100
var code
#adds and removes health from the fish then resets hook
func reel(event:InputEventKey) :
if (fish > 0 && fish < 101):
if (event.keycode == code):
fish = fish-10
text = "YAY " + str(fish)
await get_tree().create_timer(2).timeout
hook()
else:
text = "NO " + str(fish)
fish = fish + 10
await get_tree().create_timer(2).timeout
hook()
else:
text = "fish dead"
#picks a random letter and shows it on screen
func hook():
cletter = letters.pick_random()
text = cletter
code = OS.find_keycode_from_string(cletter)
#I want to call the reel func here
not sure this is the proper way to code this or if there is a better way, but this is what i came up with. Its supposed to work as hook gets called by a button i have and shows a letter a player needs to press then it calls reel to check if the player pressed the correct letter or not then repeats this until the fish doesnt have any health left.
Upvotes: 0
Views: 280
Reputation: 1729
There is already a function which receives all input events. It's called _input, So what you could do is something like this:
var hooking = false
#adds and removes health from the fish then resets hook
func _input(event):
if event is InputEventKey and event.is_pressed():
if hooking:
hooking = false
if (fish > 0 && fish < 101):
if (event.keycode == code):
fish = fish-10
text = "YAY " + str(fish)
await get_tree().create_timer(2).timeout
hook()
else:
text = "NO " + str(fish)
fish = fish + 10
await get_tree().create_timer(2).timeout
hook()
else:
text = "fish dead"
func hook():
cletter = letters.pick_random()
text = cletter
code = OS.find_keycode_from_string(cletter)
hooking = true
So as I said _input gets called if any input event at all is happening, so we need a flag so that the function only does something, if the fish is hooked. Therefore I added the variable hooked. Because the _input function executes on EVERY input I am making sure the code get only executed, if the input is an EventKey and the key is pressed.
So how it works now: you press the button,get your letter and set the variable hooked to true. Now if the user enters any key input the function checks if it is your key and does you logic. Not handling any new input until hook is called again.
Upvotes: 3