Hey all,
Newbie game development programmer here, trying to figure out why my movement is so choppy. I have implemented the time-base movement that I see from so many examples.
I cant find what I am doing wrong here. Any help would be appreciated!
#include <SFML/Graphics.hpp>
#include "AssetManager.h"
#include "Animator.h"
#include <SFML\Audio.hpp>
#include<SFML\System.hpp>
#include <iostream>
#include <SFML\Network.hpp>
using namespace sf;
int main()
{
RenderWindow window(VideoMode(800,600),"Pong");
window.setFramerateLimit(60);
AssetManager manager;
Sprite player1(AssetManager::GetTexture("pong.png"));
Sprite aiPaddle(AssetManager::GetTexture("pong.png"));
Sprite ball(AssetManager::GetTexture("ball.png"));
player1.setPosition(100,300);
int player1Speed =5;
aiPaddle.setPosition(700,300);
int ai1Speed =5;
ball.setPosition(400,300);
float ballSpeed = 100.f;
player1.setOrigin(player1.getTextureRect().width/2,player1.getTextureRect().height/2);
aiPaddle.setOrigin(aiPaddle.getTextureRect().width/2,aiPaddle.getTextureRect().height/2);
ball.setOrigin(ball.getTextureRect().width/2,ball.getTextureRect().height/2);
Clock clock;
Time timeSinceLastUpdate = Time::Zero;
Time TimePerFrame =seconds(1.f/60.f);
while(window.isOpen())
{
Event ev;
Vector2f movement;
timeSinceLastUpdate += clock.restart();
while(timeSinceLastUpdate > TimePerFrame)
{
while(window.pollEvent(ev))
{
switch(ev.type)
{
case Event::EventType::KeyPressed:
if(ev.key.code == Keyboard::Key::Up)
{
movement.y -= -100.f;
}
if(ev.key.code == Keyboard::Key::Down)
{
movement.y -= 100.f;
}
break;
default:
break;
}
}
timeSinceLastUpdate -=TimePerFrame;
player1.move(movement * timeSinceLastUpdate.asSeconds());
ball.move(ballSpeed*timeSinceLastUpdate.asSeconds(),ballSpeed*timeSinceLastUpdate.asSeconds());
if(aiPaddle.getPosition().y < ball.getPosition().y)
{
aiPaddle.move(0,100*timeSinceLastUpdate.asSeconds());
}
if(aiPaddle.getPosition().y > ball.getPosition().y)
{
aiPaddle.move(0,-100*timeSinceLastUpdate.asSeconds());
}
if(aiPaddle.getGlobalBounds().intersects(ball.getGlobalBounds()))
{
ballSpeed *=-1;
}
if(player1.getGlobalBounds().intersects(ball.getGlobalBounds()))
{
ballSpeed *=-1;
}
}
window.clear(Color::White);
window.draw(player1);
window.draw(aiPaddle);
window.draw(ball);
window.display();
}
}