Student
Student

Reputation: 452

Array of object C++

In the image below (Character.cpp), may I know how to create only one Initialize method that can be called to stored many sprites? Do I need to change the Texture1,Sprite,PosX,PosY, etc to array? The initialize method will be called in my MAIN.cpp. Sorry if the explaination is not good enough. That is just my idea of doing it but will there be a better ones instead of having so many arrays?

void Character::Initialize1(string image1, float PosX1, float PosY1, float CenterX1, float CenterY1)
{
    D3DXCreateTextureFromFile(Pull->GETd3ddev(), image.c_str(), &Texture1);
    D3DXCreateSprite(Pull->GETd3ddev(), &sprite1);
    RECT SpriteRect1;
    SpriteRect1.top = 0;
    SpriteRect1.bottom = 127;
    SpriteRect1.left = 0;
    SpriteRect1.right = 128;
    SpritePos1 = D3DXVECTOR2(PosX1, PosY1);
    SpriteCenter1 = D3DXVECTOR2(CenterX1, CenterY1);
}

void Character::Initialize2(string image2, float PosX2, float PosY2, float CenterX2, float CenterY2)
{
    D3DXCreateTextureFromFile(Pull->GETd3ddev(), image.c_str(), &Texture2);
    D3DXCreateSprite(Pull->GETd3ddev(), &sprite2);
    RECT SpriteRect2;
    SpriteRect2.top = 0;
    SpriteRect2.bottom = 14;
    SpriteRect2.left = 0;
    SpriteRect2.right = 14;
    SpritePos2 = D3DXVECTOR2(PosX2, PosY2);
    SpriteCenter2 = D3DXVECTOR2(CenterX2, CenterY2);
}

Upvotes: 0

Views: 103

Answers (1)

Gio
Gio

Reputation: 3340

Create the necessary initialization method in your sprite class. Then in main() create your sprites and call the appropriate initialization methods. If using lots of Sprites, it will be probably handy to put the created sprites inside a vector in order to have less code for cleanup and probably other things.

A quick example for a Sprite class called SpriteConfig, which only contains position parameters.

#include <iostream>
#include <vector>

using namespace std;

class SpriteConfig {
public:
    SpriteConfig() {
        top = 0;
        bottom = 0;
        left = 0;
        right = 0;
    }

    void setPos(float aTop, float aBottom, float aLeft, float aRight) {
        mTop = aTop;
        mBottom = aBottom;
        mLeft = aLeft;
        mRight = aRight;
    }
private:
    // position parameters
    float mTop;
    float mBottom;
    float mLeft;
    float mRight;
};


int main()
{
    vector<SpriteConfig*> spriteConfigs;
    SpriteConfig *sprCfg;

    sprCfg = new SpriteConfig();
    sprCfg->setPos(1,1,1,1);
    spriteConfigs.push_back(sprCfg);

    sprCfg = new SpriteConfig();
    sprCfg->setPos(2,2,2,2);
    spriteConfigs.push_back(sprCfg);

    // We now have a number of Sprites
    // Add code here to do something with it.
    // ...

    for(vector<SpriteConfig*>::iterator it = spriteConfigs.begin();
        it != spriteConfigs.end();
        ++it) {
        // cleanup
        delete (*it);
        (*it) = null;
    }

    return 0;
}

Upvotes: 1

Related Questions