第十二章- 悬停在空中的砖(轨迹)

在这里插入图片描述

上一篇无轨迹的
为了添加一个作弊按钮,使得炮弹在五秒钟内绘制其轨迹,我们可以通过以下步骤来实现:

  1. 添加按钮:在 CannonField 类的构造函数中,创建一个按钮,并将其与槽函数连接。
  2. 绘制轨迹:实现一个新的函数,该函数绘制炮弹在五秒内的轨迹。
  3. 更新 paintEvent:在 paintEvent 中调用新的函数以绘制轨迹。

1. 添加按钮

CannonField 类中,添加一个新的按钮来触发绘制炮弹轨迹的功能:

// 在头文件中声明新按钮和槽函数
public slots:
    void cheatClicked();
    
private:
    void paintTrajectory(QPainter *);
    bool showTrajectory;
    

MyWidget 构造函数中,初始化按钮并连接槽函数:

    // 创建作弊按钮
    QPushButton *cheatButton = new QPushButton("Show Trajectory");
    connect(cheatButton, SIGNAL(clicked()), cannonField, SLOT(cheatClicked()));

2. 实现槽函数

CannonField 类中,初始化 showTrajectory,添加 cheatClicked() 的实现:

showTrajectory = false;

void CannonField::cheatClicked()
{
    showTrajectory = !showTrajectory; // 切换轨迹显示状态
    repaint();
}

3. 绘制轨迹

paintEvent 方法中,绘制轨迹:

void CannonField::paintEvent(QPaintEvent *e)
{
    QRect updateR = e->rect();
    QPainter p(this);

    if (updateR.intersects(cannonRect()))
        paintCannon(&p);
    if (autoShootTimer->isActive() && updateR.intersects(shotRect()))
        paintShot(&p);
    if (updateR.intersects(targetRect()))
        paintTarget(&p);

    if (showTrajectory)
        paintTrajectory(&p);
}

添加新的 paintTrajectory 方法来绘制轨迹:

void CannonField::paintTrajectory(QPainter *p)
{
    const double gravity = 4;
    double timeInterval = 0.1;
    double maxTime = 10.0; // 10秒
    double time = 0;

    p->setPen(QPen(Qt::blue, 2)); // 设置轨迹颜色和线宽

    while (time <= maxTime)
    {
        double velocity = f;
        double radians = ang * 3.14159265 / 180;
        double velx = velocity * cos(radians);
        double vely = velocity * sin(radians);
        double x0 = (barrelRect.right() + 5) * cos(radians);
        double y0 = (barrelRect.right() + 5) * sin(radians);
        double x = x0 + velx * time;
        double y = y0 + vely * time - 0.5 * gravity * time * time;

        QPoint point(qRound(x), height() - 1 - qRound(y));
        p->drawPoint(point);

        time += timeInterval;
    }
}
  • 24
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值