I am trying to use Haxe to write scripts for game engines like Unity or Godot.
In both cases I am unable to write a line like
Translate(dir * 100.0);
where dir is a Vector2 imported from the .net dll of Godot resp. Unity.
The working alternatives I found so far would be
Translate(Vector2.op_Multiply(dir, 100.0));
which on first sight seems like a bug in the hxcs module, but after some research it seems like a limitation of Haxe's type system.
The other alternative would be to use an abstract type to overload the operator resulting in code like this:
Translate(new Vector2WithOps(dir) * 100.0);
So my question is: is there a way to get around the explicit cast to the abstract type?
Intuitively it seems like Haxe should be able to apply the operators automatically when importing from C#, and it should be able to infer the type needed for the multiplication and perform the cast to the abstract type implicitly. I understand that there are technical reasons why both is at least difficult, but I am still hoping that there's a way I haven't seen yet.
So my question is: is there a way to get around the explicit cast to the abstract type?
Yes, abstracts allow defining implicit casts. You can simply add from Vector2 to Vector2
to the declaration:
abstract Vector2WithOps(Vector2) from Vector2 to Vector2 {}
That doesn't magically make something like dir * 100.0
work, however - you still need a way to trigger the cast of dir
to a Vector2WithOps
, for instance by assigning it to a variable typed that:
var dirWithOps:Vector2WithOps = dir;
There's also a special syntax called type check to trigger the cast:
(dir : Vector2WithOps)
Ultimately, the most convenient option would be to make sure that you're already working with a Vector2WithOps
to begin with. That would work as long as you're creating new instances in your own code, but works less well when one is returned from a native API. This reminds me of a Haxe issue that considered allowing operator overloading through static extensions, which would be quite useful here: #2803