LookAt() misbehaving?

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

ray.LookAt(player.GlobalPosition);
ray.CastTo = player.GlobalPosition;

where ray is a RayCast2D and player is a KinematicBody2D

And this is the result:
https://streamable.com/ams5l

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].

Anyone know what’s going on? :slight_smile:
Thanks in advance

:bust_in_silhouette: Reply From: njamster

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:

r.cast_to.x = global_position.distance_to(player.global_position)

I knew I was misunderstanding some of this theory…
Thank you for enlightening me!

Christoffer Schindel | 2020-02-13 14:43