Exemple #1
0
void game_state::periodic_respawn_info_update()
{
    static sf::Clock clk;

    ///once per second
    float broadcast_every_ms = 100.f;

    if(clk.getElapsedTime().asMicroseconds() / 1000.f < broadcast_every_ms)
        return;

    clk.restart();

    for(auto& i : respawn_requests)
    {
        player play = get_player_from_player_id(i.player_id);

        if(play.id == -1)
            continue;

        float time_elapsed = i.clk.getElapsedTime().asMicroseconds() / 1000.f;

        byte_vector vec;
        vec.push_back(canary_start);
        vec.push_back(message::RESPAWNINFO);
        vec.push_back(time_elapsed);
        vec.push_back(i.time_to_respawn_ms);
        vec.push_back(canary_end);

        udp_send_to(play.sock, vec.ptr, (const sockaddr*)&play.store);
    }
}
Exemple #2
0
void Train::Update(const sf::Input &input) {
    
        static sf::Clock clock;
        static bool waiting = false;

        acceleration = (1/mass) *(push_force - speed * brakes_factor);
        speed += acceleration;
        position.z += speed;

        if (position.z > 900 || position.z < -900) {
            position.z = -position.z;
            //comingSound.SetPosition(this->position);
            comingSound.Play();
            StopGas();
        }
    if (!user_controlled){
        if (position.z < -250 && position.z > -300){
            StopGas();
            Brakes();
        }
        if (IsStopped() && !waiting){
            clock.Reset();
            alarm=false;
            waiting = true;
            printf("\n\n\n                         waiting\n");        

        }
        if (waiting && clock.GetElapsedTime() > waiting_time) {
            Gas();        
            waiting = false;        
            printf("                         timed out\n");
        }
        if (waiting && clock.GetElapsedTime() > waiting_time-4 && !alarm) {
            alarm=true;
                sound.SetBuffer(Buffer);             
                //sound.SetPitch(0.6);
                //sound.SetAttenuation(0.4);
                sound.SetRelativeToListener(true);
                sound.SetPosition(this->position);
                sound.SetMinDistance(100);
                sound.Play();
                //movmetnSound.SetPosition(this->position);
                movmetnSound.Play();
        }


        light->position = sf::Vector3f(-40.900002,10,position.z + 5) ;

        if(camera !=NULL)
            camera->SetOrigin(position.x+8.3,position.y+15,position.z);
    }else {
        if (input.IsKeyDown(sf::Key::Z)) {
            push_force = 0.1f;
        }else if (input.IsKeyDown(sf::Key::X)){
            brakes_factor = 0.05f;
        }
        
    }

}
bool                MultiShootGraphical::update(sf::Clock const& clock)
{
  bool ret = MultiShoot::update(clock);

  _sprite->setPosition(
		       _pos.x,
		       _pos.y
		       );
  if ((clock.getElapsedTime() - _lastUpdate) > _referential)
    {
      if (_incr)
        {
            if (_angle >= 30)
	      _incr = !_incr;
            _angle++;
        }
      else
        {
	  if (_angle <= -30)
                _incr = !_incr;
	  _angle--;
        }
      _sprite->setRotation(_angle);
      _lastUpdate = clock.getElapsedTime();
    }
  return ret;
}
Exemple #4
0
void updatePositions() {
    static float elapsed = 0.0f;
    elapsed += clck.GetElapsedTime();
    clck.Reset();
    
    float delta = elapsed - lastTime;
    lastTime = elapsed;
    
    float speed = 5.0;
    
    if (go_forward) {
        current_location += speed * delta * current_forward;
    }
    if (go_backward) {
        current_location -= speed * delta * current_forward;
    }
    if (go_left) {
        current_location -= speed * delta * current_right;
    }
    if (go_right) {
        current_location += speed * delta * current_right;
    }
    if (go_up) {
        current_location += speed * delta * Up;
    }
    if (go_down) {
        current_location -= speed * delta * Up;
    }
}
Exemple #5
0
void render()
{
	std::stringstream ss;
	std::deque<Point> trails, vertices;
	window->clear();
	window->setView(camera);
	window->draw(bg);
	sf::Color color(sf::Color::Red);
	sf::ConvexShape tail;
	tail.setFillColor(sf::Color(128,0,0,128));
	for(auto& creature:creatures) {
		window->draw(*creature);
	}
	for(auto& f:food) {
		fToken->setPosition(f);
		window->draw(*fToken);
	}
	ss.str("");
	ss << "Generation: " << gen;
	text->setPosition(10,10);
	text->setString(ss.str());
	window->setView(window->getDefaultView());
	window->draw(*text);
	if(frameclock.getElapsedTime().asMilliseconds()>0) {
		ss.str("");
		ss << "FPS: " << (int)1000.f/frameclock.restart().asMilliseconds();
		text->setString(ss.str());
		text->move(0,text->getLocalBounds().height);
		window->draw(*text);
	}

	window->display();
}
void display(sf::RenderWindow *window)
{
	if (frames==0)
		sfclock.restart();
	
	// Draw using SFML
	window->pushGLStates();
	window->resetGLStates();
	//insert SFML drawing code here (any part you are using that does not involve opengl code)
	window->popGLStates();

	//set up the background color of the window. This does NOT clear the window. Right now it is (0,0,0) which is black
	glClearColor(0,0,0,0);
	glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); //this command actually clears the window.
	glEnable(GL_DEPTH_TEST);
	v.draw(raytrace); //simply delegate to our view class that has all the data and does all the rendering

	if (frames>500)
	{
		sf::Time t = sfclock.getElapsedTime();
		frame_rate = frames/t.asSeconds();
		frames = 0;
	}
	else
	{
		frames++;
	}
	stringstream str;

	
	// Finally, display the rendered frame on screen
	window->display();
