SpelunkyRemake / Camera.cpp
Camera.cpp
Raw
#include "pch.h"
#include "Camera.h"

Camera::Camera(float width, float height)
	: m_Width { width }
	, m_Height { height }
	, m_LevelBoundaries{ 0, 0, width, height }
	, m_pTarget { nullptr }
	, m_Position { 0, 0 }
	, m_Smoothing { 6.f }
	, m_Offset{ 0, 0 }
{
	
}

Camera::~Camera()
{
	m_pTarget = nullptr;
}

void Camera::SetLevelBoundaries(const Rectf& levelBoundaries)
{
	m_LevelBoundaries = levelBoundaries;
}

void Camera::SetOffset(const Point2f& offset)
{
	m_Offset = offset;
}

Point2f& Camera::GetOffset()
{
	return m_Offset;
}

void Camera::SetSmoothing(float smoothing)
{
	m_Smoothing = smoothing;
}

float& Camera::GetSmoothing()
{
	return m_Smoothing;
}

void Camera::Update(float elapsedSec)
{
	if (m_pTarget != nullptr)
	{
		Point2f target{ m_pTarget->left + m_Offset.x + m_pTarget->width / 2 - m_Width / 2, m_pTarget->bottom + m_Offset.y + m_pTarget->height / 2 - m_Height / 2 };

		//cameraPosition = cameraPosition + (0.2f * elapsedSec) * (targetPosition - cameraPosition);

		if (std::fabs(m_Position.x - target.x) > 3)
			m_Position.x = m_Position.x + (m_Smoothing * elapsedSec) * (target.x - m_Position.x);

		if (std::fabs(m_Position.y - target.y) > 3)
			m_Position.y = m_Position.y + (m_Smoothing * elapsedSec) * (target.y - m_Position.y);

		Clamp(m_Position);
	}
}

void Camera::Translate() const
{
	glTranslatef(-m_Position.x, -m_Position.y, 0);
}

void Camera::SetTarget(const Rectf& target)
{
	m_pTarget = ⌖
}

void Camera::SnapToTarget()
{
	m_Position = Point2f{ m_pTarget->left + m_pTarget->width / 2 - m_Width / 2, m_pTarget->bottom + m_pTarget->height / 2 - m_Height / 2 };
	Clamp(m_Position);
}

void Camera::Clamp(Point2f& bottomLeftPos) const
{
	if (bottomLeftPos.x + m_Width > m_LevelBoundaries.width)
	{
		bottomLeftPos.x = m_LevelBoundaries.width - m_Width;
	}
	else if (bottomLeftPos.x < m_LevelBoundaries.left)
	{
		bottomLeftPos.x = m_LevelBoundaries.left;
	}

	if (bottomLeftPos.y + m_Height > m_LevelBoundaries.height)
	{
		bottomLeftPos.y = m_LevelBoundaries.height - m_Height;
	}
	else if (bottomLeftPos.y < m_LevelBoundaries.bottom)
	{
		bottomLeftPos.y = m_LevelBoundaries.bottom;
	}
}