Topic was automatically imported from the old Question2Answer platform.
Asked By
Christoffer Schindel
Hi,
I want to cast a 2D ray from an enemy directly to the player to check if it is the first collision. I have done so semi-successfully, however I can’t for the life of me figure out how to properly cast in the right direction. Right now, this is what is working best, but definitely not ideal:
In some directions (usually casting upwards), it works kind of alright [0:03]. In other directions (usually downwards) it’s missing the player by a considerable amount of degrees [0:10].
cast_to is describing the direction the ray is going in, defaulting to Vector2(0, 50), i.e. downwards. look_at will rotate a node by taking in a global position, transforming it into a Vector2 in local coordinates and then using its angle to determine the amount of rotation necessary. Thereby a Vector2 pointing to the right has an angle of 0°, one pointing upwards has an angle of -90° and so on. So if your players global_position is to the right of the rays origin, look_at will rotate it by 0°. Meaning: the ray is still pointing downwards. However, there’s an easy fix: simply set cast_to to Vector2(50, 0), i.e. to the right. Of course you can use a different length than 50. If you want the length to be dynamic, you could add this line to your script: