I was using the following code to do it (found the code here, I take no credit for it), but now, after I successfully got the camera to follow the sprite, the code only works when I start the program, if I move the sprite, it's like the center is out of position, re-setting the center didn't work.
#include <SFML/Graphics.hpp>
#define PI 3.1415926535
int WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow
)
{
sf::RenderWindow Window(sf::VideoMode(800, 600, 32), "Zombie Game Alpha");
sf::Image PlayerImage;
sf::Image Background;
Background.LoadFromFile("background.png");
PlayerImage.LoadFromFile("player.png");
sf::Sprite Player(PlayerImage);
sf::Sprite BackgroundS(Background);
sf::Sprite* follow = &Player;
Player.SetPosition(400,300);
sf::View Camera(sf::Vector2f(400.f, 300.f), sf::Vector2f(400.f, 300.f));
sf::Vector2f PPos = Player.GetPosition();
while(Window.IsOpened())
{
sf::Event Event;
while (Window.GetEvent(Event))
{
if (Event.Type == sf::Event::Closed)
Window.Close();
if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape))
Window.Close();
}
float ElapsedTime = Window.GetFrameTime();
if (Window.GetInput().IsKeyDown(sf::Key::W)) Player.Move(0, -425 * ElapsedTime);
if (Window.GetInput().IsKeyDown(sf::Key::S)) Player.Move(0, 425 * ElapsedTime);
if (Window.GetInput().IsKeyDown(sf::Key::A)) Player.Move(-425 * ElapsedTime, 0);
if (Window.GetInput().IsKeyDown(sf::Key::D)) Player.Move(425 * ElapsedTime, 0);
Player.SetCenter(Player.GetSize() / 2.f);
if (Window.GetInput().GetMouseX() <= Player.GetPosition().x) {
Player.SetRotation(((-1* 360 / PI * (atan2(static_cast<double>(Player.GetPosition().y - Window.GetInput().GetMouseY()), static_cast<double>(Player.GetPosition().x - Window.GetInput().GetMouseX()))))/2)+90);
} else {
Player.SetRotation(((-1* 360 / PI *(atan2(static_cast<double>(Player.GetPosition().y - Window.GetInput().GetMouseY()), static_cast<double>(Player.GetPosition().x - Window.GetInput().GetMouseX()))))/2)+90);
}
Window.Clear();
Camera.SetCenter(follow->GetPosition());
Window.SetView(Camera);
Window.Draw(BackgroundS);
Window.Draw(Player);
Window.Display();
}
}