Multiple instances of one class
#1 Members - Reputation: 26
Posted 01 November 2012 - 12:53 PM
Thank you
#2 Members - Reputation: 1556
Posted 01 November 2012 - 01:15 PM
You should check out my Old Blog (also linked in my sig). I detail the steps for making a top-down 2d game similar to what you are suggesting (player starts in map, enemies spawn from an "Enemy Spawn", bullets shooting everywhere).
(Here's the link to the entry on adding enemies to my game: Click Here)
In general, my Enemy Spawn's are considered an item, and I update it like this:
BOOL SmashPcItem::Update(void)
{
// Release Enemies into the level
if (mpItemDetails->Type == "EnemySpawn")
{
if (mu32NumReleaseLeft && (mu32LastRelease + mpItemDetails->u32ReleaseRate < timeGetTime()))
{
SmashPcEnemy *pEnemy;
mu32LastRelease = timeGetTime();
mu32NumReleaseLeft--;
// Create an enemy
pEnemy = new SmashPcEnemy(mGameData, mpApp, mpSpace,
mpBody->p, mpItemDetails->u32EnemyLevel);
// Check if this enemy should release something
mGameData.AddActiveEnemy(pEnemy);
}
}
return mbActive;
}
Which basically says, if there are still enemies to release, and if it's time to release a new enemy, then create a new enemy, and add him to the list of active enemies. Here's what the enemies actually do (the full Enemy class here):
/******************************************************************************
*
* SmashPcEnemy() - Creates a player, and places him in the space
*
******************************************************************************/
SmashPcEnemy::SmashPcEnemy(SmashPcData &GameData,
sf::RenderWindow *pApp, cpSpace *pSpace,
cpVect Location, U32 u32Level) :
PhysicalObject(pApp, pSpace, "Gfx/blueenemy.bmp", "",
Location, PI/2.0f, 0.0f, TRUE),
mu32Health(20*u32Level),
mu32LastFire(timeGetTime()),
mu32LastMoveUpdate(0),
mGameData(GameData)
{
printf("Enemy created!\n");
// Set the Velocity limit to our fake movement
mpBody->v_limit = ENEMY_SPEED;
mpShape->collision_type = ENEMY_COL_TYPE;
mpShape->layers = ENEMY_PLAYER_LAYER;
mpShape->data = (void *)this;
// Create Collision handler here
cpSpaceAddCollisionHandler(mpSpace, ENEMY_COL_TYPE, BULLET_COL_TYPE, SmashPcEnemy::BulletCollision, NULL, NULL, NULL, NULL);
// Sound notifying a player has spawned
GameSound::Play("EnemySpawn");
}
/******************************************************************************
*
* ~SmashPcEnemy() - Removes a player
*
******************************************************************************/
SmashPcEnemy::~SmashPcEnemy()
{
}
/******************************************************************************
*
* Update() - Do enemy things
*
******************************************************************************/
void SmashPcEnemy::Update(cpBody *pPlayerBody)
{
U32 u32Time = timeGetTime();
// check if we need to update the movement
if (mu32LastMoveUpdate + ENEMY_UPDATE_MOVE < u32Time)
{
cpFloat Angle = atan2(pPlayerBody->p.y - mpBody->p.y,
pPlayerBody->p.x - mpBody->p.x);
// add randomization to angle
cpFloat RandomDegrees = (cpFloat)(((S32)rand() % 20) - 10);
Angle += (RandomDegrees*PI)/180.0f;
cpBodySetAngle(mpBody, Angle);
// Change force towards player
mForce = cpv(ENEMY_FORCE*cos(Angle), ENEMY_FORCE*sin(Angle));
//mpBody->f = cpv(ENEMY_FORCE*cos(Angle), ENEMY_FORCE*sin(Angle));
mu32LastMoveUpdate = u32Time;
}
mpBody->f = mForce;
if (mu32LastFire + ENEMY_REFIRE_TIME < u32Time)
{
SmashPcData::tBulletList BulletList;
mGameData.GetBulletList(BulletList);
SmashPcBullet *pBullet = new SmashPcBullet(mpApp, BulletList[0],
mpBody, mpSpace, FALSE);
mGameData.AddActiveBullet(pBullet);
mu32LastFire = u32Time;
}
}
/******************************************************************************
*
* NotifyHit() - Notify the enemy it has been hit by a bullet
*
******************************************************************************/
void SmashPcEnemy::NotifyHit(SmashPcBullet *pBullet)
{
if (mu32Health < pBullet->GetDamage())
{
// Enemy Dead
mu32Health = 0;
// Play dead sound
}
else
{
GameSound::Play("PlayerHit");
mu32Health -= pBullet->GetDamage();
}
pBullet->SetDead();
}
/******************************************************************************
*
* BulletCollision() - Callback for when Enemy hits a bullet
*
******************************************************************************/
int SmashPcEnemy::BulletCollision(cpArbiter *arb, struct cpSpace *space, void *data)
{
SmashPcBullet *pBullet;
SmashPcEnemy *pEnemy;
cpShape *pBulletShape, *pEnemyShape;
cpArbiterGetShapes(arb, &pEnemyShape, &pBulletShape);
pEnemy = reinterpret_cast<SmashPcEnemy*>(pEnemyShape->data);
pBullet = reinterpret_cast<SmashPcBullet*>(pBulletShape->data);
// We have the enemy that hit, and the bullet he hit
pEnemy->NotifyHit(pBullet);
return 0;
}
I updated my enemies later on to make them a little smarter and to shoot better, but you get the picture.
Edited by BeerNutts, 01 November 2012 - 01:17 PM.
---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)
#3 Crossbones+ - Reputation: 1043
Posted 01 November 2012 - 02:56 PM
You can stick all the objects of that type in a single container, like std::vector<Enemy> allEnemies. Whenever you create a new enemy, you add it into that container like so: allEnemies.push_back(... your new enemy object ...). Whenever an enemy dies, you remove it from that container. To handle things like drawing all of them and having all of them take action, you just loop through all of the objects in the container on every game tick, like so:
for(std::vector<Enemy>::size_type i = 0; i<allEnemies.size(); ++i) { allEnemies[i].draw(); }or so:std::for_each(allEnemies.begin(), allEnemies.end(), [](&Enemy e){ e.draw(); });or so:for(auto e : allEnemies) {e.draw();}
#4 Members - Reputation: 26
Posted 01 November 2012 - 03:10 PM
- So to create enemies, should I just use my player class and add an AI function to it? How could I do this AI? After that should I just create, say, 10 enemies in an object array and loop through their functions just like the normal player(only that using AI instead of handle Input).
- And how could I make projectiles, you still havent talked about that.
#5 Crossbones+ - Reputation: 1043
Posted 01 November 2012 - 04:39 PM
Where in the code you should create new enemies depends on the logic you intend the game to have. Is the player avatar in the game world actually creating enemies? Probably not.- So to create enemies, should I just use my player class and add an AI function to it?
For instance, if you want enemies to spawn randomly over time, just put a function in your main game loop which does that. Assuming you want an average of one new enemy every 3 seconds, and your game runs with 60 logic ticks a second, the function should spawn an enemy 1/(3*60) of the time and do nothing the rest of the time.
Who's shooting? If the player, then the player class' game logic should make new projectiles. If an enemy is shooting, the enemy class' game logic should make new projectiles. Put a tick() function on everything in the game and just call that function on every object once per game tick, just like the draw() function above. Enemies' tick() function will contain the enemies' AI, moving them around and doing stuff. Simple projectiles' tick() function will just keep moving the projectile in the direction it was fired, and perhaps count down to a time or distance where the projectile dissipates and removes itself from the game.- And how could I make projectiles, you still havent talked about that.
You can handle projectiles like you handle the enemies: place them in their own container when you create them, remove them from the container when they are supposed to die.
#6 Members - Reputation: 1132
Posted 01 November 2012 - 04:43 PM
Remember that your player / enemy doesn't own the projectiles. Keep all the projectiles in the one and same list.
Cheers!
#7 Members - Reputation: 609
Posted 01 November 2012 - 04:45 PM
Bullets are just like Zombies: You create their constructor, Draw() and Update() function. You make a container of Bullets and loops to call Draw() and Update(). And when the player or somebody else fires their gun, you construct a new Bullet using their position, heading et cetera.
#11 Crossbones+ - Reputation: 1043
Posted 01 November 2012 - 07:58 PM
http://www.cplusplus.com/reference/stl/vector/push_back/Ok, thank you for all these ideas, but could someone explain to me how to make a vector containing items and how to add and delete elements from it.
http://www.cplusplus.com/reference/stl/vector/erase/
#12 Members - Reputation: 26
Posted 02 November 2012 - 05:14 AM
[source lang="cpp"] vector<Player> zombies (5); Player *zombieO; for (int n=0; n<5; n++) { int xR = rand() % 1000 + 1; int yR = rand() % 800 + 1; zombieO = new Player; zombieO->initialize(xR, yR, 50); zombieO->loadContent(); zombies.push_back(*zombieO); } while(Window.IsOpened()) { sf::Event Event; while(Window.GetEvent(Event)) { if(Event.Type == sf::Event::Closed) Window.Close(); } vector<Player>::iterator it; for ( it = zombies.begin(); it != zombies.end(); ++it ) { zombieO->tick(player, Window); zombieO->draw(Window); }[/source]
Any help or other ideas? Also, can you also tell me how to do projectiles?
#13 Members - Reputation: 1556
Posted 02 November 2012 - 08:11 AM
Ok... that's not helping at all. Can you just show me how I would make my code. I have a person class containing all functions for a zombie, what i want to do is create a vector, make a certain amount of zombies(person class) inside them according to a rand() function, initialize them all and then during my main loop to update them. I thought of this code, but it just makes my player go really laggy and no zombies appear:
Any help or other ideas? Also, can you also tell me how to do projectiles?
mypel,
I've given you a link to look directly at my source code (you can download the full source from my Old Blog), and you've been given the webpage that explains vectors. You need to do some work yourself.
Your code looks OK, but there's still some issues. You don't need to declare how big a vector is, it is dynamic, so you can just push_back zombie's as you need them. ALso, don't create a new player pointer for the zombies just push an instance of them onto th vector, like this:
for (int i = 0; i < 5; ++i) {
int xR = rand() % 1000 + 1;
int yR = rand() % 800 + 1;
// Your player class should have the cxonstructor define the x, y, and (whatever 50 is), not a separate call to initialize
// the constructor can probably do whatever loadContent does too
Player zombie(xR, yR, 50);
zombies.push_back(zombie);
}
Also, you're not looping through the zombies at all. Zombie0 is just the last zombie created in your loop. You need to be access the zombies form the vector. Again, the vector page will help, but here's what I would do:
for (int = 0; i < zombies.size(); ++i) {
zombies[i]->tick(player, Window);
zombies[i]->draw(Window);
}
And projectiles aren't much different than adding a zombie as far as adding them to a vector, and looping through them all to process them.
Edited by BeerNutts, 02 November 2012 - 08:12 AM.
---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)
#14 Members - Reputation: 26
Posted 02 November 2012 - 04:35 PM
Please help, I have tried vectors with other games and they work, but there's a problem with this one.
#15 Members - Reputation: 1556
Posted 02 November 2012 - 08:10 PM
Worse case, you throw some prints inside your code, see which line gets print and which doesn't. Then, work from there.
Honestly I think you need to step back from the game scene, and work on playing with objects in vectors, and looping through the objects and doing things to them in a simple program. Once you understand how it works, then you can move to the next thing.
---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)
#16 Members - Reputation: 26
Posted 03 November 2012 - 03:32 AM






