A
A
Afafks1231321321652020-01-26 17:51:04
C++ / C#
Afafks123132132165, 2020-01-26 17:51:04

Why is the c++ game slow?

Hello.
I am writing a game in c++ sfml. I do everything according to the lesson. I launch the game on my computer, it runs slowly or quickly. The player is either slow or twitching sharply. Please help me figure it out.

#include <SFML/Graphics.hpp>
 
using namespace sf;
int main()
{
  RenderWindow window(VideoMode(480,320), "Test");
  Texture t;
  t.loadFromFile("Fang.png");
  float currentFrame = 0;
  Sprite s;
  s.setTexture(t);
  s.setTextureRect(IntRect(0,244,40,50));
  s.setPosition(50,100);
  Clock clock;
  
  while(window.isOpen())
  {
    float time = clock.getElapsedTime().asMicroseconds();
    clock.restart();
    time = time/800;
    Event event;
    while(window.pollEvent(event))
    {
      if(event.type == Event::Closed)
      {
        window.close();
      }
    if(Keyboard::isKeyPressed(Keyboard::Left))
    {
      s.move(-0.01*time,0);
      currentFrame +=0.005*time;
      if(currentFrame > 6)
      {
        currentFrame-=6;
      }
      s.setTextureRect(IntRect(40*int(currentFrame)+40,244,-40,50));
    }
    if(Keyboard::isKeyPressed(Keyboard::Right))
    {
      s.move(0.01*time,0);
      currentFrame +=0.005*time;
      if(currentFrame > 6)
      {
        currentFrame-=6;
      }
      s.setTextureRect(IntRect(40*int(currentFrame),244,40,50));
    }
    if(Keyboard::isKeyPressed(Keyboard::Up))
    {
      s.move(0,-0.1*time);
    }
    }
    window.clear();
    window.draw(s);
    window.display();
  }
  return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dollar, 2020-01-27
@dollar

Perhaps there is some extra time between getting the time and resetting the timer that you don't account for?
Try replacing this:

float time = clock.getElapsedTime().asMicroseconds();
clock.restart();

On this:
float time = clock.restart().asMicroseconds();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question