1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C++:listとiteratorで弾の管理をしてみる

Posted at

シューティングゲームの弾の管理をlistとiteratorを使った可変長配列で管理してみた。


//BulletManager.h

#include<list>
#include<iostream>

class Bullet;

class BulletManager
{
private:

    std::list<Bullet*>mpBullet;//listを使って弾を作る

public:

    BulletManager();//コンストラクタ
    ~BulletManager();//デストラクタ

    void Initialize();//初期化

    void Update();//弾の更新

    void Draw();//弾の描画

    void Finalize();//弾の終了処理

    void Shot();//弾を発射する

private:

    void DeleteBullet();//画面外に出た弾を削除する
};

//BulletManager.cpp

#include"Bullet"

BulletManager::BulletManager()
    :mpBullet()
{
}

BulletManager::~BulletManager()
{
}

void BulletManager::Initialize()
{
}

void BulletManager::Update()
{
    //for文をiteratorで回す
    for(std::list<Bullet*>::iterator itr = mpBullet.begin(); itr != mpBullet.end(); itr++)
    {
        if((*itr)  !=  nullptr)
        {
            (*itr)->Update();
        }
    }

    DeleteBullet();
}

void BulletManager::Draw()
{
    for(std::list<Bullet*>::iterator itr = mpBullet.begin(); itr != mpBullet.end(); itr++)
    {
        if((*itr)  !=  nullptr)
        {
            (*itr)->Draw();
        }
    }
}

void BulletManager::Finalize()
{
    for(std::list<Bullet*>::iterator itr = mpBullet.begin(); itr != mpBullet.end(); itr++)
    {
        if((*itr) == nullptr)
        {
            continue;
        }

        (*itr)->Finalize();
        delete  (*itr);
    }

    mpBullet.clear();
}

void BulletManager::Shot()
{
    mpBullet.push_back(new  Bullet());
    std::list<Bullet*>::iterator itr = mpBullet.end();
    itr--; 
    (*itr)->Initialize();
}

void BulletManager::DeleteBullet()
{
    for (std::list<Bullet*>::iterator itr = mpBullet.begin(); itr != mpBullet.end();)
    {
        if ((*itr) == nullptr)
        {
            itr++;
            continue;
        }

        //画面外に出たら削除
        if (
            (*itr)->GetPos().mX < -50 ||
            (*itr)->GetPos().mX > 690 ||
            (*itr)->GetPos().mY < -50 ||
            (*itr)->GetPos().mY > 530)
        {
            (*itr)->Finalize();       
            delete (*itr);
            (*itr) = nullptr;
            itr = mpBullet.erase(itr);
            continue;
        }
        itr++;
    }
}

今回は練習のためにnewを使ってますが実際に作るときはゲームループ中にnewするのはやめようね!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?