2014-12-01 2 views
1

고등학생의 독립적 인 학습 프로젝트 중 하나 인 Visual C++에서 SFML을 사용하여 간단한 게임 (특히 게임 "Snake")을 만들어야합니다 (예 C++ 및 SFML을 처음 사용합니다). 게임의 핵심 및 그래픽을 코딩했으며 이제는 오디오 및 음향 효과에 대해 작업하고 있습니다. SFML 서적에서 오디오에 관한 몇 가지 사항을 읽었지 만 코드에 올바르게 구현하는 방법에 대해서는 여전히 혼란 스러웠습니다. 나는 sf : Sound와 sf :: SoundBuffer 객체를 만들고, 사운드와 음악 각각에 대해 loadFromFile과 openFromFile을 사용하여로드하고 sound.play()와 sound.stop()을 사용하여 각각 재생 및 정지해야한다는 것을 알고있다. 그러나 이것은 질문이 들어오는 곳입니다. 이러한 메소드를 메인 메소드에로드 할 것인가, 글로벌 오브젝트로서 작성해 코드 전체에서 사용할 수 있을까, sfx가 발생하는 함수에로드 할 수 있을지 어떨지, 모든 사운드를 포함하는 객체? ... 일반적으로 어떻게하면 내 오디오 파일을 올바르게 구성하고 구현할 수 있습니까? 나는 뱀이 사과와 충돌 할 때 "먹는"SFX를 재생할 수있을 것입니다 방법,C++에서 SFML 오디오를 올바르게 구성하고 구현하려면 어떻게해야합니까?

홈페이지 방법 예를 들어

/*Main method*/// 
int main(){ 
    /*Initialize the objects*/ 
    Snake snake = Snake(); 
    sf::Text textCount; 
    Apple apple(0, 0); 
    apple.locateApple(); 
    sf::RenderWindow window(sf::VideoMode(windowWidth, windowHeight), "SFML Application"); 
    /*Load the audio*/ 

    sf::Music backgroundMusic; 
    sf::Sound eating; 
    sf::SoundBuffer sb_eating; 
    sf::Sound moving; 
    sf::SoundBuffer sb_moving; 
    sf::Sound losing; 
    sf::SoundBuffer sb_losing; 
    sf::Sound begin; 
    sf::SoundBuffer sb_begin; 

    if (!backgroundMusic.openFromFile("backgroundmusic.wav")) 
     std::cerr << "Error opening \"backgroundmusic.wav\"" << std::endl; 
    if (!sb_eating.loadFromFile("eatingsfx.wav")) 
     std::cerr << "Error opening \"eatingsfx.wav\"" << std::endl; 
    if (!sb_moving.loadFromFile("movingsfx.wav")) 
     std::cerr << "Error opening \"movingsfx.wav\"" << std::endl; 
    if (!sb_losing.loadFromFile("losingsfx.wav")) 
     std::cerr << "Error opening \"losingsfx.wav\"" << std::endl; 
    if (!sb_begin.loadFromFile("beginsfx.wav")) 
     std::cerr << "Error opening \"beginsfx.wav\"" << std::endl; 

    eating.setBuffer(sb_eating); 
    moving.setBuffer(sb_moving); 
    losing.setBuffer(sb_losing); 
    begin.setBuffer(sb_begin); 

    moving.setVolume(50); 

    backgroundMusic.setLoop(true); 
    backgroundMusic.play(); 

    /*Load the font*/ 
    sf::Font font; 
    if (!(font.loadFromFile("arial.ttf"))) 
     std::cout << "Error loading fonts" << std::endl; 
    /*Create the text*/ 
    textCount.setFont(font); 
    textCount.setString(std::string("points: ") + std::to_string(points)); 
    textCount.setColor(sf::Color::Red); 
    textCount.setCharacterSize(20); 
    textCount.setPosition(windowWidth/2 - (textCount.getString().getSize()*(textCount.getCharacterSize()/5)), textCount.getCharacterSize() - 5); 
    textCount.setStyle(sf::Text::Bold); 

    window.draw(textCount); 

    /*Set Framerate fps*/ 
    window.setFramerateLimit(15); 

    /*MAIN GAME LOOP*/ 
    counterTick = 1; 


    while (inGame) 
    { 
     std::string counter = std::to_string(counterTick); 
     std::cout << "Tick: " + counter << std::endl; 

     window.clear(sf::Color::Black); 
     sf::Event event; 
     while (window.pollEvent(event)){ 
      if (event.type == sf::Event::Closed) 
       window.close(); 
     } 
     if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Escape)) break; 
     /*Call Updates*/ 
     snake.input(); 
     snake.checkReals(); 
     snake.moveUpdate(); 
     moving.play(); 

     /*Call Collisions*/ 
     std::cout << "  Outside Collision Loop " << std::endl; 
     checkApple(snake, apple); 
     checkBoundary(snake); 

     /*Call Draw*/ 
     std::vector<sf::RectangleShape> shapearray = snake.draw(); 
     for (int i = shapearray.size() - 1; i >= 0; i--){ 
      window.draw(shapearray[i]); 
     } 
     window.draw(textCount); 
     window.draw(apple.draw()); 
     window.display(); 

     counterTick++; 

    } 
    losing.play(); 
    backgroundMusic.stop(); 
    std::system("PAUSE");//bad practice, debuggin purposes 
    return 0; 
} 

을 : 여기에 지금까지 가지고 무엇인가?

애플 방법

void checkApple(Snake mA, Apple& mB){ 
    if ((mA.x[0] == mB.x()) && (mA.y[0] == mB.y())){ 
     dots += dotInterval; 
     std::cout << "In Collision Method" << std::endl; 
     points++; 
     textCount.setString(std::string("points: ") + std::to_string(dots - 3)); 
     mB.locateApple(); 

    } 
} 

나는이 포럼뿐만 아니라 질문이있는 경우 이렇게 문의하시기 바랍니다 새로운 오전을 확인 : 여기 내 checkApple() 방법이다.

답변

1

우선, 저는 C++ & SFML을 처음 접했습니다. 내가 가진 것보다 당신의 문제에 대한 더 나은 해결책이있을 것이라고 확신하지만 여기서는 간다.

나는 loadAudio (std :: string source)라는 메서드와 오디오를 저장하는 벡터를 가지고있다.

class Audio { 

private: 
    sf::SoundBuffer buffer; 
    sf::Sound sound; 
    std::string _src; 
public: 
    void init(std::string src) {  //Initialize audio 
     _src = src; 
     buffer.loadFromFile(src); 
     sound.setBuffer(buffer); 
    } 
    void play(){ 
     sound.play();  // Play queued audio 
    } 
    void stop(){ 
     sound.stop(); 
    } 
    //void setVolume(), void setPitch() .... 


}; 

std::vector<Audio*> audio; 

void loadAudio(std::vector<std::string> src) { 
    audio.push_back(new Audio()); 
    audio.back()->init(src[i]); 
} 

그래서 기본적으로 게임의 시작 부분에서 나는이 같은 소리를 선언 : 다음 audio[0]->play()

+0

매우 간단하면서도 효율적인 코드를 사용하여 벡터에 저장된 소리를 액세스 할 수 있습니다

loadAudio("sound/foo.wav"); loadAudio("sound/bar.wav"); 

. 매우 도움이되는 회원은 저의 다른 질문에서 오디오로 작업 할 수있는 또 다른 좋은 방법을 제시했습니다. 새로운 SFML을 배우면서 행운을 빌어 요. 감사 – codingbash

관련 문제