Example #1
0
	////////////////////////////////////////////////////////////
	/// \brief Sets the beginning and end of the sound's looping sequence using sf::Time
	///
	/// Loop points allow one to specify a pair of positions such that, when the music
	/// is enabled for looping, it will seamlessly seek to begin whenever it encounters end.
	/// The input values are clamped to the duration of the sound. If they are the same,
	/// then a closed loop cannot be formed, and this function will "reset" the loop to the
	/// full length of the sound. Note that the implicit "loop points" from the end to the
	/// beginning of the stream are still honored. Because of this, "reverse" loop ranges,
	/// where end comes before begin, are allowed, and will cause the sound to loop everything
	/// "outside" of the specified range. This function can be safely called at any point
	/// after a stream is opened, and will be applied to a playing sound without affecting
	/// the current playing offset.
	///
	/// \param begin	The offset of the beginning of the loop. Can be any time point within the sound's length
	/// \param end	  The offset of the end of the loop. If Time::Zero is passed, it defaults to the end of the sound
	///
	/// \see getLoopBegin, getLoopEnd
	///
	////////////////////////////////////////////////////////////
	void setLoopPoints(sf::Time begin, sf::Time end)
	{
		std::size_t sampleCount = m_file.getSampleCount();

		// Reset to playing whole stream
		if (begin == end)
		{
			m_loopBegin = 0;
			m_loopEnd = sampleCount;
			return;
		}

		unsigned int sampleRate = getSampleRate();
		unsigned int channelCount = getChannelCount();

		begin = sf::microseconds(std::max(begin.asMicroseconds(), 0ll));
		end = sf::microseconds(std::max(end.asMicroseconds(), 0ll));

		sf::Uint64 loopBegin = static_cast<sf::Uint64>(begin.asSeconds() * sampleRate * channelCount);
		sf::Uint64 loopEnd = static_cast<sf::Uint64>(end.asSeconds() * sampleRate * channelCount);

		loopBegin = std::min(loopBegin, static_cast<sf::Uint64>(sampleCount));
		loopEnd = std::min(loopEnd, static_cast<sf::Uint64>(sampleCount));

		if (!loopEnd)
			loopEnd = sampleCount;

		loopBegin -= loopBegin % channelCount;
		loopEnd -= loopEnd % channelCount;

		m_loopBegin = loopBegin;
		m_loopEnd = loopEnd;
	}
Example #2
0
void Engine::update(sf::Time dt)
{
	m_entMgr->update(dt.asMicroseconds());
	
	if(Stats::get()->getLives() < 0) m_exit = true;
	m_dbg->update(dt.asMilliseconds(), m_entMgr->getPlayer()->getPos());
}
Example #3
0
 template <typename Game> void update(const sf::Time & elapsedTime, Game *) {
     timer += elapsedTime.asMicroseconds();
     glowFadeTimer += elapsedTime.asMicroseconds();
     if (timer > 65000) {
         timer -= 65000;
         frameIndex++;
         if (frameIndex > 5) {
             frameIndex = 5;
             killFlag = true;
         }
     }
     uint8_t color =
         Easing::easeOut<2>(glowFadeTimer, static_cast<int64_t>(300000)) *
         230;
     glow.setColor(sf::Color(color, color, color, 255));
 }
Example #4
0
 template <typename Game> void update(const sf::Time & elapsedTime, Game *) {
     timer += elapsedTime.asMicroseconds();
     glowFadeTimer += elapsedTime.asMicroseconds();
     static const int frameTransitionTime = 70000;
     if (timer > frameTransitionTime) {
         timer -= frameTransitionTime;
         frameIndex++;
         static const int maxFrame = 8;
         if (frameIndex > maxFrame) {
             frameIndex = maxFrame;
             killFlag = true;
         }
     }
     uint8_t color =
         Easing::easeOut<1>(glowFadeTimer, static_cast<int64_t>(560000)) *
         230;
     glow.setColor(sf::Color(color, color, color, 255));
 }
