Rotation of RayCast2D

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

How can I make the raycast’s rotation_degrees be equal the player’s direction?
Like when the player goes in diagonal direction and then the raycast points in the same direction.

enter image description here

DarlesLSF | 2020-07-21 16:42

:bust_in_silhouette: Reply From: deaton64

Make the Raycast a child of the sprite


something like:
$RayCast2D.global_rotation = $Sprite.global_rotation

I tried both methods and no one works :confused:

DarlesLSF | 2020-07-21 12:35

OK, can you upload your project somewhere?

deaton64 | 2020-07-21 13:47

enter image description here

Its like this on the tree and nothing happens if I put the raycast as a children of the sprite.

Here’s the script of the player:

extends KinematicBody2D

onready var anim : AnimationPlayer = $Sprite/anims
var frame = 0
export (int) var speed = 70
var pode_andar = true
var movendo
var mover : Vector2

func input():
	mover.x = Input.get_action_strength("direita") - Input.get_action_strength("esquerda")
	mover.y = Input.get_action_strength("baixo") - Input.get_action_strength("cima")

	if abs(mover.x) == 1 and abs(mover.y) == 1:
		mover = mover.normalized()
	movendo = speed * mover

	# sprites da movimentação
	if mover.x == 1:"direita")
		frame = 4
	if mover.x == -1:"esquerda")
		frame = 10
	if mover.y > 0:"baixo")
		frame = 7
	if mover.y < 0:"cima")
		frame = 1
	if mover.x == 0 and mover.y == 0:
		$Sprite.frame = frame

func _physics_process(delta):
	if pode_andar:

func raycast():
	$RayCast2D.global_rotation = mover.angle()

With the “func raycast”, the arrow points where I want, but when I stop move, the arrow returns to the initial point.

DarlesLSF | 2020-07-21 16:17

I had to subtract 90 degrees to get it to point the correct way in my test.
Is this what you wanted?
You’ll have to log the last direction and set that to the correct angle when the player doesn’t move.

 func raycast():
    $RayCast2D.global_rotation_degrees = rad2deg(mover.angle()) - 90

deaton64 | 2020-07-21 20:42

enter image description here

When I walk, the arrow points correctly, but when I stop, still the same: the arrow points to the initial point

DarlesLSF | 2020-07-21 23:41

Yes, I did mention that.

A quick fix:

Set mover to zero before changing the values:

func input():
	mover = Vector2.ZERO

Only change the raycast angle if you’ve moved:

func raycast():
	if mover != Vector2.ZERO:
		$RayCast2D.global_rotation_degrees = rad2deg(mover.angle()) - 90

deaton64 | 2020-07-22 07:49

Thx dude, the second option works for me :smiley:

DarlesLSF | 2020-07-22 12:14