//	cout << "Rendering" << endl;
}
Exemple #7
0
void game_state::broadcast_ping_data()
{
    static sf::Clock clk;
    const float send_time_ms = 1000;

    if(clk.getElapsedTime().asMicroseconds() / 1000.f < send_time_ms)
        return;

    clk.restart();

    byte_vector vec;
    vec.push_back(canary_start);
    vec.push_back(message::PING_DATA);

    int32_t num = player_list.size();

    vec.push_back<int32_t>(num);

    for(int i=0; i<player_list.size(); i++)
    {
        ///playerid int32_t
        ///playerping float

        vec.push_back<int32_t>(player_list[i].id);
        vec.push_back<float>(player_list[i].ping_ms);
    }

    vec.push_back(canary_end);

    int none = -1;

    broadcast(vec.ptr, none);
}
Exemple #8
0
void RenderSceneCB()
{
	glClear(GL_COLOR_BUFFER_BIT);

	static sf::Clock a_timer;
	static bool a_first_time = true;
	if (a_first_time) {
		a_first_time = false;
		a_timer.restart ();
	}
	float dt = a_timer.getElapsedTime ().asSeconds ();
	a_timer.restart ();
	// ֲ�גמה ג פאיכ פןס ט הוכ�עא ׂ
	//static FILE *out = fopen ((prefix_path + "inf/out.txt").c_str (), "w");
	//fprintf (out, "%4d %10g\n", int(1/dt), dt);
	if (in.kb.escape.pressed_now) {
		exit (0);
	}
	core.update (dt);
	core.render ();

	core.m_renderer.draw_everything ();

    glutSwapBuffers();
}
Exemple #9
0
void game_state::periodic_team_broadcast()
{
    static sf::Clock clk;

    ///once per second
    float broadcast_every_ms = 1000.f;

    if(clk.getElapsedTime().asMicroseconds() / 1000.f < broadcast_every_ms)
        return;

    clk.restart();

    for(auto& i : player_list)
    {
        ///network
        byte_vector vec;
        vec.push_back(canary_start);
        vec.push_back(message::TEAMASSIGNMENT);
        vec.push_back<int32_t>(i.id);
        vec.push_back<int32_t>(i.team);
        vec.push_back(canary_end);

        //printf("Team ass %i team player %i\n", i.team, i.id);

        int no_player = -1;

        broadcast(vec.ptr, no_player);
    }
}
Exemple #10
0
void display(sf::RenderWindow *window)
{
	if (frames==0)
		sfclock.restart();

	window->pushGLStates();
	window->resetGLStates();
	
	window->popGLStates();

	glClearColor(1.0f,1.0f,1.0f,1.0f);
	glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); 
	glEnable(GL_DEPTH_TEST);
	v.draw(); 

	if (frames>500)
	{
		sf::Time t = sfclock.getElapsedTime();
		frame_rate = frames/t.asSeconds();
		frames = 0;
	}
	else
	{
		frames++;
	}
	stringstream str;

	str << "Frame rate " << frame_rate;

	//drawText(window,str.str(),window->getSize().x-200,50);

	window->display();

}
Exemple #11
0
//Process the player's inputs WASD and mouse buttons.
void Player::update(sf::RenderWindow &window, vector <Bullet *> &bullets, sf::Sound &laser, sf::FloatRect bounds, sf::Clock &fireRateTimer) {
	if (sf::Keyboard::isKeyPressed(sf::Keyboard::W) && this->getPosition().y > bounds.top) {
		this->velocity.y -= this->acceleration;
	}
	else if (sf::Keyboard::isKeyPressed(sf::Keyboard::D) && this->getPosition().x < bounds.width) {
		this->velocity.x += this->acceleration;
	}
	else if (sf::Keyboard::isKeyPressed(sf::Keyboard::S) && this->getPosition().y < bounds.height) {
		this->velocity.y += this->acceleration;
	}
	else if (sf::Keyboard::isKeyPressed(sf::Keyboard::A) && this->getPosition().x > bounds.left) {
		this->velocity.x -= this->acceleration;
	}
	if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
		if (fireRateTimer.getElapsedTime().asSeconds() >= this->rateOfFire && this->alive) {
			this->shoot(window, bullets, laser);
			fireRateTimer.restart();
		}
	}
	if (sf::Mouse::isButtonPressed(sf::Mouse::Right)) {
		this->activateShield(window);
	}
	if (this->shieldCharge >= 200) {
		this->shieldCharge = 200;
	}
}
Exemple #12
0
float GameTime::getTime()
{
	static sf::Clock gameTime;

	sf::Time time = gameTime.getElapsedTime();
	return (time.asSeconds());
}
Exemple #13
0
/**
Représente un tour de boucle, ici ce trouve
toutes la gestion du jeu
@return true si pas de collision
*/
bool Game::gameLoop(sf::Clock & clock)
{
	affichage();

	sf::Event event;
	recuperationEntree(event);

	//valeur qui sera retrournée a la fin de la GameLoop
	bool etat = m_map.collisionBloc(m_vaisseauJoueur, m_tirs, m_distanceParcouru);

	actualisationInfoJoueur();

	//actualisation du temps
	m_tempsPasse = clock.getElapsedTime().asMicroseconds() / 20000.;
	clock.restart().asMicroseconds();
	m_tempsPasse /= m_coefRalentissement;

	//calcul de la trajectoire puis la vitesse sera calculé a part
	traitement(event, m_tempsPasse);

	gestionScrolling(m_tempsPasse);

	//deplacement des tirs
	gererTirs(m_tempsPasse);

	rechargeDesVaisseaux(m_tempsPasse);

	actualiserAnimation(m_tempsPasse);

	//comp 1
	float tempsMaxComp = m_vaisseauJoueur.getCompetence(2)->getTempsDeRechargeMax();
	float tempsActuelComp = m_vaisseauJoueur.getCompetence(2)->getTempsDeRechargeActuel();
	float rapportComp1 = 1;

	if (tempsActuelComp != tempsMaxComp)
		rapportComp1 = ((tempsMaxComp - tempsActuelComp) / tempsMaxComp);

	//comp 2
	tempsMaxComp = m_vaisseauJoueur.getCompetence(3)->getTempsDeRechargeMax();
	tempsActuelComp = m_vaisseauJoueur.getCompetence(3)->getTempsDeRechargeActuel();
	float rapportComp2 = tempsActuelComp / tempsMaxComp;

	//comp 3
	tempsMaxComp = m_vaisseauJoueur.getCompetence(1)->getTempsDeRechargeMax();
	tempsActuelComp = m_vaisseauJoueur.getCompetence(1)->getTempsDeRechargeActuel();
	float rapportComp3 = 1;
	if (m_vaisseauJoueur.getCompetence(1)->estActive())
	{
		rapportComp3 = tempsActuelComp / tempsMaxComp;
	}
	else if (tempsActuelComp != tempsMaxComp)
	{
		rapportComp3 = (tempsMaxComp - tempsActuelComp) / tempsMaxComp;
	}

	tableauDeBord.actualiserAnimationAvecCompetence(rapportComp1, rapportComp2, rapportComp3, m_vaisseauJoueur.getCompetence(1)->estActive());

	return etat;
}
Exemple #14
0
 void                    CheckForEnemyCreate()       { if(enemy_create.getElapsedTime() > sf::milliseconds(500))
                                                         {
                                                             int willThereBeEnemy = rand()%10;
                                                             if(willThereBeEnemy >= 4)
                                                                 EnemyGroup.resize(EnemyGroup.size()+1);
                                                             enemy_create.restart();
                                                         }
                                                     }
	void update() {
		delta_t = clock.getElapsedTime();
		if (delta_t<max_frame_time)
			sf::sleep(max_frame_time - delta_t);
		delta_t = clock.restart();
		currentFPS = 1 / delta_t.asSeconds();
		delta_t *= time_factor;
	}
 // called every couple of lines. Use it to check for events
 void Turing_StdlibSFML_PeriodicCallback() {
     // check every quarter of a second. This does make input delayed.
     // It only stops the system from deeming us unresponsive
     if(WinMan && eventClock.GetElapsedTime() > 0.5) {
         WinMan->surface();
         eventClock.Reset();
     }
 }
