【问题标题】:I'm trying to shoot with vectors我正在尝试用矢量拍摄
【发布时间】:2014-04-27 03:48:08
【问题描述】:

我目前正在用直接 X 用 C++ 编写游戏,目前正在使用一个向量来存储绘制我的所有精灵。我无法让子弹在矢量中工作。 子弹射了,但应该有 50 颗的时候只有一颗出来

//this vector also contains all other sprites i have like my player and my score and other sprites 
///Draw is a class

vector<Draw*> chap;
vector<Draw*>::iterator it;
Draw *bullet = NULL;

///initialization of stuff
for (int i = 0; i < gt; i++)
{
    bullet = new Draw[gt];
    //this sets the x position and y position and other properties 
    bullet[i].setDraw(blet,0,0,.1,.1,0,64,64,1,0,1,color,0,0,90,0,0,false);
    chap.push_back(&bullet[i]);
}
//end initialization

///game loop
for (int i = 0; i < bell; i++)
{
    for (it = chap.begin(); it != chap.end(); it++)
    {
        (*it)->testShoot(&bullet[i], ME);
        ME->playerMove();
        monster1->move();
    }
}
///end loop there is other stuff in loop but doesn't effect anything

/// what i'm using 
void Draw::testShoot(Draw *sprite, Draw *sprite1)
{
    if ((int)timeGetTime() < timer + 100)return;
    timer = timeGetTime();

    for (int i = 0; i < 50; i++)
    {
        if (Key_Down(DIK_SPACE))
        {
            if (!sprite[i].alive)
            {
                sprite[i].x = sprite1->x + sprite1->width / 4;
                sprite[i].y = sprite1->y + sprite1->height / 4;
                sprite[i].velx = 1;
                sprite[i].vely = 0;
                sprite[i].alive = true;
                break;
            }
        }
    }
}

【问题讨论】:

    标签: c++ arrays class pointers vector


    【解决方案1】:

    bullet = new Draw[gt]; 应该在 for 循环之前,而不是在里面。现在,您在循环的每次迭代中创建一个新数组,该数组只有一个填充元素,并且在每次覆盖 bullet 中的值时丢失之前创建的数组。

    换句话说,这个:

    for (int i = 0; i < gt; i++)
    {
        bullet = new Draw[gt];
        bullet[i].setDraw( ...
    

    应该是这样的:

    bullet = new Draw[gt];
    for (int i = 0; i < gt; i++)
    {
         bullet[i].setDraw( ...
    

    【讨论】:

    • 我忘了把循环的开始和结束放在哪里,一切都很好,没有错误,没有任何中断,
    • 我什至根本没有注意到,我在寻找错误的地方来解决我的问题。
    • 更不用说,根据Drawgt的大小,大量的内存泄漏:L
    猜你喜欢
    • 2023-03-08
    • 1970-01-01
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    • 2012-04-04
    相关资源
    最近更新 更多