How to create a grappling hook? (2D)

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

Hello, can someone please help me with creating a grappling hook for a kinematic body 2d player? I don’t need the the grappling hook to swing, just stick to a surface and slowly carry the player over to its position.

I am somewhat new to Gdscript and godot in general, so i would really appreciate the help.
Thanks.

:bust_in_silhouette: Reply From: Socrates

You will want to use a Raycast2D to figure out where the grappling hook collides with something. Use:

Raycast2D.cast_to(Vector2(some_x_position, some_y_position)

and then check if the raycast is colliding

if Raycast2D.is_colliding():
<draw grappling hook along the vector that was cast to ending at Raycast2D.get_collision_point>

After that you can normalize the vector with

Vector2.normalized()

This basically allows you to use the vector as a direction and multiply it by the character’s speed to move the character along that direction. So you will end up with something like:

character.position += speed * normalized_direction_vector * delta

in the _process() or _physics_process() function (depending on which you’re using). This will be called every frame till the character arrives at (or near more likely) the collision point of the original raycast) and then you can stop calling it. There is also probably a way to do that last bit with a Tween, which might give you better control over accelration/deceleration, but I don’t have much experience using them.

There are also a few tutorials on youtube about raycasts that might explain them better, such as: https://www.youtube.com/watch?v=lNADi7kTDJ4&t=350s

Socrates | 2018-07-17 23:30

Thanks for the help!

TheBaldChick | 2018-07-18 13:43

While this is a really great answer, it doesn’t explain how to make the visuals of the grapple gun. It would be great if it explained how to make a rope extend out of the gun, and then be reeled in.

Millard | 2019-10-24 13:20