void Game_Manager::draw()
{
    static sf::Clock render_clock;
    if (render_clock.getElapsedTime().asMilliseconds() < 2) {
        return;
    }
    render_clock.restart();
    m_app->clear();

    if (is_tree)
    {
        tree_background.draw(0, 0);
        skill_button[0].draw();
        skill_button[3].draw();
        skill_button[4].draw();
        skill_button[5].draw();
        skill_button[6].draw();
        skill_button[7].draw();
        skill_button[8].draw();

        energy_text.refill(to_string(myPlayer.getEnergy()));
        energy_text.draw(0, 0, 55);
        if (skill_level < 3)
        {
            empty.draw(0, 500);
        }
        else if (skill_level >= 3)
        {
            empty.draw(0, 700);
        }
    }
    else if (is_menu_visible)
    {
        menu1.draw();
    }
    else
    {
        m_app->setView(m_view2);
        //Changes on the world
        world_sprite.draw(0, 0);
        afficherMapobjet();

        m_app->setView(m_view1);

        //Changes on the HUD, player
        myPlayer.draw();
        light_bar_background.draw(m_screen_x - light_bar_background.get_w(), 0);
        light_bar.draw(m_screen_x + 28 - light_bar_background.get_w(), 40);
        light_bar_grad.draw(m_screen_x - light_bar_background.get_w(), 0);
        energy_text.refill(to_string(myPlayer.getEnergy() ) );
        energy_text.draw(0, 0, 55);
        difficulter_text.refill(to_string(_difficulter-1));
        difficulter_text.draw(0, 100, 55);
    }
    m_app->display();
}
Exemple #18
0
unsigned long getDelta()
{
  static sf::Clock clock; // starts the clock
  static unsigned long last, now = clock.getElapsedTime().asMilliseconds();

  last = now;
  now = clock.getElapsedTime().asMilliseconds();

  return (now-last);
}
Exemple #19
0
void Boss::comportamiento(Personaje* s, Mapa *map){
    
   
    if(clock_comportamiento.getElapsedTime().asMilliseconds()>4000)      
    { srand(time(NULL));
        int num = rand()%2;
    actitud=num;
    clock_comportamiento.restart();         
    }
    if(actitud==0){
    if(detectada && !muriendo){
        if(!rapido){ this->set_speed(fast); rapido = true;}
        int distancia = this->pos->getX() - s->getPosicion()->getX();
        if(distancia > 0){ 
            if(distancia < 15){ this->attack(s); }
            else{ this->atacando = false; this->orientacion = 1;}
        }
        else{
            if(distancia > -15){ this->attack(s); }
            else{ this->atacando = false; this->orientacion = 0;}
        }
        
        int aux = this->colision_Boss(map);
        if(!(aux == 0 && this->orientacion == 0 || aux == 1 && this->orientacion == 1)){
            this->move();
        }
        else{
            this->pos->setInicial();
            clock_posicion.restart();
        }
    }}
    
    if(actitud==1){
       
     if(detectada){
         this->getPosition()->setInicial();
          clock_posicion.restart();
        //if(this->clock_quieto.getElapsedTime().asSeconds() > 0.5){ this->quieto = false; }
        if(!rapido){ this->set_speed(fast); rapido = true;}
        int distancia = this->pos->getX() - s->getPosicion()->getX();
        if(distancia > 0){
            this->orientacion = 1; 
            this->attack2(s);
            //if(this->clock_quieto.getElapsedTime().asSeconds() > 0.1){ this->orientacion = 0; }
        }
        else{
            this->orientacion = 0; 
            this->attack2(s);
            //if(this->clock_quieto.getElapsedTime().asSeconds() > 0.1){ this->orientacion = 1; }
        }
        //this->move();
     }
    }
    
}
void Engine::playerControl(Player *player, float &delta_time, bool pressed)
{
    sf::Vector2f vectors;
    static sf::Vector2f wektor;
    static sf::Clock clockCrash;
    static sf::Time timerCrash;

    if(player->lifes < -1)
    {
        game_over.setString(stringGameOver+toString(player->score));
        game_over.setPosition((windowSize.x-game_over.getGlobalBounds().width)/2, windowSize.y/2);
        gameOver = true;
    }

    if(crash)
    {
        player->ship.setOutlineColor(red);
        timerCrash = clockCrash.getElapsedTime();

        if(player->lifes >= 0)
            info.setString(stringInfo+toString(player->lifes));

        if(timerCrash >= sf::seconds(5))
        {
            crash = false;
            player->ship.setOutlineColor(cyan);
            clockCrash.restart();
            player->lifes -= 1;
        }
    }

    if(player->ship.getPosition().y < - 3.f)
        player->ship.setPosition(player->ship.getPosition().x, windowSize.y + 3.f);

    else if(player->ship.getPosition().y > windowSize.y + 3.f)
        player->ship.setPosition(player->ship.getPosition().x, - 3.f);

    else if(player->ship.getPosition().x > windowSize.x + 3.f)
        player->ship.setPosition(-3.f, player->ship.getPosition().y);

    else if(player->ship.getPosition().x < - 3.f)
        player->ship.setPosition(windowSize.x + 3.f, player->ship.getPosition().y);

    if(pressed)
    {
        wektor.x = std::sin((player->ship.getRotation()*M_PI) / 180.0f);
        wektor.y = -std::cos((player->ship.getRotation()*M_PI) / 180.0f);
    }

    vectors.x = wektor.x * player->velocity * delta_time;
    vectors.y = wektor.y * player->velocity * delta_time;

    player->ship.move(vectors);
}
Exemple #21
0
  void draw(sf::Clock &Clock)
  {	

	// Apply move direction
	if (dir == 0)
	  glRotatef(Clock.GetElapsedTime() * 90, 1.f, 0.f, 0.f);
	else if (dir == 1)
	  glRotatef(Clock.GetElapsedTime() * -90, 1.f, 0.f, 0.f);
	else if (dir == 2)
	  glRotatef(Clock.GetElapsedTime() * 90, 0.f, 1.f, 0.f);
	else if (dir == 3)
	  glRotatef(Clock.GetElapsedTime() * -90, 0.f, 1.f, 0.f);

        // Draw a cube
        glBegin(GL_QUADS);

	glColor3f(0.0f, 1.0f, 0.0f);
	glVertex3f(-50.f, -50.f, -50.f);
	glVertex3f(-50.f,  50.f, -50.f);
	glVertex3f( 50.f,  50.f, -50.f);
	glVertex3f( 50.f, -50.f, -50.f);
	
	glColor3f(0.0f, 0.0f, 1.0f);
	glVertex3f(-50.f, -50.f, 50.f);
	glVertex3f(-50.f,  50.f, 50.f);
	glVertex3f( 50.f,  50.f, 50.f);
	glVertex3f( 50.f, -50.f, 50.f);
	
	glColor3f(1.0f, 0.0f, 0.0f);
	glVertex3f(-50.f, -50.f, -50.f);
	glVertex3f(-50.f,  50.f, -50.f);
	glVertex3f(-50.f,  50.f,  50.f);
	glVertex3f(-50.f, -50.f,  50.f);
	
	glColor3f(1.0f, 1.0f, 0.0f);
	glVertex3f(50.f, -50.f, -50.f);
	glVertex3f(50.f,  50.f, -50.f);
	glVertex3f(50.f,  50.f,  50.f);
	glVertex3f(50.f, -50.f,  50.f);
	
	glColor3f(0.0f, 1.0f, 1.0f);
	glVertex3f(-50.f, -50.f,  50.f);
	glVertex3f(-50.f, -50.f, -50.f);
	glVertex3f( 50.f, -50.f, -50.f);
	glVertex3f( 50.f, -50.f,  50.f);
	
	glColor3f(1.0f, 0.0f, 1.0f);
	glVertex3f(-50.f, 50.f,  50.f);
	glVertex3f(-50.f, 50.f, -50.f);
	glVertex3f( 50.f, 50.f, -50.f);
	glVertex3f( 50.f, 50.f,  50.f);
	
        glEnd();
  }
