0 votes
func _input(event):
    if event.is_action_pressed("ui_accept"):
        var target = $RayCast2D.get_collider()
        print(target.name)
        if target != null:
            if target.name.find("Dragon") > 0:
                print("test")
                if food > 0:
                    food = food - 1
                    emit_signal("player_stats_change", self)
                    emit_signal("dragon_feed")

I have a static body named dragon: the raycast does detect it since print(target.name)always turns out to be Dragon: but the other one, print("test") doesn't print anything: so the whole thing under it doesn't work!
please help!

in Projects by (63 points)

1 Answer

+2 votes
Best answer

Actually there's no problem with your code, but you have misunderstood the returned value of String.find(), which will return -1(if not found) or > -1(the starting position of substring).
In your case, it will always return 0 instead of number bigger than 0(since "Dragon" start at position 0), that's why target.name.find("Dragon") > 0 is always false

Here's how I would code, not necessary, but more readable:

func _input(event):
    if event.is_action_pressed("ui_accept"):
        var target = $RayCast2D.get_collider()
        print(target.name)
        if target: # If target not null
            if target.name == "Dragon": # If target's name is "Dragon"
                print("test")
                if food > 0:
                    food = food - 1
                    emit_signal("player_stats_change", self)
                    emit_signal("dragon_feed")
by (142 points)
selected by

Thank you so much!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.

Categories