void GameStateCinematic::update(sf::Time dt) { this->activateNext += dt.asSeconds(); if (this->activateNext >= 0.25 && next) { this->d->pop_front(); this->c++; this->next = false; this->activateNext = 0; } if (this->control.empty()) { this->game->changeState(this->nextState); } else if (this->c == this->control.front()) { this->background.pop_front(); this->control.pop_front(); this->c = 0; } }
int main() { sf::Clock clock; initTexts(); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } window.clear(sf::Color(244, 67, 54)); if(game_over) { window.draw(endText); ostringstream s; s << "Your score was : " << snake.length(); scoreText.setString(s.str()); window.draw(scoreText); } else { input(dir); sf::Time elapsed = clock.getElapsedTime(); if(elapsed >= delta) { if(snake.head()->position() == f.position()) { snake.add(); f.generatePos(); delta = sf::seconds(delta_i.asSeconds() - (float)snake.length()/100); } snake.move(dir); clock.restart(); } o.draw(); f.draw(); snake.draw(); } window.display(); } return 0; }
/* * move */ void Bee::targetMove(sf::Time dt) { if(avoidanceClock_.asSeconds() <= 0){ Vec2d currSpeed = directionTo(target_).normalised() * speed_.length(); Collider dummy(position_, rayon_); dummy.move(currSpeed*dt.asSeconds()); if(getAppEnv().getWorld().isFlyable(dummy.getPosition())) { position_ = dummy.getPosition(); }else{ avoidanceClock_ = sf::seconds(getConfig()["moving behaviour"]["target"] ["avoidance delay"].toDouble()); } }else{ avoidanceClock_ -= dt; RandomMove(dt); } }
void ParticleSystem::Update(sf::Time dt) { for(unsigned int id : _EntitiesToUpdate) { Entity* e = this->GetEntity(id); ParticleComponent* pc = e->GetComponent<ParticleComponent>("particle"); for(std::size_t i = 0; i < pc->_particleInfo.size(); ++i) { ParticleInfo& p = pc->_particleInfo[i]; p.life -= dt; if(p.life <= sf::Time::Zero) pc->resetParticle(i); pc->_particles._vertices[i].position += p.velocity * dt.asSeconds(); float ratio = p.life.asSeconds() / pc->_lifeTime.asSeconds(); pc->_particles._vertices[i].color.a = static_cast<sf::Uint8>(ratio * 255); } } }
void Player::update(sf::Time deltaTime) { float seconds = deltaTime.asSeconds(); if(_rotation != 0) { float angle = _rotation*180*seconds; _ship.rotate(angle); } if(_is_moving) { float angle = _ship.getRotation() / 180 * M_PI - M_PI / 2; _velocity += sf::Vector2f(std::cos(angle),std::sin(angle)) * 60.f * seconds; } _ship.move(seconds * _velocity); }
//What's in doStuff right now is only for testing purpose. Lot of stuff to do here. void Elodie::doStuff(const EventHandler& event, const std::vector< std::vector<TileSprite*> >& tiles, EntityMap& entities, sf::Time animate) { //Compute the gravity computeGravity(animate); //Check the collisions, set the new distances and do the move Collide collideTiles = collideWithTiles(tiles, animate.asSeconds()); setDistance(collideTiles); move(animate.asSeconds()*(speed.x), animate.asSeconds()*speed.y); spriteCast->update(animate); //Change the sprite in accord with the speed changeAnimation(collideTiles); handleEvent(event, entities, collideTiles); if (0 == speed.x && !collideTiles.right["surface"]) { speed.x = moveSpeed; } float dist = cameraPos.x - spriteCast->getPosition().x; if (dist > 0 && !collideTiles.right["surface"] && !buffed) { buffed = true; speed.x = moveSpeed + dist; } buffed = !collideTiles.right["surface"]; if (buffed && dist <= 0) { buffed = false; speed.x = moveSpeed; } //Other stuff to do attackTimer += animate.asSeconds(); pvTimer += animate.asSeconds(); if (pvTimer > interRecoveryTime) { pvTimer = 0; immersionLevel = immersionLevel == 100 ? 100 : immersionLevel + 1; } if (damageCD) { --damageCD; } cameraPos.x += (moveSpeed)*animate.asSeconds(); cameraPos.y = spriteCast->getPosition().y; }
void mover(da::Game &game, const sf::Time &delta) { int vert = sf::Keyboard::isKeyPressed(sf::Keyboard::S) - sf::Keyboard::isKeyPressed(sf::Keyboard::W); int horz = sf::Keyboard::isKeyPressed(sf::Keyboard::D) - sf::Keyboard::isKeyPressed(sf::Keyboard::A); if (vert || horz) { float theta = atan2(vert, horz); xform->move(horz * delta.asSeconds() * 100.f, vert * delta.asSeconds() * 100.f); dirAnim->setDirection(theta); dirAnim->getAnimation().play(); } else { dirAnim->getAnimation().stop(); } }
void Aircraft::updateMovementPattern(sf::Time dt) { const std::vector<Direction>& directions = Table[mType].directions; if (!directions.empty()) { float distanceToTravel = directions[mDirectionIndex].distance; if (mTravelledDistance > distanceToTravel) { mDirectionIndex = (mDirectionIndex + 1) % directions.size(); mTravelledDistance = 0.f; } float Radians = toRadian(directions[mDirectionIndex].angle + 90.f); float vx = getSpeed() * std::cos(Radians); float vy = getSpeed() * std::sin(Radians); setVelocity(vx, vy); mTravelledDistance += getSpeed() * dt.asSeconds(); } }
void Aircraft::updateMovementPattern(sf::Time delta) { const std::vector<Direction>& directions = Table[mType].directions; if (!directions.empty()) { float distanceToTravel = directions[mDirectionIndex].distance; if (mTravelledDistance > distanceToTravel) { mDirectionIndex = (mDirectionIndex + 1) % directions.size(); mTravelledDistance = 0.f; } float radians = Utility::toRadian(directions[mDirectionIndex].angle + 90.f); float xVel = getMaxSpeed() * std::cos(radians); float yVel = getMaxSpeed() * std::sin(radians); setVelocity(xVel, yVel); mTravelledDistance += getMaxSpeed() * delta.asSeconds(); } }
void ParticleNode::updateCurrent(sf::Time dt, CommandQueue& commands) { if (mParticles.empty()) return; while (!mParticles.empty() && mParticles.front().lifetime <= sf::Time::Zero) mParticles.pop_front(); for (auto& particle : mParticles) { particle.lifetime -= dt; particle.position += dt.asSeconds() * particle.velocity; particle.rotation += dt.asSeconds() * particle.rotationSpeed; for (const auto& affector : mAffectors) affector(particle, dt); } mNeedsVertexUpdate = true; }
//Update the spaceship void Spaceship::updateCurrent(sf::Time dt) { Entity::updateCurrent(dt); //If we don't have a target, stay where we are if(target == sf::Vector2f(0, 0)) target = getWorldPosition(); sf::Vector2f velocity = getVelocity(); velocity += normalize((target-getWorldPosition()))*deltaV*dt.asSeconds(); if(sqrt(velocity.x*velocity.x+velocity.y*velocity.y) > maxV) velocity = normalize(velocity)*maxV; setVelocity(velocity); if(velocity.x != 0||velocity.y != 0) { float rotation = atan2(velocity.y, velocity.x)*180/3.1415+90; while(rotation > 360) rotation -= 360; setRotation(rotation); } }
void Player::shoot(const sf::Time& elapsedTime) { if (mCooldown > 0) { mCooldown -= elapsedTime.asSeconds(); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && mCooldown <= 0) { mProjectileManager.addProjectile(sf::Vector2f(player.getPosition().x + player.getLocalBounds().width / 2, player.getPosition().y - player.getLocalBounds().height), sf::IntRect(134, 308, 55, 98)); std::cout << player.getPosition().y << std::endl; mCooldown = mDelay; } if (!mProjectileManager.getSpriteVector().empty() && (mProjectileManager.getSpriteVector().back().getPosition().y > window.getSize().y - mProjectileManager.getSpriteVector().back().getLocalBounds().height)) { mProjectileManager.getSpriteVector().pop_back(); } }
void shape_system::gravity(sf::Time tElapsed) { for (int i = 0; i < numberOfShapes; i++) { float dt = tElapsed.asSeconds(); float u = shapesVelocities[i].j; float v = dt*acceleration + u; float s = u*dt + 0.5*acceleration*dt*dt; shapesVelocities[i].j = v; //cout << "v = " << v; sf::Vector2f pos = shapes[i]->getPosition(); pos.y = pos.y + s; shapes[i]->setPosition(pos); } }
void update(sf::Time elapsed) { for (std::size_t i=0; i<m_particles.size(); ++i) { // update the particle lifetime m_particles[i].lifetime -= elapsed; // if the particle is dead, respawn it if (m_particles[i].lifetime <= sf::Time::Zero) resetParticle(i); // update the position of the corresponding vertex m_vertices[i].position += m_particles[i].velocity * elapsed.asSeconds(); // update the alpha (transparency) of the particle according to its lifetime float ratio = m_particles[i].lifetime.asSeconds() / m_lifetime.asSeconds(); m_vertices[i].color.a = static_cast<sf::Uint8>(ratio * 255); } }
std::string MusicPlayer::getReadableMusicOffset(const sf::Time & offset) { int time_s = static_cast<int>(offset.asSeconds()); int hours = time_s / 3600; time_s -= 3600 * hours; int minutes = time_s / 60; time_s -= 60 * minutes; int seconds = time_s; char * c_str = new char[64]; if (hours > 0) sprintf(c_str, "%d:%02d:%02d", hours, minutes, seconds); else sprintf(c_str, "%d:%02d", minutes, seconds); return std::string(c_str); }
void Player::Update(sf::Time deltaTime) { ProcessEvents(); float seconds = deltaTime.asSeconds(); if (rotation_ != 0) { float angle = rotation_ * 250 * seconds; sprite_.rotate(angle); } if (is_moving_) { float angle = sprite_.getRotation() / 180 * M_PI - M_PI / 2; speed_ = sf::Vector2f(Configuration::max_speed_ * std::cos(angle), Configuration::max_speed_ * std::sin(angle)); //speed_ += sf::Vector2f(std::cos(angle), std::sin(angle)) * 100.f * seconds; //ship like movement } sprite_.move(seconds * speed_); rotation_ = 0; //is_moving_ = 0; }
// Add controls to move hero void Hero::listenInputs(sf::Time elapsedTime) { sf::Vector2u position = getPosition(); int speed = 150*elapsedTime.asSeconds(); bool inAction = false; Orientation newOrientation = orientation; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) { cout << "Up" << endl; position.y -= speed; newOrientation = Orientation::North; inAction = true; } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) { cout << "Right" << endl; position.x += speed; newOrientation = Orientation::East; inAction = true; } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) { cout << "Down" << endl; position.y += speed; newOrientation = Orientation::South; inAction = true; } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) { cout << "Left" << endl; position.x -= speed; newOrientation = Orientation::West; inAction = true; } if (newOrientation != orientation) { orientation = newOrientation; sprite.setAnimation(animations[orientation]); } if (inAction) { sprite.play(); } else { sprite.pause(); } setPosition(position); sprite.setPosition(position.x, position.y); }
void World::update(sf::Time dt) { // Scroll the world mWorldView.move(0.f, mScrollSpeed * dt.asSeconds()); // Move the player sidewards (plane scouts follow the main aircraft) sf::Vector2f position = mPlayerAircraft->getPosition(); sf::Vector2f velocity = mPlayerAircraft->getVelocity(); // If player touches borders, flip its X velocity if (position.x <= mWorldBounds.left + 150.f || position.x >= mWorldBounds.left + mWorldBounds.width - 150.f) { velocity.x = -velocity.x; mPlayerAircraft->setVelocity(velocity); } // Apply movements mSceneGraph.update(dt); }
void Player::update(sf::Time deltaTime) { float seconds = deltaTime.asSeconds(); _time_since_last_shoot += deltaTime; if(_rotation != 0) { float angle = _rotation*250*seconds; _sprite.rotate(angle); } if(_is_moving) { float angle = _sprite.getRotation() / 180 * M_PI - M_PI / 2; _impulse += sf::Vector2f(std::cos(angle),std::sin(angle)) * 300.f * seconds; } _sprite.move(seconds * _impulse); }
void GardenSelector::draw(sf::RenderWindow* window, sf::Time delta, int x, int y) { _offset += _multiplier * (delta.asSeconds() * _movement); if(_multiplier == -1 && _offset <= _minOffset ) { _multiplier = 1; } else if(_multiplier == 1 && _offset >= _maxOffset) { _multiplier = -1; } topLeft.setPosition(x-_offset, y-_offset); topRight.setPosition(x+_offset+_width-5,y-_offset); bottomLeft.setPosition(x-_offset,y+_offset+_height-5); bottomRight.setPosition(x+_offset+_width-5,y+_offset+_height-5); window->draw(topLeft); window->draw(topRight); window->draw(bottomLeft); window->draw(bottomRight); }
void GameObject::calculateAngle(sf::Time elapsedTime, sf::Vector2f target, bool neg) { const float maxDelta = this->deltaAngle * elapsedTime.asSeconds(); float newAngle = (float)-(atan2(representation.getPosition().x - target.x, representation.getPosition().y - target.y)); newAngle = ezo::radToDeg(newAngle); if(neg) newAngle -= 180.f; if(newAngle < 0) newAngle += 360; float dAngle = newAngle - angle; if(dAngle > 180) dAngle -= 360; else if(dAngle < -180) dAngle += 360; if(dAngle > maxDelta) dAngle = maxDelta; else if(dAngle < -maxDelta) dAngle = -maxDelta; angle += dAngle; if(angle < 0.f) angle += 360.f; else if(angle > 360.f) angle -= 360.f; representation.setRotation(angle); }
void Saucer::update(sf::Time deltaTime) { float seconds = deltaTime.asSeconds(); //get the nearest object Entity* near = nullptr; float near_distance = 300; for(Entity* entity_ptr : _world.getEntities()) { if(entity_ptr != this and(dynamic_cast<const Meteor*>(entity_ptr) or dynamic_cast<const ShootPlayer*>(entity_ptr))) { float x = getPosition().x - entity_ptr->getPosition().x; float y = getPosition().y - entity_ptr->getPosition().y; float dist = std::sqrt(x*x + y*y); if(dist < near_distance) { near_distance = dist; near = entity_ptr; } } } if(near != nullptr) { sf::Vector2f pos = near->getPosition() - getPosition(); float angle_rad = std::atan2(pos.y,pos.x); _impulse -= sf::Vector2f(std::cos(angle_rad),std::sin(angle_rad)) * 300.f * seconds; } else { sf::Vector2f pos = Configuration::player->getPosition() - getPosition(); float angle_rad = std::atan2(pos.y,pos.x); _impulse += sf::Vector2f(std::cos(angle_rad),std::sin(angle_rad)) * 100.f * seconds; } _sprite.move(seconds * _impulse); }
int DebugModule::update(sf::Time _timeSinceLastFrame){ float oldfps=m_fpsTab[m_fpsTabIndex]; float newFps=1.0f/_timeSinceLastFrame.asSeconds(); m_fpsTab[m_fpsTabIndex]=newFps; m_averageFps=m_averageFps - oldfps + newFps; m_fpsTabIndex= ++m_fpsTabIndex % m_nbFpsSample; //float fps= m_averageFps/30.0f; float fps= newFps; if (fps>999){ fps=999; } char text[11]; sprintf(text,"%.2f fps",fps); m_fpsDisplay.setString(text); //m_graphicsEngine.render_window()->draw(m_fpsDisplay); // m_graphicsEngine.render_window()->display(); return 0; }
void play(int frequency, sf::Time duration) { unsigned constexpr sample_rate{44100}; unsigned const samples_size{static_cast<unsigned>(sample_rate * duration.asSeconds())}; std::vector<sf::Int16> samples(samples_size); unsigned const amplitude{30000}; double const two_pi{2 * 4 * std::atan(1)}; double const increment{static_cast<double>(frequency) / sample_rate}; double x{}; for (unsigned i{}; i < samples_size; ++i) { samples[i] = amplitude * std::sin(x * two_pi); x += increment; } if (not sound_buffer.loadFromSamples(samples.data(), samples_size, 1, sample_rate)) throw "Failed to load buffer"; sound.setBuffer(sound_buffer); sound.play(); }
bool HistoryDialog::onMove(sf::Time dt, sf::Vector2f dest) { if (getPosition() != dest) { sf::Vector2f s = dest - getPosition(); sf::Vector2f dir = unitVector(s); setVelocity(dir * MOVEMENT_SPEED); if (magnitudeOf(getVelocity() * dt.asSeconds()) > magnitudeOf(s)) { setVelocity(0.f, 0.f); setPosition(dest); return true; } return false; } else { setVelocity(0.f, 0.f); return true; } }
void Character::updateMovementPattern(sf::Time dt) { const std::vector<Direction>& directions = Table[mType].directions; if (!directions.empty()) { // Moved long enough in current direction: Change direction if (mTravelledDistance > directions[mDirectionIndex].distance) { mDirectionIndex = (mDirectionIndex + 1) % directions.size(); mTravelledDistance = 0.f; } // Compute velocity from direction float radians = toRadian(directions[mDirectionIndex].angle + 90.f); float vx = getMaxSpeed() * std::cos(radians); float vy = getMaxSpeed() * std::sin(radians); setVelocity(vx, vy); mTravelledDistance += getMaxSpeed() * dt.asSeconds(); } }
void World::update( sf::Time dt ) { mWorldView.move( 0.0f, mScrollSpeed * dt.asSeconds() * mScrollSpeedCompensation ); for ( Aircraft* a : mPlayerAircrafts ) { a->SetVelocity( 0.0f, 0.0f ); } destroyEntitiesOutsideView(); guideMissiles(); while ( !mCommandQueue.isEmpty() ) { mSceneGraph.OnCommand( mCommandQueue.pop(), dt ); } adaptPlayerVelocity(); handleCollisions(); // Remove aircrafts that were destroyed // (World::removeWrecks() only destroys the entities, // not the pointers in mPlayerAircrafts) auto firstToRemove = std::remove_if( mPlayerAircrafts.begin(), mPlayerAircrafts.end(), std::mem_fn( &Aircraft::IsMarkedForRemoval ) ); mPlayerAircrafts.erase( firstToRemove, mPlayerAircrafts.end() ); mSceneGraph.RemoveWrecks(); spawnEnemies(); mSceneGraph.Update( dt, mCommandQueue ); adaptPlayerPosition(); updateSounds(); }
void BodySystem::update(sf::Time deltaTime) { // scale the time step with the deltaTime double dt = TIME_STEP * deltaTime.asSeconds(); // update each body position for (unsigned int i = 0; i < _bodies.size(); i++) { Body* body = _bodies[i]; body->updatePosition(dt); body->updateRender(); } // Recalculate accelerations and update body velocities computeAccelerations(); for (unsigned int i = 0; i < _bodies.size(); i++) { Body* body = _bodies[i]; body->updateVelocity(dt); } }
void Game::update(sf::Time deltaTime) { sf::Vector2f movement(0.f, 0.f); if (isMovingUp) { movement.y -= 1.f; } if (isMovingDown) { movement.y += 1.f; } if (isMovingLeft) { movement.x -= 1.f; } if (isMovingRight) { movement.x += 1.f; } player.move(movement * deltaTime.asSeconds()); }
void GUI::update(sf::Time deltaTime) { #ifdef PONG_BENGINE_TICK_CALC float f_elapsed; if (this->m_lastTime == 0) { f_elapsed = 0; this->m_lastTime = this->m_deltaFPS->getClock().getElapsedTime().asMilliseconds(); } else { float f_nextTime = this->m_deltaFPS->getClock().getElapsedTime().asMilliseconds(); f_elapsed = f_nextTime - this->m_lastTime; this->m_lastTime = f_nextTime; } this->m_context->injectTimePulse(f_elapsed / 1000.0f); #else this->m_context->injectTimePulse(deltaTime.asSeconds()); #endif }