Exemple #22
0
void MenuStanje::Input()
{
    static sf::Clock clock;
    float deltaT=clock.restart().asSeconds();
	
	if(tranzicija==T_NEMA)
	{
		if(stanje==GLAVNI_MENU)
		{
			if(misOtpusten==true)
			{
				if(startGumb.odabran==true)
				{						
					stanje=NIVO_ODABIR;
				}
				if(oigriGumb.odabran==true)
				{					
					stanje=O_IGRI;
				}
				if(izlazGumb.odabran==true)
				{
					tranzicija=T_FADEOUT;			
				}
				misOtpusten=false;
			}
		}
		if(stanje==NIVO_ODABIR)
		if(misOtpusten==true)
		{
			if(natragGumb.odabran==true)
				stanje=GLAVNI_MENU;
			for(int i=0; i<nivoi.size(); i++)
			{
				if(nivoi[i].gumb.odabran==true)
				{
					RenderLoading();
					nivo_datoteka=nivoi[i].datoteka;
					nivo_datoteka_g=nivoi[i].datoteka_g;
					nivo_trenutni=i;
					igra->SetState(new GameState(), true);
					break;
				}
			}
			misOtpusten=false;
		}
		if(stanje==O_IGRI)
		if(misOtpusten==true)
		{
			if(natragGumb.odabran==true)
				stanje=GLAVNI_MENU;
		}
	}
	misOtpusten=false;	
}
Exemple #23
0
int main(int argc, char* argv[])
{


    char filename[] = "doom-e1m1.mid";
      RtMidiOut *midiout = new RtMidiOut();
    string portName;
    
    nPorts = midiout->getPortCount();
 
    if(argc < 2)    {
        if ( nPorts == 0 )     cout << "No ports available!\n";
        for ( unsigned int i=0; i<nPorts; i++ ) {
            try { portName = midiout->getPortName(i);    }
             catch (RtError &error) {error.printMessage(); }
            cout << "  Output Port #" << i+1 << ": " << portName << '\n';
        }
    }else{
        int port = atoi(argv[1]);
          //midiout->openPort( port );

        cout << "Opening midi" << endl;    
        char *filef = argv[2];
        if(argc == 3)
            parser.Open(filef);
        else
            parser.Open(filename);
    
        tickspersecond = ( (parser.bpm / 30.0) * ( parser.tpb));
        cout << " Ticks per second: " << tickspersecond << endl;
        
        (void) signal(SIGINT, finish);
        tickcount = 0;

        Sequencer sequencers[parser.numtracks];
        SequencerRunning = true;
        for(int i=0;i<parser.numtracks;i++)    {
            sequencers[i].StartSequencer(i, &parser.mididata.tracks[i], port);
            sf::Sleep(0.01f);
        }
        sf::Sleep(1);
        timer.Reset();
        while(run)    {
            timecount = timer.GetElapsedTime();
            tickcount += timecount * tickspersecond;
            timer.Reset();
            //sf::Sleep(0.0001f);
        }
    }
    delete midiout;    
    finish(0);
    return 0;
}
Exemple #24
0
void Car::updateGhosts() {
    static sf::Clock clock = sf::Clock();
    
    sf::Time time = clock.getElapsedTime();
    
    sf::Vector2f lastLocation = this->mLastLocation;
    if (this->mCarGhostDrawables.size() > 0) {
        lastLocation = this->mCarGhostDrawables.back().ghost.getPosition();
    }
    
    // add new ghost
    float ghostDistance = length(this->mCurrentLocation - lastLocation);
    if (ghostDistance >= Car::MAX_GHOSTS_DISTANCE && this->mVelocity > 0.0f) {
        sf::RectangleShape ghost(sf::Vector2f(Car::CAR_WIDTH, Car::CAR_HEIGHT));
        ghost.setOrigin(Car::CAR_WIDTH / 2.0f, Car::CAR_HEIGHT / 2.0f);
        
        sf::Vector2f dir = normalize(this->mCurrentDirection);
        ghost.setPosition(this->mCurrentLocation); // - (dir * (Car::MAX_GHOSTS_DISTANCE + 20.0f)));
        ghost.setRotation(RAD_TO_DEG(heading(dir)));
        
        ghost.setFillColor(this->mCarDrawable.getFillColor());
        
        this->mCarGhostDrawables.push_back(Ghost(ghost, time.asMilliseconds()));
        
        if (this->mCarGhostDrawables.size() >= Car::MAX_GHOSTS) {
            this->mCarGhostDrawables.erase(this->mCarGhostDrawables.begin());
        }
    }
    
    // do we need to remove some ghosts?
    std::list<Ghost>::iterator it = this->mCarGhostDrawables.begin();
    while (it != this->mCarGhostDrawables.end()) {
        if ((time.asMilliseconds() - (*it).age) >= Car::MAX_GHOSTS_AGE) {
            it = this->mCarGhostDrawables.erase(it);
        } else {
            ++it;
        }
    }
       
    // adjust alphas
    int i = this->mCarGhostDrawables.size()+1;
    //float steps = (80.0f - (80.0f * (MAX_VELOCITY / this->mVelocity))) / static_cast<float>(i);
    float steps = 80.0f / static_cast<float>(i);
    sf::Color color = this->mCarDrawable.getFillColor();
    for (std::list<Ghost>::reverse_iterator it = this->mCarGhostDrawables.rbegin(); it != this->mCarGhostDrawables.rend(); ++it) {
        color.a = steps * i--;
        (*it).ghost.setFillColor(color);
    }

}
Exemple #25
0
int main(int argc, const char **argv)
{	
	init(argc, argv);
	loadAssets();
	while (window.IsOpened()) {
		clockdiff = clck.GetElapsedTime();
		elapsed += clockdiff;
		clck.Reset();
		inputFn();
		renderFn();
		window.Display();
	}
	return 0;
}
Exemple #26
0
float framesPerSecond(sf::Clock & clock) {
    frames_count++;
    if (frames_count >= MAX_FRAME_SAMPLES) {
        fps = ((float)frames_count / (float)clock.getElapsedTime().asMilliseconds()) * 1000;
        clock.restart();
        frames_count = 0;
    }
    //if (clock.getElapsedTime().asMilliseconds() >= 1000) {
    //    clock.restart();
    //    fps = count;
    //    count = 0;
    //}
    fflush(stdout);
    return fps;
}
Exemple #27
0
std::string Comunicare :: interactTastatura(sf::RenderWindow &fereastra, sf::Event &ev)
{
    static sf::Clock timpActiune;
    float timpRamas = timpActiune.getElapsedTime().asSeconds();
    if(ev.type == sf::Event::TextEntered)
        text_dl_tastatura += (char)ev.text.unicode;
    if(sf::Keyboard::isKeyPressed(sf::Keyboard::Return))
        if(timpRamas > 0.1)
        {
            timpActiune.restart();
            text_dl_tastatura += '\n';
        }
    if(sf::Keyboard::isKeyPressed(sf::Keyboard::BackSpace) && !text_dl_tastatura.empty())
        text_dl_tastatura.erase(text_dl_tastatura.size()-1,1);
}
Exemple #28
0
	void setShaderVariables(GLuint bubbleShaderProg)
	{
		GLfloat projMatrix[16];
		GLfloat viewMatrix[16];
		glGetFloatv(GL_PROJECTION_MATRIX, projMatrix);
		glGetFloatv(GL_MODELVIEW_MATRIX, viewMatrix);

		if(GL20Support)
		{
			glUniform1f(glGetUniformLocation(bubbleShaderProg, "elapsedTime"), motionClock.GetElapsedTime());
			glUniform1f(glGetUniformLocation(bubbleShaderProg, "near"), _near);
			glUniform1f(glGetUniformLocation(bubbleShaderProg, "far"), _far);
			glUniform1f(glGetUniformLocation(bubbleShaderProg, "fov"), fov);
			glUniform1f(glGetUniformLocation(bubbleShaderProg, "cursorScrollAmount"), cursorScrollAmount);
			glUniform2f(glGetUniformLocation(bubbleShaderProg, "resolution"), RES_WIDTH, RES_HEIGHT);
			glUniform3f(glGetUniformLocation(bubbleShaderProg, "modelCenter"),  center[0], center[1], center[2]);
			glUniform3f(glGetUniformLocation(bubbleShaderProg, "cameraPos"),  cameraPos[0], cameraPos[1], cameraPos[2]);
			glUniform3f(glGetUniformLocation(bubbleShaderProg, "lookAtPos"),  lookAtPos[0], lookAtPos[1], lookAtPos[2]);
			glUniform3f(glGetUniformLocation(bubbleShaderProg, "cameraUp"),  cameraUp[0], cameraUp[1], cameraUp[2]);
			glUniformMatrix4fv(glGetUniformLocation(bubbleShaderProg, "projMatrix"), 1, false, projMatrix);
			glUniformMatrix4fv(glGetUniformLocation(bubbleShaderProg, "viewMatrix"), 1, false, viewMatrix);
			glUniform2f(glGetUniformLocation(bubbleShaderProg, "lightPos"), lightPos[0], lightPos[1]);
			glUniform2f(glGetUniformLocation(bubbleShaderProg, "cursorAbsolutePos"), cursorAbsolutePos[0], cursorAbsolutePos[1]);
			glUniform2f(glGetUniformLocation(bubbleShaderProg, "cursorDragAmount"), cursorDragAmount[0], cursorDragAmount[1]);
			glUniform2f(glGetUniformLocation(bubbleShaderProg, "lastClickPos"), lastClickPos[0], lastClickPos[1]);
			glUniform2f(glGetUniformLocation(bubbleShaderProg, "lastFrameDragPos"), lastFrameDragPos[0], lastFrameDragPos[1]);
			glUniform1i(glGetUniformLocation(bubbleShaderProg, "mouseButtonDown"), mouseButtonDown);
		} else {
			glUniform1fARB(glGetUniformLocationARB(bubbleShaderProg, "elapsedTime"), Clock.GetElapsedTime());
			glUniform1fARB(glGetUniformLocationARB(bubbleShaderProg, "near"), _near);
			glUniform1fARB(glGetUniformLocationARB(bubbleShaderProg, "far"), _far);
			glUniform1fARB(glGetUniformLocationARB(bubbleShaderProg, "fov"), fov);
			glUniform1fARB(glGetUniformLocationARB(bubbleShaderProg, "cursorScrollAmount"), cursorScrollAmount);
			glUniform2fARB(glGetUniformLocationARB(bubbleShaderProg, "resolution"), RES_WIDTH, RES_HEIGHT);
			glUniform3fARB(glGetUniformLocationARB(bubbleShaderProg, "modelCenter"),  center[0], center[1], center[2]);
			glUniform3fARB(glGetUniformLocationARB(bubbleShaderProg, "cameraPos"),  cameraPos[0], cameraPos[1], cameraPos[2]);
			glUniform3fARB(glGetUniformLocationARB(bubbleShaderProg, "lookAtPos"),  lookAtPos[0], lookAtPos[1], lookAtPos[2]);
			glUniform3fARB(glGetUniformLocationARB(bubbleShaderProg, "cameraUp"),  cameraUp[0], cameraUp[1], cameraUp[2]);
			glUniformMatrix4fvARB(glGetUniformLocationARB(bubbleShaderProg, "projMatrix"), 1, false, projMatrix);
			glUniformMatrix4fvARB(glGetUniformLocationARB(bubbleShaderProg, "viewMatrix"), 1, false, viewMatrix);
			glUniform2fARB(glGetUniformLocationARB(bubbleShaderProg, "cursorAbsolutePos"), cursorAbsolutePos[0], cursorAbsolutePos[1]);
			glUniform2fARB(glGetUniformLocationARB(bubbleShaderProg, "cursorDragAmount"), cursorDragAmount[0], cursorDragAmount[1]);
			glUniform2fARB(glGetUniformLocationARB(bubbleShaderProg, "lastClickPos"), lastClickPos[0], lastClickPos[1]);
			glUniform2fARB(glGetUniformLocationARB(bubbleShaderProg, "lastFrameDragPos"), lastFrameDragPos[0], lastFrameDragPos[1]);
			glUniform1iARB(glGetUniformLocationARB(bubbleShaderProg, "mouseButtonDown"), mouseButtonDown);

		}
	}
Exemple #29
0
    float step()
    {
        ++mySteps;

        float time(myClock.getElapsedTime().asSeconds());

        if (time >= 1.f)
        {
            std::ostringstream str; str.precision(4);
            str<<mySteps/time;
            setString(str.str());
            mySteps = 0;
            myClock.restart();
        }
        return time;
    }
Exemple #30
0
	void Present() {
		window_->display();
		//sleep enough time
		sf::Time t = tclock.restart();
		if(t.asMilliseconds() < 1000.0 / 60.0)
			sf::sleep(sf::milliseconds(1000.0 / 60.0) - t);
	}