0 votes

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

$raycast2D.enabled = true

But that didn't work

asked Mar 29 in Engine by mynamesdat (19 points)

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!

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

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?

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.

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

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

Please log in or register to answer this question.

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.