83 lines
2.5 KiB
C++
83 lines
2.5 KiB
C++
// Copyright (c) 2024 Dominic Masters
|
|
//
|
|
// This software is released under the MIT License.
|
|
// https://opensource.org/licenses/MIT
|
|
|
|
#include "RPGPlayer.hpp"
|
|
#include "scene/Scene.hpp"
|
|
#include "assert/assert.hpp"
|
|
|
|
using namespace Dawn;
|
|
|
|
void RPGPlayer::onInit() {
|
|
rpgEntity = getItem()->getComponent<RPGEntity>();
|
|
assertNotNull(rpgEntity, "RPGPlayer requires an RPGEntity component!");
|
|
|
|
events.push_back(getScene()->onUnpausedUpdate.listen([&](
|
|
float_t d
|
|
) {
|
|
glm::vec2 movement = getGame()->inputManager.getAxis2D(
|
|
InputBind::LEFT, InputBind::RIGHT,
|
|
InputBind::UP, InputBind::DOWN
|
|
);
|
|
|
|
if(movement.x != 0 || movement.y != 0) {
|
|
enum RPGEntityDirection dir = rpgEntity->getFacingDirection();
|
|
if(movement.x > 0) {
|
|
if(
|
|
movement.y == 0 ||
|
|
(movement.y < 0 && dir == RPGEntityDirection::SOUTH) ||
|
|
(movement.y > 0 && dir == RPGEntityDirection::NORTH)
|
|
) {
|
|
rpgEntity->setFacingDirection(RPGEntityDirection::EAST);
|
|
}
|
|
} else if(movement.x < 0) {
|
|
if(
|
|
movement.y == 0 ||
|
|
(movement.y < 0 && dir == RPGEntityDirection::SOUTH) ||
|
|
(movement.y > 0 && dir == RPGEntityDirection::NORTH)
|
|
) {
|
|
rpgEntity->setFacingDirection(RPGEntityDirection::WEST);
|
|
}
|
|
} else if(movement.y > 0) {
|
|
rpgEntity->setFacingDirection(RPGEntityDirection::SOUTH);
|
|
} else if(movement.y < 0) {
|
|
rpgEntity->setFacingDirection(RPGEntityDirection::NORTH);
|
|
}
|
|
|
|
// Normalize angle.
|
|
float_t angle = atan2(movement.x, movement.y);
|
|
angle -= Math::deg2rad(90.0f);
|
|
movement = glm::vec2(cosf(angle), sinf(angle)) * PLAYER_SPEED * d;
|
|
|
|
// Update position.
|
|
auto ePos = getItem()->getLocalPosition();
|
|
ePos.x += movement.x;
|
|
ePos.y += movement.y;
|
|
getItem()->setLocalPosition(ePos);
|
|
}
|
|
|
|
if(this->camera != nullptr) {
|
|
this->camera->lookAtPixelPerfect(
|
|
getItem()->getLocalPosition() + glm::vec3(0, -(RPG_ENTITY_SIZE*2), 0),
|
|
getItem()->getLocalPosition(),
|
|
2.0f
|
|
);
|
|
}
|
|
}));
|
|
}
|
|
|
|
void RPGPlayer::onDispose() {
|
|
this->rpgEntity = nullptr;
|
|
}
|
|
|
|
void RPGPlayer::load(SceneComponentLoadContext &ctx) {
|
|
SceneComponent::load(ctx);
|
|
|
|
if(ctx.data.contains("camera")) {
|
|
assertMapHasKey(ctx.components, ctx.data["camera"], "Camera not found!");
|
|
const auto component = ctx.components[ctx.data["camera"].get<std::string>()];
|
|
this->camera = std::dynamic_pointer_cast<Camera>(component);
|
|
assertNotNull(this->camera, "Camera not found!");
|
|
}
|
|
} |