#Smooth changes of direction with 2D moves

1 messages · Page 1 of 1 (latest)

gleaming drift
#

Here is a part of my code for player movement :

func _physics_process(delta):
    var direction = Input.get_vector("left", "right", "up", "down")

    var hook_pressed = Input.is_action_pressed("hook")
    var is_hook_linked = line2D.get_point_count() > 1

    if hook_pressed and is_cube_in_range:
        if global_position.distance_to(cube_position) < DISTANCE_THRESHOLD:
            return
        if is_hook_linked:
            line2D.set_point_position(1, cube_position - self.position)
            velocity = Steering.follow(
                velocity,
                global_position,
                cube_position,
                max_speed,
                MASS
            )


        else:
            line2D.add_point(cube_position - self.position)
            velocity = speed * direction
    else:
        if line2D.get_point_count() > 1:
            line2D.remove_point(1)
            
        velocity = speed * direction
    velocity /= GRAVITY
    move_and_slide()
#

And here is the follow function from GDQuest tutorial :

static func follow(
        velocity: Vector2,
        global_position: Vector2,
        target_position: Vector2,
        max_speed: = DEFAULT_MAX_SPEED,
        mass: = DEFAULT_MASS
    ) -> Vector2:
    """
    Calculates and returns a velocity steering towards target_position
    """
    var desired_velocity: Vector2 = (target_position - global_position).normalized() * max_speed
    var steering: Vector2 = (desired_velocity - velocity) / mass
    return velocity + steering