Enable raycast 2D using code

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By mynamesdat

I want to enable and disable a raycast using code. I tried this:

$raycast2D.enabled = true

But that didn’t work

If your node is called “raycast2D” (node names are case-sensitive!) and is a direct child of the node your script is attached to: yes, it does work precisely that way!

njamster | 2020-03-29 14:15

Yes, it’s named like that and it’s case-sensitive, but it doesn’t work for some reason. Do you have any alternative ways of doing it?
Thanks

mynamesdat | 2020-03-29 14:46

No, there is no alternative way: This is the way to do it! As it works fine on my end it’s either a bug (that you should report) or you did something wrong. From the information you provided that’s impossible to tell though!

Can you provide an example project?

njamster | 2020-03-29 17:48

Yes, sure. So basically the raycast is for an enemy to check if there is a cliff in front of it. The enemy is knocked back into the air and because of that, the raycast doesn’t work properly, so I want to disable it.

func _process(delta: float) -> void:
#turning the enemy if the raycast to check the ground isn't colliding
if $raycast2D.is_colliding() == false:
    if facing == 1:
        _move_left()
    elif facing == -1:
        _move_right()

#when damaged
func _damage(amount):
    health = health - amount
    #changing the velocity to show that it is knocked back
    velocity.x = 75
    velocity.y = -30
    $raycast2D.enabled = false
   $knockback_timer.start() #staring the timer to set the raycast2D to be enabled again

func _on_knockback_timer_timeout() -> void:
    velocity.x = 0 #stop the knockback velocity
    $raycast2D.enabled = true

It it suppose to stop the raycast from checking for ground when the enemy is in the air, but when I run the game the raycast is still working when the enemy is knocked back.
p.s my wording maybe weird for certain parts because English is not my native language, thanks for your time.

mynamesdat | 2020-03-30 02:28

Have you tried calling force_raycast_update (documentation) after setting the enabled-property?

njamster | 2020-03-30 11:16

Oh, I didn’t know about that at all. Thanks a lot, it works as intended now :DD

mynamesdat | 2020-03-30 12:20