Truncate(a , b) in GDScript

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

I followed an explanation about steering behavior and came across this line:

velocity = truncate (velocity + steering , max_speed)

Does somebody knows what truncate does here and how I can reproduce this in Godot, because the explanation is written in AS3 and Flash.



Thats the link to the explanation about steering behavior:

:bust_in_silhouette: Reply From: PEIGNAULT Laurent


Seem that truncate is used because velocity + steering must be lower than max-speed.
You can do a while loop < max_speed for example.

Have a nice day.

:bust_in_silhouette: Reply From: exuin

I assume this is the code you’re asking about:

// If (velocity + steering) equals zero, then there is no movement
velocity = truncate(velocity + steering, max_speed)
position = position + velocity
function truncate(vector:Vector3D, max:Number) :void {
    var i :Number;
    i = max / vector.length;
    i = i < 1.0 ? i : 1.0;

First, the truncate function creates a variable i with type Number. Then, it assigns to i the maximum speed divided by the length of the velocity plus steering vectors. The next line is a ternary operator, but I don’t think those exist in GDScript. If i is less than 1.0, then assign that to i. Else, assign 1.0 to i. Then the vector is scaled by i.

So to replicate this in GDScript I would do something like:

func truncate(vector, max):
    var i = max / vector.length()
    i = min(i, 1.0)
    return vector * i

I’m not 100% sure but I think that Vector3s are passed as values and not references so you’ll have to return the vector instead of void like the AS3 function does.

1 Like