move the player to raycast2d Collision Point

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

move the player to raycast2d Collision Point

:bust_in_silhouette: Reply From: p7f

Whats your player node? KinematicBody2D?

Anyways, in most cases, something like this should be enough

$Player.global_position = $RayCast2D.get_collision_point( )

You should previously check if the raycast did collide with something .
For better answer, you should provide more information. What type of node is your player? is the raycast child of the player? Do you want to make the movement in the player’s script or anywhere else?

My player node is a KinematicBody2D, yes the raycast is son of the player and i want it in the player script thanks :smiley:

ManiCus | 2020-08-10 16:10

Ok, so in the player script, you need to do something like:

global_position = $RayCast2D.get_collision_point( )

You should previously check if the raycast collided with $RayCast2D.is_colliding()

p7f | 2020-08-10 16:44

that worked but i don’t want to teleport…

I’m trying to do this:

func _proces(delta):

func raycast(delta):
if Input is action pressed(“activate_raycast”):
global_position = $RayCast2D.get_collision_point( ) * delta

but its not going with the time its teleporting

ManiCus | 2020-08-10 18:55

Ah ok, yo dont want to move the body to the point instantly… that wasnt clear in the question. So there are many ways. You first need to define if you want to move it a constant speed, or move it in a specific time, etc… also, is it a top down game? what would be your case?
For example, for constant speed, you may do something like this:

func _process(delta):
    if Input.is_action_pressed("activate_raycast"):
        direction = global_position.direction_to($RayCast2D.get_collision_point())
        velocity = direction * speed
        velocity = move_and_slide(velocity)
   else: #only use this if you want to stop movement after releasing
        velocity = Vector2.ZERO

with speed a float and velocity a Vector2 global variables

p7f | 2020-08-10 19:12

would this be similar for 3d? I’ve been struggling to make it work

Jeejus | 2023-03-08 23:25