0 votes

I'm using Godot 4 beta 4.
I have a RayCast2D. I want it to be facing the direction the player is looking at, and I thought that I could do it by changing the value of its rotation property depending on the player's direction.
I made a dictionary to associate each direction my player can face to an angle.

const DIRECTION_TO_ROTATION : Dictionary = {
    Vector2.DOWN : 0,
    Vector2.DOWN + Vector2.RIGHT : -45,
    Vector2.RIGHT : -90,
    Vector2.RIGHT + Vector2.UP : -135,
    Vector2.UP : 180,
    Vector2.UP + Vector2.LEFT : 135,
    Vector2.LEFT : 90,
    Vector2.LEFT + Vector2.DOWN : 45,
}

In my physics_process function, I made two variables:

var direction : Vector2 = Input.get_vector("move_left", "move_right", "move_up", "move_down").normalized()
var direction_key : Vector2 = direction.round()

Then, I add an "if" statement:

if direction_key in DIRECTION_TO_ROTATION:
    $RayCast2D.rotation = DIRECTION_TO_ROTATION[direction_key]

When I run my scene, the RayCast is pointing at the right direction when I face down, down/left, and down/right, but not in every other direction. Does someone know what I did wrong?

By the way, I added a print($RayCast2D.rotation) at the end of my "if". When I go up for exemple, the output correctly prints 180, but my raycast appears to be facing at around 135 degrees and collides with things as if it was facing at 135 degrees. Manually putting the raycast orientation at 180 degrees via the editor while the game is running makes it face the right direction in-game.

Godot version Godot 4 beta 4
in Engine by (15 points)

1 Answer

+1 vote
Best answer

The rotation property expects values in radians, not degrees. Does this fix your issue?

$RayCast2D.rotation = deg2rad(DIRECTION_TO_ROTATION[direction_key])
by (19,272 points)
selected by

Yes. It's now the deg_to_rad function in Godot 4, but it solved my problem, thanks.

deg_to_rad? Really? I looked that up in the Godot 4 docs to be sure before posting. Maybe the docs haven't been updated for this yet. Anyway, glad that took care of it.

Yes the docs have not been updated yet but its in the source code

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 Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.