diff --git a/include/typings/linalg.pyi b/include/typings/linalg.pyi index 75610203..0694e342 100644 --- a/include/typings/linalg.pyi +++ b/include/typings/linalg.pyi @@ -19,6 +19,16 @@ class vec2(_StructLike['vec2']): def rotate(self, radians: float) -> vec2: ... def rotate_(self, radians: float) -> None: ... + @staticmethod + def angle(__from: vec2, __to: vec2) -> float: + """Returns the angle in radians between vectors `from` and `to`. + + The result range is `[-pi, pi]`. + + + if y axis is top to bottom, positive value means clockwise + + if y axis is bottom to top, positive value means counter-clockwise + """ + class vec3(_StructLike['vec3']): x: float y: float diff --git a/src/linalg.cpp b/src/linalg.cpp index cceeafdd..068d4ffa 100644 --- a/src/linalg.cpp +++ b/src/linalg.cpp @@ -55,6 +55,16 @@ namespace pkpy{ return VAR(Tuple({ VAR(self.x), VAR(self.y) })); }); + vm->bind(type, "angle(__from: vec2, __to: vec2) -> float", [](VM* vm, ArgsView args){ + PyVec2 __from = CAST(PyVec2, args[0]); + PyVec2 __to = CAST(PyVec2, args[1]); + float val = atan2f(__to.y, __to.x) - atan2f(__from.y, __from.x); + const float PI = 3.1415926535897932384f; + if(val > PI) val -= 2*PI; + if(val < -PI) val += 2*PI; + return VAR(val); + }); + vm->bind__repr__(PK_OBJ_GET(Type, type), [](VM* vm, PyObject* obj){ PyVec2& self = _CAST(PyVec2&, obj); std::stringstream ss;