Hey everyone just wanted to share a little tip to reduce code repetition in the Godot 3D (RPG) course.
First off, sorry if this post is a bit on the longer side, I just want to explain how this works for those newer to game dev / programming (Extension methods can be found near the end)
I am also doing this in C# rather than GDscript but would be happy to create a GDscript version if people are having trouble with translating it.
I’m not very far in yet but there have been a few instances where we need to use InterpolateWith and pass in the exponential function with decay. Rather than writing out the full exponential function every time we could make use of extension methods.
For those that are new to programming, an extension method allows you to add functionality to an already existing component / node, for example when you reference a transform you’ll see a dropdown with suggestions of what you can use (InterpolateWith being the example here). An extension method will show up just like that.
Here are the extension methods I’ve created to handle the exponential decay interpolate methods. These live in their own separate Utilities script
public static partial class Utilities
{
public static Transform3D Interpolate(this Node3D transform, Transform3D transformTarget, double delta, float decay)
{
return transform.GlobalTransform = transform.GlobalTransform.InterpolateWith(transformTarget, 1 - (float)Mathf.Exp(-delta * decay));
}
public static Transform3D Interpolate(this Transform3D transform, Transform3D transformTarget, double delta, float decay)
{
return transform = transform.InterpolateWith(transformTarget, 1 - (float)Mathf.Exp(-delta * decay));
}
}
As you might have noticed these are static methods and the first parameter uses the “this” keyword, it needs to be public static so it can be accessed anywhere and the “this” keyword tells the method to apply it to the thing we are referencing so you don’t actually have to pass that in.
Using this made my lines go from this
_RigPivot.GlobalTransform = _RigPivot.GlobalTransform.InterpolateWith(targetTransform, 1 - (float)Mathf.Exp(-delta * _AnimationDecay));
to
_RigPivot.GlobalTransform = _RigPivot.Interpolate(targetTransform, delta, _AnimationDecay);