【C++/OpenSiv3D】波の背景


説明

このような波の形の Polygon を作成し描画するサンプルを紹介します。

サンプル

# include <Siv3D.hpp> // OpenSiv3D v0.4.2

class WaveBackground
{
private:

    Polygon m_polygon;

public:

    WaveBackground() = default;

    explicit WaveBackground(const Rect& rect, double distance = 4.0)
    {
        const Vec2 br(rect.x + rect.w, rect.y + rect.h);
        const Vec2 bl(rect.x, rect.y + rect.h);
        const int32 samples = static_cast<int32>(rect.w / distance);

        Array<Vec2> points;

        for (int32 i : Range(0, samples))
        {
            const double x = Math::Lerp(rect.x, rect.x + rect.w, static_cast<double>(i) / samples);
            const double y = rect.y + rect.h * 0.75 - Math::Sin(x * 0.5_deg) * (rect.h * 0.1);
            points.emplace_back(x,  y);
        }

        points << br << bl;

        m_polygon = Polygon(points);
    }

    void draw(const ColorF& color) const
    {
        m_polygon.draw(color);
    }

    void drawWireframe(const ColorF& color) const
    {
        m_polygon.drawWireframe(1.0, color);
    }
};

void Main()
{
    Scene::SetBackground(Palette::White);

    double distance = 5.0;
    bool showWireframe = false;
    WaveBackground waveBackground(Scene::Rect(), distance);

    while (System::Update())
    {
        waveBackground.draw(Palette::Skyblue);

        if (showWireframe)
        {
            waveBackground.drawWireframe(Palette::Blue);
        }

        if (SimpleGUI::Slider(U"Distance: {:.0f}"_fmt(distance), distance, 1.0, 80.0, Vec2(20, 20), 140, 140))
        {
            waveBackground = WaveBackground(Scene::Rect(), distance);
        }

        SimpleGUI::CheckBox(showWireframe, U"Show wireframe", Vec2(20, 60));
    }
}

実行結果