player.cpp Example File
accelgame/src/player.cpp
#include <bb/cascades/AbsoluteLayoutProperties>
#include <bb/cascades/ParallelAnimation>
#include <bb/cascades/RotateTransition>
#include <bb/cascades/StockCurve>
#include <bb/cascades/TranslateTransition>
#include "board.hpp"
#include "player.hpp"
using namespace bb::cascades;
const static int s_tileSize = 50;
Player::Player(Board *board, QObject *parent)
: QObject(parent)
, m_board(board)
, m_playerTile(new ImageView)
, m_currentDirection(Up)
, m_currentPosition(0, 0)
, m_currentAnimation(0)
{
m_playerTile->setPreferredWidth(s_tileSize);
m_playerTile->setPreferredHeight(s_tileSize);
m_playerTile->setImage(Image(QUrl("asset:///images/player.png")));
m_board->board()->add(m_playerTile);
AbsoluteLayoutProperties *props
= qobject_cast<AbsoluteLayoutProperties*>(m_playerTile->layoutProperties());
if (props) {
props->setPositionX(0);
props->setPositionY(0);
}
}
Player::~Player()
{
m_board->board()->remove(m_playerTile);
delete m_playerTile;
delete m_currentAnimation;
}
void Player::reset()
{
m_currentDirection = Up;
m_playerTile->setRotationZ(0);
m_currentPosition = QPoint(0, 0);
m_playerTile->setTranslationX(0);
m_playerTile->setTranslationY(0);
}
void Player::go(Direction direction)
{
m_currentDirection = direction;
bool move = false;
switch (direction) {
case Up:
if (m_board->canMoveTo(m_currentPosition.x(), m_currentPosition.y() - 1)) {
move = true;
m_currentPosition.setY(m_currentPosition.y() - 1);
}
break;
case Right:
if (m_board->canMoveTo(m_currentPosition.x() + 1, m_currentPosition.y())) {
move = true;
m_currentPosition.setX(m_currentPosition.x() + 1);
}
break;
case Down:
if (m_board->canMoveTo(m_currentPosition.x(), m_currentPosition.y() + 1)) {
move = true;
m_currentPosition.setY(m_currentPosition.y() + 1);
}
break;
case Left:
if (m_board->canMoveTo(m_currentPosition.x() - 1, m_currentPosition.y())) {
move = true;
m_currentPosition.setX(m_currentPosition.x() - 1);
}
break;
default:
break;
}
if (m_currentAnimation) {
m_currentAnimation->stop();
m_currentAnimation->deleteLater();
}
const int rotationOffset
= (move ? ((m_currentDirection == Up || m_currentDirection == Left)
? -115 : 115) : 0);
const int duration = 80;
m_currentAnimation = ParallelAnimation::create(m_playerTile)
.add(TranslateTransition::create()
.toX(m_currentPosition.x() * s_tileSize)
.duration(duration).easingCurve(StockCurve::Linear))
.add(TranslateTransition::create()
.toY(m_currentPosition.y() * s_tileSize)
.duration(duration).easingCurve(StockCurve::Linear))
.add(RotateTransition::create()
.toAngleZ(m_playerTile->rotationZ() + rotationOffset)
.duration(duration).easingCurve(StockCurve::Linear));
bool ok = connect(m_currentAnimation, SIGNAL(ended()), SIGNAL(moved()));
Q_ASSERT(ok);
Q_UNUSED(ok);
m_currentAnimation->play();
}
void Player::goUp()
{
go(Up);
}
void Player::goRight()
{
go(Right);
}
void Player::goDown()
{
go(Down);
}
void Player::goLeft()
{
go(Left);
}