Can I use the same Vector2 struct across multiple librarys that implement their own Vector2 structs?

Viewed 84

I'm making a 2D game that will use one library for rendering graphics to the screen, and another for physics. The problem is that both libraries implement their own Vector2 struct. This means I have to convert between the two very often and it can be confusing which Vector2 I'm referring to because they are both called "Vector2". Ideally, I would like to use the same Vector2 class across both libraries. How can I achieve this with C#?

2 Answers

You can write your own MyVector2 struct that supports implicit conversion to the other Vector2 types.

struct MyVector2
{
    public float x;
    public float y;

    public static implicit operator GraphicsLib.Vector2(MyVector2 v)
    { return new GraphicsLib.Vector2(v.x,v.y); }

    public static implicit operator PhysicsLib.Vector2(MyVector2 v)
    { return new PhysicsLib.Vector2(v.x,v.y); }

    ...
}

Then instances of MyVector2 should be compatible with any function expecting a Vector2 from either library.

MyVector2 v = new MyVector2(5f, 20f);
GraphicsLib.DoSomethingWithVector(v);
PhysicsLib.DoSomethingWithVector(v);

The other answer that mentions using System.Runtime.CompilerServices.Unsafe.As<MyVector2, PhysicsLib.Vector2>(ref v); might also be possible to use inside the conversion operators if optimization is crucial.

If they have the same internal layout, you can use System.Runtime.CompilerServices.Unsafe to convert between them. You can also create extension methods that for each kind. E.g. public static Lib1.Vector2 ToLib1(this Lib2.Vector2 v) = > System.Runtime.CompilerServices.Unsafe.As<Lib2.Vector2, Lib1.Vector2>(ref v); Personally, I use MonoGame but use System.Numerics.Vector2 everywhere I can for SIMD support (it might be an unnecessary micro-optimization but I sleep better knowing that I use SIMD instructions when I can).

Related