建立移动物体基类,使玩家以此类为基础
#ifndef MOVE_THING_BASE_H
#define MOVE_THING_BASE_H
#include "info.h"
class Move_Thing_Base : public QWidget
{
Q_OBJECT
public:
Move_Thing_Base();
~Move_Thing_Base() {}
void moveto(QPointF pos);
void moveto(qreal x, qreal y);
void setPos(qreal x, qreal y);
QGraphicsPixmapItem *itempix;
QPointF cpos, arrivepos; //角色坐标,到达目标坐标
QTimer *timer; //用于移动
qreal speed; //速度
bool once; //移动后是否销毁
bool fix; //是否为其移动地图
protected slots:
void move_use_timer();
};
#endif // MOVE_THING_BASE_H
实现
#include "info.h"
#include "gamewindow.h"
#include "move_thing_base.h"
Move_Thing_Base::Move_Thing_Base()
{
timer = 0;
speed = 5;
once = 0;
fix = 1;
}
void Move_Thing_Base::setPos(qreal x, qreal y)
{
cpos.setX(x);
cpos.setY(y);
itempix->setPos(cpos.x() - 45, cpos.y() - 45); //战车图片左上角与中心偏移45
}
void Move_Thing_Base::move_use_timer()
{
qreal partx = arrivepos.x() - cpos.x(); //x,y分量
qreal party = arrivepos.y() - cpos.y();
qreal s = sqrt(partx*partx + party*party); //直线路程
if (s <= speed)
{
if (timer->isActive())
{
timer->stop();
delete timer;
timer = 0;
if (once)
{
scene->removeItem(itempix);
delete this;
}
}
}
else
{
qreal movex = partx/s*speed; //每次计时移动距离
qreal movey = party/s*speed;
if (client->canArrive(cpos.x() + movex, cpos.y() + movey))
{
cpos.setX(cpos.x() + movex);
cpos.setY(cpos.y() + movey);
itempix->setPos(cpos.x() - 45, cpos.y() -45); //战车图片左上角与中心偏移45
}
else
{
if (timer->isActive())
{
timer->stop();
delete timer;
timer = 0;
}
}
}
if (fix)
client->fixClientFor(cpos.x(), cpos.y(), partx > 0 , party > 0);
}
void Move_Thing_Base::moveto(qreal x, qreal y)
{
arrivepos.setX(x);
arrivepos.setY(y);
if (!timer)
{
timer = new QTimer;
timer->start(50);
connect(timer, SIGNAL(timeout()), this, SLOT(move_use_timer()));
}
}
void Move_Thing_Base::moveto(QPointF pos)
{
moveto(pos.x(), pos.y());
}
玩家类
#ifndef PLAYER_H
#define PLAYER_H
#include "info.h"
#include "move_thing_base.h"
class Player : public Move_Thing_Base
{
Q_OBJECT
public:
Player();
~Player() {}
};
#endif // PLAYER_H
实现
#include "info.h"
#include "player.h"
//Player
Player::Player()
{
QPixmap pix(":/pic/1");
itempix = scene->addPixmap(pix);
setPos(MAPWIDTH/2, MAPHEIGHT/2);
}
炮弹类
#ifndef PAODAN_H
#define PAODAN_H
#include "info.h"
#include "move_thing_base.h"
class Paodan : public Move_Thing_Base
{
public:
Paodan(QPointF startpos, QPointF endpos);
};
#endif // PAODAN_H
实现
#ifndef PAODAN_H
#define PAODAN_H
#include "info.h"
#include "move_thing_base.h"
class Paodan : public Move_Thing_Base
{
public:
Paodan(QPointF startpos, QPointF endpos);
};
#endif // PAODAN_H