2014-01-25 7 views
0

Я очень заинтересован в создании сердца.Создание сердца в C++

Я знаю о геометрических примитивных типах.

http://www.opentk.com/doc/chapter/2/opengl/geometry/primitives

Мне любопытно, как бы я идти о получении изогнутой линии. Должен ли я использовать библиотеку cmath и связать ее с двумя точками?

Я искал много разных сайтов о математике за созданием сердец.

http://www16.ocn.ne.jp/~akiko-y/heart2/index_heart2_E.html

http://www.mathematische-basteleien.de/heart.htm

я борюсь с портированием этой математики C++, а не фактической математику; Я только начинаю изучать язык.

Мне бы очень понравилось, если бы кто-то мог предоставить мне примерный код и объяснение, поскольку я не могу найти это в Интернете. Также я использую структуру SFML для этого проекта.

Спасибо!

Ниже приведен пример текущего кода.

enter image description here

#include <SFML/Graphics.hpp> 
#include <iostream> 
#include <string> 
#include <ctime> 
#include <cstdlib> 



int main() 
{ 

    sf::RenderWindow Window; 
    Window.create(sf::VideoMode(800, 600), "My First Smfl Game"); 

    Window.setKeyRepeatEnabled(false); 



    sf::Texture pTexture; 

    while(Window.isOpen()) 
    { 
     sf::Event Event; 
     while(Window.pollEvent(Event)) 
     { 
      switch(Event.type) 
      { 
       case sf::Event::Closed: 
        Window.close(); 
        break; 
      } 


     } 

     sf::VertexArray vArray(sf::Lines, 20); 
     vArray[0].position = sf::Vector2f(82, 300); 
     vArray[1].position = sf::Vector2f(82, 84); 
     vArray[2].position = sf::Vector2f(82, 84); 
     vArray[3].position = sf::Vector2f(200, 84); 
     vArray[4].position = sf::Vector2f(200, 84); 
     vArray[5].position = sf::Vector2f(200, 100); 
     vArray[6].position = sf::Vector2f(200, 100); 
     vArray[7].position = sf::Vector2f(99, 100); 
     vArray[8].position = sf::Vector2f(99, 100); 
     vArray[9].position = sf::Vector2f(99, 284); 
     vArray[10].position = sf::Vector2f(99, 284); 
     vArray[11].position = sf::Vector2f(200, 284); 
     vArray[12].position = sf::Vector2f(200, 284); 
     vArray[13].position = sf::Vector2f(200, 300); 
     vArray[14].position = sf::Vector2f(200, 300); 
     vArray[15].position = sf::Vector2f(82, 300); 
     vArray[16].position = sf::Vector2f(250, 300); 
     vArray[17].position = sf::Vector2f(300, 82); 
     vArray[18].position = sf::Vector2f(380, 300); 
     vArray[19].position = sf::Vector2f(320, 82); 
     for(int k = 0; k < 20; k++) 
     { 
      int red = rand() % 255; 
      int green = rand() % 255; 
      int blue = rand() % 255; 

      vArray[k].color = sf::Color(red, green, blue); 
     } 

     Window.draw(vArray); 
     Window.display(); 
     Window.clear(); 
    } 
} 
+0

Вы можете посмотреть на кривых Безье и де алгоритма Кастельжо в. Это упростит рисование кривой. Я разместил видео на https://www.youtube.com/watch?v=YATikPP2q70, но поиск в Google «de Casteljau» принесет много хитов. Это легко, попробуйте! –

ответ

1

Заменить жестко закодированные координаты для вашей кривой (все vArray[.].position заданий) с помощью кода, который генерирует координаты. Чтобы сгенерировать эти координаты, вам просто нужно выбрать одну из предложенных кривых из ваших ссылок. Ниже приводится возможная реализация method 3 от вашего второго звена (это одна с четырьмя квадратами, которые казались достаточно просто реализовать):

#include <vector> 
#include <math.h> 

#ifndef M_PI 
#define M_PI 3.14159265358979323846 
#endif // M_PI 

// ... 

    int x0 = 800/2; // Coordinates of the center of the heart 
    int y0 = 600/2; 

    int size = 400; // Size of the heart 
    int r = size/4; // Radius of the curves 

    int total_curve_vertex_count = 40; // Maximum number of vertices per curve 
    int total_vertex_count = 80; // Total number of vertices: 30 + 10 + 10 + 30 

    struct CurveInfo // Store information for each of the four square curves 
    { 
     int vertex_count; 
     double t0; // Angle origin 
     double s; // Angle sign: +1 or -1 
     int cx, cy; // (Relative) coordinates of the center of the curve 
    } 
    curve_infos[4] = 
    { 
     // Upper-left 
     { 3 * total_curve_vertex_count/4,  0.0, -1.0, -r, -r}, 
     // Lower-left 
     {  total_curve_vertex_count/4, 1.5 * M_PI, 1.0, -r, r}, 
     // Lower-right 
     {  total_curve_vertex_count/4,  M_PI, 1.0, r, r}, 
     // Upper-right 
     { 3 * total_curve_vertex_count/4, 0.5 * M_PI, -1.0, r, -r}, 
    }; 

    std::vector<sf::Vector2f> vertices(total_vertex_count); 
    int vertex_index = 0; 

    for(int i = 0; i < 4; i++) 
    { 
     CurveInfo& curve_info = curve_infos[i]; 
     int vertex_count = curve_info.vertex_count; 
     double t0 = curve_info.t0; 
     double s = curve_info.s; 
     int cx = x0 + curve_info.cx; 
     int cy = y0 + curve_info.cy; 

     for(int j = 0; j < vertex_count; j++) 
     { 
      double dt = s * 2.0 * M_PI * j/(total_curve_vertex_count - 1); 
      int x = cx + r * cos(t0 + dt); 
      int y = cy + r * sin(t0 + dt); 
      vertices[vertex_index++] = sf::Vector2f(x, y); 
     } 
    } 

    // Generate the vertices of the lines primitives 
    int total_line_count = total_vertex_count - 1; 
    // Don't duplicate the first and last vertices 
    int line_vertex_count = 2 * total_vertex_count - 2; 

    sf::VertexArray vArray(sf::Lines, line_vertex_count); 

    int line_index = 0; 
    vertex_index = 0; 

    for(int k = 0; k < total_line_count; k++) 
    { 
     vArray[line_index++].position = vertices[vertex_index++]; 
     vArray[line_index++].position = vertices[vertex_index]; 
    } 

    for(int k = 0; k < line_vertex_count; k++) 
    { 
     int red = rand() % 255; 
     int green = rand() % 255; 
     int blue = rand() % 255; 

     vArray[k].color = sf::Color(red, green, blue); 
    } 

// ... 
+0

Когда я запускаю свой код, он дает мне эту ошибку: переменная длина массива элемента не-POD типа 'sf :: Vector2f' (aka 'Vector2 ') – AEGIS

+0

@AEGIS Код использовался нестандартным расширением C++, я изменил вместо этого использовать std :: vector. – user3146587

+0

Большое вам спасибо! – AEGIS