Example #5
0
/**
 * advance the song by the given delta time
 * and play/stop the notes according to the events
 * present in that delta time
 */
static void playSong(
    linthesia::Context &context,
    const sf::Time& delta
) {
    auto events =context.update(delta.asMicroseconds());
    for (const auto& oneEvent : events) {
        context.midiOut.write(oneEvent.second);
    }
}
Example #6
0
void AnimHandler::updateAnimation(const sf::Time& time_elapsed)//Update the current frame (must be called at least once before draw()!)
{
	ctime += (int)time_elapsed.asMicroseconds();
	if (ctime < currentFrame->delay) return;
	cframe++;
	if (cframe >= (int)currentAnim->frames.size() || cframe < 0)
	{
		cframe = 0;
	}
	ctime = ctime % currentFrame->delay;
	currentFrame = &currentAnim->frames[cframe];
}
Example #7
0
SoundManager::FadedMusic::FadedMusic(
    VFileMusic& music, float target, sf::Time fadeDuration):
    target(target),
    music(&music),
    increment(0)
{
    if (fadeDuration.asMicroseconds()) {
        music.setVolume(100 - target);
        increment = (target - music.getVolume()) / fadeDuration.asSeconds();
    } else {
        music.setVolume(target);
    }
}
	void drawFpsCounter(sf::RenderWindow& aWindow, const sf::Font& aFont, sf::Time aDeltaTime)
	{
		sf::Text text;
		text.setFont(aFont);
		text.setColor(sf::Color::Red);
		text.setPosition(0, 50.0f);

		char buffer[Int64TextWidth];
		_i64toa_s(aDeltaTime.asMicroseconds(), buffer, Int64TextWidth, 10);
		//_gcvt_s(buffer, Int64TextWidth, elapsedTime, 20);

		text.setString(buffer);

		aWindow.draw(text);
	}
int main(int argv, char* argc[])
{
	sf::RenderWindow window(sf::VideoMode(windowWidth, windowHeight), "SFML and Box2D", sf::Style::Close);

	window.setVerticalSyncEnabled(false); // vsync messes with updates

	b2Vec2 gravity(0.0f, 0.0f);

	b2World world(gravity);

	sf::Clock clock;
	sf::Clock seconds;

	while (window.isOpen())
	{
		sf::Time elapsed = clock.getElapsedTime();

		if (elapsed.asMicroseconds() >= updateRate.asMicroseconds())
		{
			clock.restart();
			update(&window);
		}
		elapsed = seconds.getElapsedTime();
		if (elapsed.asSeconds() >= 1)
		{
			UPS = tick;
			FPS = frame;
			std::cout << "UPS: " << UPS << ", FPS: " << FPS << std::endl;
			tick = 0;
			frame = 0;
			seconds.restart();
		}

		render(&window);
	}



	return 0;
}
Example #10
0
void Skier::Update_velocity( sf::Time elapsed_time ) {
  
    // This multiplier acts as a general physics speed modifier.
    // All other similar multiplying values behave as relative intensities
    // compared to other physics effects
    long double amount = elapsed_time.asMicroseconds() / 10000.0f;

    // increase lateral velocity by 'amount' if the right or left arrow key
    // is being pressed.  Decrease vertical (downward) velocity by amount
    // if the up arrow is pressed.

    if( sf::Keyboard::isKeyPressed( sf::Keyboard::Right ) ) {
        // turn right
        m_velocity += Util::Get_perpendicular_v2f( m_velocity, amount / 30.0f );
    } else if( sf::Keyboard::isKeyPressed( sf::Keyboard::Left ) ) {
        // turn left.
        m_velocity -= Util::Get_perpendicular_v2f( m_velocity, amount / 30.0f );
    }
    if( sf::Keyboard::isKeyPressed( sf::Keyboard::Up ) ) {
        // slow down...
        m_velocity.y /= 1.0f + amount / 20.0f;
    
        // ... but not too much
        if( m_velocity.y < 0.0f ) {
            m_velocity.y = 0.0f;
        }
        // friction:
        m_velocity.x /= 1.0f + amount / 20.0f;
    }
    #if 0
    if( sf::Keyboard::isKeyPressed( sf::Keyboard::Down ) ) {
        // Nothing curently
    }
    #endif

    // gravity
    m_velocity.y += amount * 2 / 980.6f;

    Normalize_velocity();
}
Example #11
0
    void update(const sf::Time & elapsedTime, Game * pGame) {
        switch (state) {
        case State::opening:
            animationTimer += elapsedTime.asMicroseconds();
            if (animationTimer > 50000) {
                animationTimer -= 50000;
                frameIndex++;
                if (frameIndex > 5) {
                    frameIndex = 4;
                    state = State::ready;
                }
            }
            break;

        case State::ready:
            // TODO: play reward sound
            pGame->getUI().setPowerup(powerup);
            state = State::complete;
            break;

        default:
            break;
        }
    }
