Godot Slowing down Area2d objects

Viewed 42

I'm making a prototype for my 2d top-down space game and I'm using area2d for my *ship object since most of its mechanics rely only in collisions. Is there a way i can slow down then stop my ship after it is launched, because as for now it just fly continuously. Here is my basic code:


var jump_speed = 500
var velocity = Vector2()

func get_input(delta):
    if Input.is_action_pressed("click"):
        look_at(get_global_mouse_position())
    if Input.is_action_just_released("click"):
        velocity = transform.x * jump_speed
        
func _physics_process(delta):
    get_input(delta)
    position -= velocity * delta```
1 Answers

In general the idea is to reduce the length of the velocity vector over time. We could define a deceleration for that (this is not the only way to go about it):

var deceleration := 10.0

And then in _physics_process we can compute by how much the velocity would be reduced:

var speed_reduction := deceleration * delta

Compare it with the magnitud of velocity, if it is more, just set the velocity to Vector2.ZERO otherwise we want to scale velocity appropriately:

var current_speed := velocity.length()
if current_speed > speed_reduction:
    velocity = Vector2.ZERO
else:
    velocity = velocity * (current_speed - speed_reduction) / current_speed

By the way, from Godot 3.5 onward there is a limit_length method in Vector2 and Vector3 that can make this simpler to implement.

Related