Check collision of RayCast2D after rotation

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

Hi everyone

I’m quite new to Godot so apologies if this is a silly question, but I wasn’t able to find a solution online.
I’m trying to rotate a RayCast2D and once it’s rotated, check if it collides with something. The player can rotate the character and attack using the same key, e.g. pressing “W” will result in the character looking up and attacking up as well. The issue I’m facing at the moment is that it seems like the collision is checked before the rotation happens. I’m using the following two lines of code to do this:

attackRay.rotation_degrees = rad2deg(atan2(facingDir.y, facingDir.x))
print(attackRay.is_colliding())

where attackRay is the RayCast2D and facingDir is the direction the character should be turning to, determined by the user input. If there is an object above the player and I press “W”, the raycast is rotated perfectly fine but the console prints “False”. If I press it again, it prints “True”. If I then press e.g. “S” the raycast points downwards but the console output is “True” again, although there is no object to collide with. Pressing “S” again outpus “False”.
The point is, apparently checking for the collision happens prior to the rotation even though in the script rotating the raycast is done before.
I’ve been trying to fix this for quite some time now but can’t seem to get it to work. Any input would be highly appreciated.

Just call force_raycast_update() on the raycast.

Guliver_Jham | 2020-08-25 19:34

Thank you very much!

Zudav | 2020-08-26 06:39

:bust_in_silhouette: Reply From: Guliver_Jham

Don’t worry, we all have silly questions (tought i do not ask them, don’t be like me).
Anyway, here, what you have to do is update the raycast by calling force_raycast_update()on it.

:bust_in_silhouette: Reply From: klaas

Hi,
i think you have to force an update

#adjust rotation etc. here
raycaster.force_raycast_update()
if raycaster.is_colliding():
    #do something
    pass