Hello,
so i've been trying to create a smooth and nice camera with the sf::View in sfml. Currently, i have a camera which moves when the Player leaves a specific area (the Player can move inside a box but if he gets out of it the camera will follow him). It is working as i wished, but its not smooth. The code is:
#include "Camera.h"
Camera::Camera()
{
view.setSize(384, 216);
view.setCenter(0, 0);
}
void Camera::Render(RenderWindow &window)
{
window.setView(view);
}
void Camera::Update(FloatRect object, Vector2f objectVelocity)
{
if (object.left + object.width > view.getCenter().x + radius)
{
if (viewX < objectVelocity.x)
viewX = viewX + camSpeed;
}
else if (object.left < view.getCenter().x - radius)
{
if (viewX > objectVelocity.x)
viewX = viewX - camSpeed;
}
else
{
if (viewX < -camSpeed * 0.9)
{
viewX = viewY + camSpeed * 0.9;
}
else if (viewX > camSpeed * 0.9)
{
viewX = viewY - camSpeed * 0.9;
}
else
viewX = 0;
}
if (object.top + object.height > view.getCenter().y + radius / 1.5)
{
if (viewY < objectVelocity.y)
viewY = viewY + camSpeed;
}
else if (object.top < view.getCenter().y - radius / 1.5)
{
if (viewY > objectVelocity.y)
viewY = viewY - camSpeed;
}
else
{
if (viewY < -camSpeed * 0.9)
{
viewY = viewY + camSpeed * 0.9;
}
else if (viewY > camSpeed * 0.9)
{
viewY = viewY - camSpeed * 0.9;
}
else
viewY = 0;
}
view.move(viewX, viewY);
}
in the cpp file and the h file:
#include <SFML\Graphics.hpp>
#include <iostream>
using namespace sf;
class Camera
{
public:
Camera();
~Camera();
void Render(RenderWindow &window);
void Update(FloatRect object, Vector2f objectVelocity);
private:
View view;
int radius = 60;
float viewY = 0, viewX = 0;
float camSpeed = 2;
};
The Problem seems to be the camera moving a bit faster than the player, then camera passes the player and slows down, this happening inside a fraction of a second causes the camera to look stuttering. But I dont know how to solve this Problem.