Problems with raycast! Please help!

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Anastasia
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!

:bust_in_silhouette: Reply From: imjp94

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")

Thank you so much!

Anastasia | 2020-03-30 15:41