MyCurry/src/gamelib/character.cpp

101 lines
2.8 KiB
C++

/*
Copyright 2016, 2017 Michele "King_DuckZ" Santullo
This file is part of MyCurry.
MyCurry is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MyCurry is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with MyCurry. If not, see <http://www.gnu.org/licenses/>.
*/
#include "character.hpp"
#include "inputbag.hpp"
#include "gameactions.hpp"
#include "worldgrid.hpp"
#include "drawing_queue.hpp"
#include "worldviewport.hpp"
#include "texture.hpp"
#include "draw_layer_names.hpp"
#include <ciso646>
#include <cassert>
#include <cstdint>
namespace curry {
Character::Character (cloonel::InputBag* parInputBag, const WorldSizeNotifiable::DeferredRegister& parDeferredRegister) :
WorldMoveable(parDeferredRegister),
m_input_bag(parInputBag),
m_speed(1.0f)
{
assert(m_input_bag);
}
Rect<float> Character::destination_rect (const vec2f& parWorldPos) const {
return Rect<float>(
position() - parWorldPos,
position() - parWorldPos + width_height()
);
}
Rect<float> Character::source_rect() const {
return Rect<float>(
vec2f(0.0f),
width_height()
);
}
void Character::do_movement (float parDeltaT) {
const float speed = parDeltaT * m_speed;
vec2f offset(0.0f);
if (cloonel::IsPressed(*m_input_bag, ActionRight))
offset.x() += speed;
if (cloonel::IsPressed(*m_input_bag, ActionLeft))
offset.x() -= speed;
if (cloonel::IsPressed(*m_input_bag, ActionUp))
offset.y() -= speed;
if (cloonel::IsPressed(*m_input_bag, ActionDown))
offset.y() += speed;
const auto old_pos = this->position();
this->set_position(old_pos + offset);
if (position() == old_pos)
return;
WorldGrid& world = this->world();
const vec2f new_pos = m_collider.try_reach_tile(
texture()->width_height() / world.tile_size(),
old_pos,
position(),
world
);
this->set_position(new_pos);
}
void Character::set_speed (float parSpeed) {
assert(parSpeed > 0.0f);
m_speed = parSpeed;
}
void Character::draw (DrawingQueue& parDQ, const WorldViewport& parViewport) {
DrawingQueue::ItemInfo item;
item.source = source_rect();
item.destination = destination_rect(parViewport.position());
item.texture = texture();
parDQ.add_for_rendering(DrawaLayerNames::Characters, std::move(item));
assert(not item.texture);
}
void Character::on_texture_size_changed (const vec2f& parOldSz, const vec2f& parNewSz) {
this->update_moveable_size(parOldSz, parNewSz);
}
} //namespace curry