Example #12
0
void Crocodile::update(sf::Time elapsed_time) {

    sf::Vector2f previous_direction = direction;
    bool key_pressed = (new_direction != sf::Vector2f(0, 0));
    bool u_turn = (new_direction == - direction);
    bool already_doing_a_turn = (path.front().length < 0);
    if (key_pressed && ! u_turn && ! already_doing_a_turn) {
        direction = new_direction;
    }

    // If the direction has changed, add 2 new path chunks:
    // one for the curve (smooth turn) and one for the straight
    // line that follows.
    if (direction != previous_direction) {
        sf::Vector2f current_head_position = sprites.front().getPosition();

        PathChunk curve;
        curve.from = previous_direction;
        curve.to = direction;
        curve.length = M_PI * curve_radius / 2.0;
        curve.position = current_head_position;
        path.push_front(curve);

        PathChunk straight_line;
        straight_line.from = direction;
        straight_line.to = direction;
        straight_line.length = - curve.length;
        straight_line.position = current_head_position
                + direction*curve_radius
                + previous_direction*curve_radius;
        path.push_front(straight_line);
    }

    // update the distance-to-head of the first path chunk
    sf::Int64 elapsed_ms = elapsed_time.asMicroseconds();
    float velocity = elapsed_ms * speed;
    path.front().length += velocity;

    // update position of all sprites
    std::vector<sf::Sprite>::iterator sprite = sprites.begin();
    std::deque<PathChunk>::iterator chunk = path.begin();
    float chunk_dist_to_head = chunk->length;
    float sprite_dist_to_head = 0.0;

    while (true) {

        if (chunk_dist_to_head >= sprite_dist_to_head) {

            sf::Vector2f prev_pos = sprite->getPosition();

            // Compute new position depending on the type of the path chunk
            sf::Vector2f new_pos;
            // offset is the distance ran on the current path chunk
            float offset = chunk_dist_to_head - sprite_dist_to_head;

            if (chunk->from == chunk->to) { // straight line
                sf::Vector2f shifting = chunk->to * offset;
                new_pos = chunk->position + shifting;

            } else { // curve

                // theta is the angle travelled along on the current path chunk
                float theta = offset / curve_radius;

                float absolute_angle;

                if (chunk->from == sf::Vector2f(1.0, 0.0)
                        && chunk->to == sf::Vector2f(0.0, 1.0)) {
                    absolute_angle = - M_PI / 2.0 + theta;

                } else if (chunk->from == sf::Vector2f(1.0, 0.0)
                        && chunk->to == sf::Vector2f(0.0, -1.0)) {
                    absolute_angle = + M_PI / 2.0 - theta;

                } else if (chunk->from == sf::Vector2f(-1.0, 0.0)
                        && chunk->to == sf::Vector2f(0.0, 1.0)) {
                    absolute_angle = - M_PI / 2.0 - theta;

                } else if (chunk->from == sf::Vector2f(-1.0, 0.0)
                        && chunk->to == sf::Vector2f(0.0, -1.0)) {
                    absolute_angle = M_PI / 2.0 + theta;

                } else if (chunk->from == sf::Vector2f(0.0, 1.0)
                        && chunk->to == sf::Vector2f(1.0, 0.0)) {
                    absolute_angle = M_PI - theta;

                } else if (chunk->from == sf::Vector2f(0.0, 1.0)
                        && chunk->to == sf::Vector2f(-1.0, 0.0)) {
                    absolute_angle = + theta;

                } else if (chunk->from == sf::Vector2f(0.0, -1.0)
                        && chunk->to == sf::Vector2f(1.0, 0.0)) {
                    absolute_angle = M_PI + theta;

                } else if (chunk->from == sf::Vector2f(0.0, -1.0)
                        && chunk->to == sf::Vector2f(-1.0, 0.0)) {
                    absolute_angle = - theta;

                } else {
                    std::cout << "should not happen" << std::endl;
                    exit(1);
                }

                // coordinates of the new position, relative to the circle centre
                float x = cos(absolute_angle) * curve_radius;
                float y = sin(absolute_angle) * curve_radius;

                sf::Vector2f circle_centre = chunk->position + chunk->to * curve_radius;

                new_pos = circle_centre + sf::Vector2f(x, y);

            }

            sprite->setPosition(new_pos);

            sprite->setRotation(
                    atan2(-new_pos.y + prev_pos.y, -new_pos.x + prev_pos.x)
                    * 180 / M_PI);

            sprite++;

            // Once all the sprites are updated,
            // delete useless path chunks and break
            if (sprite == sprites.end()) {
                chunk++;
                path.erase(chunk, path.end());
                break;
            }

            sprite_dist_to_head += dist_between_sprites;

        }
        else {
            chunk++;

            if (chunk == path.end()) {
                std::cout << "oops" << std::endl;
                exit(1);
            }

            chunk_dist_to_head += chunk->length;

        }
    }
}
Example #13
0
void PlayerObject::UpdateCurrent(sf::Time p_xDtime){
	sf::Vector2f l_xVel((sf::Keyboard::isKeyPressed(sf::Keyboard::D) - sf::Keyboard::isKeyPressed(sf::Keyboard::A)), (sf::Keyboard::isKeyPressed(sf::Keyboard::S) - sf::Keyboard::isKeyPressed(sf::Keyboard::W)));
	
	setVelocity(l_xVel * (float)p_xDtime.asMicroseconds());
}
Example #14
0
void Dasher::update(Game * pGame, const std::vector<wall> & walls,
                    const sf::Time & elapsedTime) {
    auto & effects = pGame->getEffects();
    auto & details = pGame->getDetails();
    auto & player = pGame->getPlayer();
    if (health > 0) {
        for (auto & element : effects.get<EffectRef::PlayerShot>()) {
            if (hitBox.overlapping(element->getHitBox()) &&
                element->checkCanPoof()) {
                if (health == 1) {
                    element->disablePuff();
                    element->setKillFlag();
                }
                element->poof();
                health -= 1;
                colored = true;
                colorAmount = 1.f;
            }
        }
        for (auto & helper : pGame->getHelperGroup().get<HelperRef::Laika>()) {
            if (hitBox.overlapping(helper->getHitBox())) {
                health = 0;
            }
        }
        if (health == 0) {
            hSpeed = 0;
            vSpeed = 0;
            frameIndex = 0;
            killFlag = true;
            details.add<DetailRef::DasherCorpse>(
                this->getPosition(),
                getgResHandlerPtr()->getTexture(
                    ResHandler::Texture::gameObjects),
                dasherSheet.getScale().x);
            unsigned long int temp = rng::random<4>();
            if (temp < 1) {
                effects.add<EffectRef::Heart>(
                    getgResHandlerPtr()->getTexture(
                        ResHandler::Texture::gameObjects),
                    getgResHandlerPtr()->getTexture(
                        ResHandler::Texture::redglow),
                    position.x, position.y + 4, Item::Type::Heart);
            } else if (temp < 3) {
                effects.add<EffectRef::GoldHeart>(
                    getgResHandlerPtr()->getTexture(
                        ResHandler::Texture::gameObjects),
                    getgResHandlerPtr()->getTexture(
                        ResHandler::Texture::yellowGlow),
                    position.x, position.y + 4, Item::Type::GoldHeart);
            } else {
                effects.add<EffectRef::Coin>(
                    getgResHandlerPtr()->getTexture(
                        ResHandler::Texture::gameObjects),
                    getgResHandlerPtr()->getTexture(
                        ResHandler::Texture::blueglow),
                    position.x, position.y + 4, Item::Type::Coin);
            }
            effects.add<EffectRef::SmallExplosion>(
                getgResHandlerPtr()->getTexture(
                    ResHandler::Texture::gameObjects),
                getgResHandlerPtr()->getTexture(
                    ResHandler::Texture::fireExplosionGlow),
                position.x, position.y - 2);
            blurEffects.clear();
        }
    }
    SoundController & sounds = pGame->getSounds();
    Enemy::updateColor(elapsedTime);
    dasherSheet.setPosition(position.x + 4, position.y);
    shadow.setPosition(position.x - 4, position.y + 22);
    hitBox.setPosition(position.x, position.y);
    timer += elapsedTime.asMilliseconds();
    auto facePlayer = [this, player]() {
        if (this->position.x > player.getXpos()) {
            this->dasherSheet.setScale(1, 1);
        } else {
            this->dasherSheet.setScale(-1, 1);
        }
    };
    switch (state) {
    case State::idle:
        if (timer >= 200) {
            timer -= 200;
            const int select = rng::random<2>();
            if (select) {
                state = State::dashBegin;
                frameIndex = 1;
            } else {
                state = State::shootBegin;
                frameIndex = 3;
            }
        }
        break;

    case State::pause:
        if (timer >= 200) {
            timer -= 200;
            state = State::dashBegin;
            frameIndex = 1;
        }
        break;

    case State::shooting:
        facePlayer();
        frameTimer += elapsedTime.asMilliseconds();
        if (frameTimer > 80 && shotCount < 3) {
            frameTimer -= 80;
            shotCount++;
            if (position.x > player.getXpos()) {
                effects.add<EffectRef::TurretFlashEffect>(
                    getgResHandlerPtr()->getTexture(
                        ResHandler::Texture::gameObjects),
                    position.x - 14, position.y + 2);
                effects.add<EffectRef::DasherShot>(
                    position.x - 12, position.y,
                    angleFunction(target.x + 8, target.y + 8, position.x,
                                  position.y));
                pGame->getSounds().play(ResHandler::Sound::silenced,
                                        this->shared_from_this(), 220.f, 5.f);
            } else {
                effects.add<EffectRef::TurretFlashEffect>(
                    getgResHandlerPtr()->getTexture(
                        ResHandler::Texture::gameObjects),
                    position.x + 6, position.y + 2);
                effects.add<EffectRef::DasherShot>(
                    position.x + 4, position.y,
                    angleFunction(target.x, target.y + 8, position.x,
                                  position.y));
                pGame->getSounds().play(ResHandler::Sound::silenced,
                                        this->shared_from_this(), 220.f, 5.f);
            }
        }
        if (timer > 300) {
            timer -= 300;
            shotCount = 0;
            state = State::pause;
        }
        break;

    case State::shootBegin:
        facePlayer();
        if (timer > 80) {
            timer -= 80;
            frameTimer = 0;
            target = player.getPosition();
            state = State::shooting;
            frameIndex = 4;
        }
        break;

    case State::dashBegin:
    begin:
        facePlayer();
        if (timer > 352) {
            timer -= 352;
            state = State::dashing;
            sounds.play(ResHandler::Sound::wooshMono, this->shared_from_this(),
                        220.f, 5.f);
            frameIndex = 2;
            uint8_t tries{0};
            float dir{static_cast<float>(rng::random<359>())};
            do {
                tries++;
                if (tries > 254) {
                    state = State::shootBegin;
                    frameIndex = 3;
                    goto begin;
                }
                dir += 12;
            } while (wallInPath(walls, dir, position.x, position.y));
            hSpeed = 5 * cos(dir);
            vSpeed = 5 * sin(dir);
            if (hSpeed > 0) {
                dasherSheet.setScale(-1, 1);
            } else {
                dasherSheet.setScale(1, 1);
                dasherSheet.setScale(1, 1);
            }
        }
        break;

    case State::dashing:
        frameTimer += elapsedTime.asMilliseconds();
        if (frameTimer > 40) {
            frameTimer = 0;
            blurEffects.emplace_back(dasherSheet.getSpritePtr(), position.x,
                                     position.y);
        }
        if (timer > 250) {
            timer -= 250;
            state = State::dashEnd;
            frameIndex = 1;
            hSpeed = 0.f;
            vSpeed = 0.f;
        }

        if (Enemy::checkWallCollision(walls, position.x, position.y)) {
            hSpeed *= -1.f;
            vSpeed *= -1.f;
        }
        break;

    case State::dashEnd:
        if (timer > 150) {
            blurEffects.clear();
            timer -= 150;
            state = State::idle;
            frameIndex = 0;
        }
        break;
    }

    if (!blurEffects.empty()) {
        for (auto it = blurEffects.begin(); it != blurEffects.end();) {
            if (it->getKillFlag())
                it = blurEffects.erase(it);
            else {
                it->update(elapsedTime);
                ++it;
            }
        }
    }

    position.x += hSpeed * (elapsedTime.asMicroseconds() * 0.00005f);
    position.y += vSpeed * (elapsedTime.asMicroseconds() * 0.00005f);
}
Example #15
0
float Game::getFPS(const sf::Time& time) {
	return (1000000.0f / time.asMicroseconds());
}
Example #16
0
int main()
{
	std::map<std::string, std::string> _texts = std::map<std::string, std::string>();

	std::vector<GameObject*> _gameObjects = std::vector<GameObject*>();

	sf::RenderWindow window(sf::VideoMode(800, 600), "Collision test");
	/*
	sf::Texture _bkg;
	_bkg.loadFromFile("gorge.jpg");
	_bkg.setRepeated(true);
	sf::Sprite _background(_bkg, sf::IntRect(0, 0, 2000, 1000));
	*/

	if(load("Brown_Rocks.png", sf::Vector2u(32, 32), nullptr, 800, 600))
		std::cout << "YEAH\n";

	sf::Texture _bkg;
	_bkg.loadFromFile("Brown_Rocks.png");
	_bkg.setRepeated(true);
	sf::Sprite _background(_bkg, sf::IntRect(0, 0, 2000, 1000));

	std::cout << sf::Texture::getMaximumSize() << "\n";	

	sf::Texture _cliffsTexture;
	_cliffsTexture.loadFromFile("Cliffs.png");
	_cliffsTexture.setRepeated(true);
	sf::Sprite _cliffsBottom(_cliffsTexture);
	sf::Sprite _cliffsTop(_cliffsTexture, sf::IntRect(0, 400, 800, -800));
	_cliffsTop.setPosition(-300, 0);


	std::cout << _cliffsTexture.getSize().x << "," << _cliffsTexture.getSize().y;


	sf::Texture _platformTexture;
	_platformTexture.loadFromFile("Rocks_Platform1.png");
	_platformTexture.setRepeated(true);
	sf::Sprite _platform(_platformTexture, sf::IntRect(0, 0, 2000, 32));
	_platform.setPosition(0, window.getSize().y - 32);

	sf::Sprite _platformBottom(_platformTexture, sf::IntRect(0, 32, 2000, -32));
	_platformBottom.setPosition(0, 0);

	sf::Texture texture;
	texture.loadFromFile("plane.png");
	//texture.loadFromFile("player.png");
	GameObject _player(texture);
	_player.setPosition(window.getSize().x / 2.f - 300, window.getSize().y / 2.f - 75);
	_gameObjects.push_back(&_player);

	sf::Texture etexture;
	etexture.loadFromFile("plane.png");
	//sf::IntRect textRect(64, 0, -64, 32);
	//GameObject _enemy(etexture, textRect);
	GameObject _enemy(etexture);
	_enemy.setPosition(window.getSize().x / 2.f + 75, window.getSize().y / 2.f - 16);
	_gameObjects.push_back(&_enemy);

	sf::RectangleShape _bounding1(sf::Vector2f(_player.getBoundingBox().width - 1, _player.getBoundingBox().height - 1));
	_bounding1.setPosition(_player.getPosition());
	_bounding1.setFillColor(sf::Color::Transparent);
	_bounding1.setOutlineColor(sf::Color::Red);
	_bounding1.setOutlineThickness(1);

	sf::RectangleShape _bounding2(sf::Vector2f(_enemy.getBoundingBox().width - 1, _enemy.getBoundingBox().height - 1));
	_bounding2.setPosition(_enemy.getPosition());
	_bounding2.setFillColor(sf::Color::Transparent);
	_bounding2.setOutlineColor(sf::Color::Red);
	_bounding2.setOutlineThickness(1);

	sf::Font font;
	font.loadFromFile("VeraMono.ttf");
	sf::Text _text("Debug", font, 12);
	_text.setPosition(0, 0);

	sf::Clock clock;
	sf::Time timeSinceLastUpdate = sf::Time::Zero;

	// Start the game loop
	while (window.isOpen())
	{
		sf::Time elapsedTime = clock.restart();
		timeSinceLastUpdate += elapsedTime;

		while (timeSinceLastUpdate > TimePerFrame)
		{
			timeSinceLastUpdate -= TimePerFrame;

			// Process events
			sf::Event event;
			while (window.pollEvent(event))
			{
				// Close window : exit
				if (event.type == sf::Event::Closed)
					window.close();

				if(event.type == sf::Event::KeyPressed)
				{
					short id = 1;
					for( auto& i : _gameObjects )
					{
						i->update(event, id);
						id++;
					}
				}
			}

			if(checkCollisions(_gameObjects, _texts))
				_texts["Collision"] = "Detected";
			else
				_texts["Collision"] = "NOT Detected";

			std::map<std::string, std::string>::iterator i = _texts.begin();
			std::stringstream ss;

			for( ; i != _texts.end(); ++i )
			{
				ss << i->first << ": " << i->second << std::endl << std::endl;
			}

			_text.setString(ss.str());
		}

		_bounding1.setPosition(_player.getPosition());
		_bounding2.setPosition(_enemy.getPosition());

		_statisticsUpdateTime += elapsedTime;
		_statisticsNumFrames += 1;

		if (_statisticsUpdateTime >= sf::seconds(1.0f))
		{
			std::stringstream fps, timeupdate;
			fps << _statisticsNumFrames;
			timeupdate << _statisticsUpdateTime.asMicroseconds() / _statisticsNumFrames;

			_statisticsUpdateTime -= sf::seconds(1.0f);
			_statisticsNumFrames = 0;

			_texts["FPS"] = fps.str() + "\n" + "Time / Update = " + timeupdate.str() + "us";
		}

		window.clear();

		window.draw(_background);
		// window.draw(m_vertices, &m_tileset);
		window.draw(_cliffsBottom);
		window.draw(_cliffsTop);
		window.draw(_platform);
		window.draw(_platformBottom);

		for( auto& i : _gameObjects )
		{
			window.draw(*i);
		}

		window.draw(_text);

		window.draw(_bounding1);
		window.draw(_bounding2);

		window.display();
	}
}
Example #17
0
	/*#####
	# Simulation
	#####*/
	void Simulation::update(const sf::Time& _timeElapsed)
	{
		m_IngameTime += m_GameVelocity * _timeElapsed.asMicroseconds();
	}
