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#?
Can I use the same Vector2 struct across multiple librarys that implement their own Vector2 structs?
-
@stuartd I'm not entirely sure I understand what you mean. If I implement my own Vector2 struct in a shared library, I wouldn't be able to pass an instance of it into a function in the physics library because the physics library function is expecting the parameter type to be of its implementation of Vector2, not the one in the shared library. – C. Lang Sep 15 '20 at 18:01
-
1@stuartd I'm pretty sure OP means they are using third party libraries for graphics and physics; They probably won't be able to modify those libraries to reference a common library & vector type. – Romen Sep 16 '20 at 16:57
-
@Romen I guess so, I didn't think of 3rd party libraries. – stuartd Sep 16 '20 at 17:51
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.

- 1,617
- 10
- 26
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).

- 345
- 1
- 7