87 lines
		
	
	
		
			2.2 KiB
		
	
	
	
		
			C++
		
	
	
	
	
	
			
		
		
	
	
			87 lines
		
	
	
		
			2.2 KiB
		
	
	
	
		
			C++
		
	
	
	
	
	
| #include "KPawn.h"
 | |
| 
 | |
| #include <memory>
 | |
| #include <typeinfo>
 | |
| #include <unordered_map>
 | |
| 
 | |
| #include "Constants.h"
 | |
| #include "KPlayerController.h"
 | |
| #include "KExit.h"
 | |
| 
 | |
| namespace KapitanGame
 | |
| {
 | |
| 	void KPawn::CollisionDetectionStep(const std::unordered_map<std::pair<int, int>, std::shared_ptr<KObject>, Utils::PairHash>& objects)
 | |
| 	{
 | |
| 		if (GetCollider() == nullptr) return;
 | |
| 
 | |
| 		const auto xPos = static_cast<int>(GetPosition().X / Constants::TILE_WIDTH);
 | |
| 		const auto yPos = static_cast<int>(GetPosition().Y / Constants::TILE_HEIGHT);
 | |
| 
 | |
| 		for (const auto& [oX, oY] : std::initializer_list<std::pair<int, int>>{ {0, 0}, {-1,0}, {1,0}, {0,-1}, {0,1}, {-1,-1}, {1,1}, {1,-1}, {-1,1} })
 | |
| 		{
 | |
| 			try {
 | |
| 				const auto& other = objects.at({ xPos + oX, yPos + oY });
 | |
| 				if (other->GetCollider() == nullptr) continue;
 | |
| 				if (other->Id == Id) continue;
 | |
| 				if (GetCollider()->IsCollision(other->GetCollider())) {
 | |
| 					if (typeid(*other) == typeid(KExit)) {
 | |
| 						if (const auto pc = PlayerController.lock()) {
 | |
| 							//pc->NotifyWin();
 | |
| 						}
 | |
| 						return;
 | |
| 					}
 | |
| 					const auto separationVector = GetCollider()->GetSeparationVector(other->GetCollider());
 | |
| 
 | |
| 					Position += separationVector;
 | |
| 					if (separationVector.Y < 0)
 | |
| 					{
 | |
| 						Velocity.Y = 0;
 | |
| 						Grounded = true;
 | |
| 					}
 | |
| 				}
 | |
| 			}
 | |
| 			catch (std::out_of_range&)
 | |
| 			{
 | |
| 			}
 | |
| 		}
 | |
| 	}
 | |
| 
 | |
| 	void KPawn::MovementStep(const float& timeStep)
 | |
| 	{
 | |
| 		Position.X += Velocity.X * timeStep;
 | |
| 		Position.Y += Velocity.Y * timeStep + 1.f / 2.f * Constants::GRAVITY * timeStep * timeStep;
 | |
| 		Velocity.Y += Constants::GRAVITY * timeStep;
 | |
| 	}
 | |
| 
 | |
| 	void KPawn::CollisionDetectionWithMapStep(const SDL_FRect& map)
 | |
| 	{
 | |
| 		const auto separationVector = GetCollider()->GetSeparationVector(map);
 | |
| 		Position += separationVector;
 | |
| 		if (separationVector.Y < 0)
 | |
| 		{
 | |
| 			Velocity.Y = 0;
 | |
| 			Grounded = true;
 | |
| 		}
 | |
| 	}
 | |
| 
 | |
| 	void KPawn::AddXMovementInput(const float& input)
 | |
| 	{
 | |
| 		Velocity.X = input * Constants::SPEED * (1 - Constants::SMOOTH) + Velocity.X * Constants::SMOOTH;
 | |
| 	}
 | |
| 
 | |
| 	void KPawn::StopJump() {
 | |
| 		if (!Grounded) {
 | |
| 			if (Velocity.Y < -Constants::JUMP_SHORT_SPEED)
 | |
| 				Velocity.Y = -Constants::JUMP_SHORT_SPEED;
 | |
| 		}
 | |
| 	}
 | |
| 
 | |
| 	void KPawn::StartJump() {
 | |
| 		if (Grounded) {
 | |
| 			Grounded = false;
 | |
| 			Velocity.Y = -Constants::JUMP_SPEED;
 | |
| 		}
 | |
| 	}
 | |
| }
 | |
| 
 |