Example #18
0
// ----------------------------------------------------------------- getFPS
inline float getFPS(const sf::Time& time) {
         return (1000000.0f / time.asMicroseconds());
}
Example #19
0
void Skier::Update_sprite( sf::Time elapsed_time ) {
    // Note: This math is a little weird due to our sprite angles
    //       being based on a typical cartesian grid whereas SFML's
    //       image grid being a typical grid mirrored about the X-axis.
  
    if( m_velocity.y == 0 ) {
        if( m_velocity.x > 0 ) {
            // Facing straight right
            Get_sprite().setTextureRect( Sprites::SKIER_CARVE_0 );
        } else if( m_velocity.x < 0 ){
            // Facing straight left
            Get_sprite().setTextureRect( Sprites::SKIER_CARVE_180 );
        }
    } else {
        float slope = m_velocity.x / m_velocity.y;

        if( m_velocity.y >= 0 ) {
            // Angle is between 180 and 360 on normal cartesion grid

            if( slope >= Sprite_angle::SLOPE_352_5 ) {
                Get_sprite().setTextureRect( Sprites::SKIER_CARVE_0 );
            } else if( slope >= Sprite_angle::SLOPE_337_5 ) {
                Get_sprite().setTextureRect( Sprites::SKIER_CARVE_345 );
            } else if( slope >= Sprite_angle::SLOPE_322_5 ) {
                Get_sprite().setTextureRect( Sprites::SKIER_CARVE_330 );
            } else if( slope >= Sprite_angle::SLOPE_292_5 ) {
                Get_sprite().setTextureRect( Sprites::SKIER_CARVE_315 );
            } else if( slope <= Sprite_angle::SLOPE_187_5 ) {
                Get_sprite().setTextureRect( Sprites::SKIER_CARVE_180 );
            } else if( slope <= Sprite_angle::SLOPE_202_5 ) {
                Get_sprite().setTextureRect( Sprites::SKIER_CARVE_195 );
            } else if( slope <= Sprite_angle::SLOPE_217_5 ) {
                Get_sprite().setTextureRect( Sprites::SKIER_CARVE_210 );
            } else if( slope <= Sprite_angle::SLOPE_247_5 ) {
                Get_sprite().setTextureRect( Sprites::SKIER_CARVE_225 );
            } else {
                Get_sprite().setTextureRect( Sprites::SKIER_CARVE_270 );
            }
        } else {
            // Angle is between 0 and 180 on normal cartesian grid
    
            if( slope >= Sprite_angle::SLOPE_172_5 ) {
                Get_sprite().setTextureRect( Sprites::SKIER_CARVE_180 );
            } else if( slope >= Sprite_angle::SLOPE_157_5 ) {
                Get_sprite().setTextureRect( Sprites::SKIER_CARVE_165 );
            } else if( slope <= Sprite_angle::SLOPE_7_5 ) {
                Get_sprite().setTextureRect( Sprites::SKIER_CARVE_0 );
            } else if( slope <= Sprite_angle::SLOPE_22_5 ) {
                Get_sprite().setTextureRect( Sprites::SKIER_CARVE_15 );
            } else {
                // Already took care of cases where slope = 0
                if( slope > 0.0f ) {
                    Get_sprite().setTextureRect( Sprites::SKIER_CARVE_150 );
                } else {
                    Get_sprite().setTextureRect( Sprites::SKIER_CARVE_30 );
                }
            }
        }
    }

    float elapsed_time_ms = elapsed_time.asMicroseconds() / 1000.0f;
  
    Move( m_velocity.x * elapsed_time_ms, m_velocity.y * elapsed_time_ms );
}