C++/SDL:矢量/曲面问题

C++ / SDL: vector / surface issues

本文关键字:曲面 问题 矢量 SDL C++      更新时间:2023-10-16

这是我遇到的最新问题。我有一个课叫"炮弹",它掌握了炮弹的基本组成。它的坐标,以及它使用的图像。以下是基本结构:

class Projectile
{
    private:
        void load();
    public:
        SDL_Surface *surface;
        SDL_Surface* returnSurface()
        {
            return surface;
        }
        Projectile( int );
        void coordinates( int, int );
        int type;
        int width, height;
        int positionX, positionY;
        bool alive;
};
Projectile::Projectile( int type )
{
    type = 1;
    alive = true;
    width  = 83;
    height = 46;
}
void Projectile::load()
{
    SDL_Surface* loadedImage = NULL;
    loadedImage = IMG_Load( "hero.png" );
    surface = SDL_DisplayFormat( loadedImage );
    SDL_FreeSurface( loadedImage );
}
void Projectile::coordinates( int x, int y )
{
    positionX = x;
    positionY = y;
}

现在,我也有我的英雄类,它将投射物保持在一个向量中,比如:

向量<射弹>射弹;

我在英雄类中有一个方法,它制造一个新的投射物,并将其推入这个向量中,如下所示:

void Hero::newProjectile( int type )
{
    projectiles.push_back( Projectile( type ) );
    projectileCount++;
}

然后是一个绘制方法,它在我的主循环的最后被调用,它执行以下操作:

void Hero::drawProjectileState( SDL_Surface* destination )
{   
    for( int i = 0; i < projectileCount; i++ )
    {
        SDL_Rect offset;
        offset.x = positionX;
        offset.y = positionY;
        SDL_BlitSurface( projectiles[i].returnSurface(), NULL, destination, &offset );
    }
}

从概念上讲,我认为这会很好。最初,我的射弹类将所有射弹坐标保存在自己的向量中,但当我想删除它们时,遇到了一个问题。由于他们都使用相同的表面资源,在屏幕上删除一个会导致游戏崩溃。我以为这会解决问题(每个人都有自己的地表资源(,但我得到了

读取位置0xccccccf8时发生访问冲突。

当它试图将炮弹拉向时

SDL_BlitSurface( projectiles[i].returnSurface(), NULL, destination, &offset );

我有一种感觉,我误解了表面参照的工作方式。最好的方法是给每枚炮弹自己的表面,这样我就可以独立删除它们了?

编辑:为了消除可能的混乱,我希望能够独立地释放曲面。一枚炮弹死亡后释放一个表面,但另一枚仍在屏幕上,这是最初造成坠机的原因。

Projectile::Projectile( int type )
{
    type = 1;
    alive = true;
    width  = 83;
    height = 46;
}
void Hero::newProjectile( int type )
{
    projectiles.push_back( Projectile( type ) );
    projectileCount++;
}

在上面的代码中,您从未加载过曲面。你甚至从未初始化过surface,所以它在空间中指向外,因此当你这样做时,drawProjectileState中的访问违规:

SDL_BlitSurface( projectiles[i].returnSurface(), NULL, destination, &offset );