2dkg/2dgk_6/2dgk_6/KCircle.cpp

79 lines
2.2 KiB
C++

#include "KCircle.h"
#include <utility>
#include <vector>
#include "Constants.h"
#include "Utils.h"
namespace KapitanGame {
std::atomic<int> KCircle::IdCounter{ 0 };
KCircle::KCircle(const KVector2D& position, const KVector2D& velocity, const float& radius, const KTexture& texture) : Id(++IdCounter),
Position(position),
Velocity(velocity),
Radius(radius),
Texture(texture) {
}
void KCircle::CollisionDetectionStep(const std::vector<KCircle>& circles, const bool& shouldSeparate, const bool& shouldReflect) {
for (auto& other : circles) {
if (other.Id == Id) continue;
if (IsCollision(other)) {
auto separationVector = GetSeparationVector(other);
if (shouldSeparate)
Position += separationVector;
if (shouldReflect)
{
separationVector.Normalize();
Velocity = Velocity.Reflect(separationVector);
}
}
}
}
void KCircle::MovementStep(const float& timeStep) {
//Velocity.Normalize();
//Velocity *= 100;
Position += Velocity * timeStep;
}
bool KCircle::IsCollision(const KCircle& other) const {
return (Position - other.Position).Length() < Radius + other.Radius;
}
KVector2D KCircle::GetSeparationVector(const KCircle& other) const {
const KVector2D centerDiff = Position - other.Position;
const float centerDiffLength = centerDiff.Length();
return centerDiff / centerDiffLength * (Radius + other.Radius - centerDiffLength);
}
void KCircle::Render(SDL_Renderer* renderer) const {
Texture.Render(renderer, static_cast<int>(Position.X) - Texture.GetWidth() / 2, static_cast<int>(Position.Y) - Texture.GetHeight() / 2);
}
void KCircle::CollisionDetectionWithMapStep(const SDL_Rect& map) {
if (Position.X - map.x - Radius < 0)
{
Position.X += -(Position.X - map.x - Radius);
Velocity = Velocity.Reflect({ -1.f, 0.f });
}
if (Position.X + Radius - map.w > 0)
{
Velocity = Velocity.Reflect({ 1.f, 0.f });
Position.X += -(Position.X - map.w + Radius);
}
if (Position.Y - Radius - map.y < 0) {
Position.Y += -(Position.Y - map.y - Radius);
Velocity = Velocity.Reflect({ 0.f, 1.f });
}
if (Position.Y + Radius - map.h > 0) {
Position.Y += -(Position.Y - map.h + Radius);
Velocity = Velocity.Reflect({ 0.f, -1.f });
}
}
}