Hello,
I'd like to play a sound when my ship is moving. Where can I call "ship_sound.play()" ? I tried inside the sf::Keyboard::IsKeyPressed() but it plays the sound and restart it at the same time (which is logic)
void Game::run()
{
window.create(sf::VideoMode(800,600), "Test", sf::Style::Default);
window.setVerticalSyncEnabled(true);
sf::SoundBuffer buffer;
if(!buffer.loadFromFile("ship.ogg"))
{
std::cerr << "Failed to load ship sound" << std::endl;
}
else
{
std::unique_ptr<Ship> player = std::make_unique<Ship>(10,10,40);
sf::Sound ship_sound;
ship_sound.setBuffer(buffer);
while(window.isOpen() == true)
{
sf::Event ev;
while(window.pollEvent(ev) == true)
{
if(ev.type == sf::Event::Closed)
{
window.close();
}
if(ev.type == sf::Event::KeyPressed)
{
if(ev.key.code == sf::Keyboard::Escape)
{
window.close();
}
}
}
//Left : If only Left Key is pressed
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
//Left rotation: If Left + Either Down or Up are pressed
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left) && (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) || sf::Keyboard::isKeyPressed(sf::Keyboard::Up)))
{
player->rotate(10);
}
else
{
player->move_x(-10);
}
}
//Right : If only Right Key is pressed
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
//Right rotation : If Right + Either Down or Up are pressed
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right) && (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) || sf::Keyboard::isKeyPressed(sf::Keyboard::Up)))
{
player->rotate(-10);
}
else
{
player->move_x(10);
}
}
//Up : If only Up Key is pressed
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up) && (sf::Keyboard::isKeyPressed(sf::Keyboard::Left) == false && sf::Keyboard::isKeyPressed(sf::Keyboard::Right) == false))
{
player->move_y(-10);
}
//Down : If only Down Key is pressed
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down) && (sf::Keyboard::isKeyPressed(sf::Keyboard::Left) == false && sf::Keyboard::isKeyPressed(sf::Keyboard::Right) == false))
{
player->move_y(10);
}
window.clear(sf::Color::Black);
player->drawOn(&window);
window.display();
}
}
}
Regards
Thanks for your answer eXpl0it3r,
I'd just like one sound to be played when the ship moves (every positions).
Here is a method I wrote for the Ship class :
void Ship::move_sound(sf::Sound *sound)
{
if(isSoundPlaying == false)
{
sound->play();
isSoundPlaying = true;
}
else
{
sound->stop();
isSoundPlaying = false;
}
}
isSoundPlaying is a boolean that is initialized to false when the Ship object is created. Then I put :
player->move_sound();
inside each if statements but it doesn't give me the loop effect I'd like to have.
I'd like that the ship sound (1 second) would repeat each time it reaches the end of its loop and that either Up, Down, Left or Right is pressed (at least).