#pragma once #include namespace extra2d { // --------------------------------------------------------------------------- // 常量 // --------------------------------------------------------------------------- constexpr float PI_F = 3.14159265358979323846f; constexpr float DEG_TO_RAD = PI_F / 180.0f; constexpr float RAD_TO_DEG = 180.0f / PI_F; // --------------------------------------------------------------------------- // 2D 向量 // --------------------------------------------------------------------------- struct Vec2 { float x = 0.0f; float y = 0.0f; constexpr Vec2() = default; constexpr Vec2(float x, float y) : x(x), y(y) {} // 基础运算 Vec2 operator+(const Vec2 &v) const { return {x + v.x, y + v.y}; } Vec2 operator-(const Vec2 &v) const { return {x - v.x, y - v.y}; } Vec2 operator*(float s) const { return {x * s, y * s}; } Vec2 operator/(float s) const { return {x / s, y / s}; } Vec2 operator-() const { return {-x, -y}; } Vec2 &operator+=(const Vec2 &v) { x += v.x; y += v.y; return *this; } Vec2 &operator-=(const Vec2 &v) { x -= v.x; y -= v.y; return *this; } Vec2 &operator*=(float s) { x *= s; y *= s; return *this; } Vec2 &operator/=(float s) { x /= s; y /= s; return *this; } bool operator==(const Vec2 &v) const { return x == v.x && y == v.y; } bool operator!=(const Vec2 &v) const { return !(*this == v); } // 向量运算 float length() const { return std::sqrt(x * x + y * y); } float lengthSquared() const { return x * x + y * y; } Vec2 normalized() const { float len = length(); if (len > 0.0f) return {x / len, y / len}; return {0.0f, 0.0f}; } float dot(const Vec2 &v) const { return x * v.x + y * v.y; } float cross(const Vec2 &v) const { return x * v.y - y * v.x; } float distance(const Vec2 &v) const { return (*this - v).length(); } float angle() const { return std::atan2(y, x) * RAD_TO_DEG; } static Vec2 lerp(const Vec2 &a, const Vec2 &b, float t) { return a + (b - a) * t; } static constexpr Vec2 Zero() { return {0.0f, 0.0f}; } static constexpr Vec2 One() { return {1.0f, 1.0f}; } static constexpr Vec2 UnitX() { return {1.0f, 0.0f}; } static constexpr Vec2 UnitY() { return {0.0f, 1.0f}; } }; inline Vec2 operator*(float s, const Vec2 &v) { return v * s; } using Point = Vec2; } // namespace extra2d