Returning an element from an array

Started by
23 comments, last by Toshio 11 years, 9 months ago
Show us the code that is having problems.

If it's too large to post, consider taking out pieces one by one until you identify the smallest program subset that actually demonstrates the problem you're having, and post that instead.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

Advertisement

void Game::OnInit()
{
Map map;
Player p(map);
p.Init();
}

void Game::OnLoop()
{
Map map;
Player p(map);
p.Move();
}


Nothing compiles as it should.
Here are those two functions:


void Player::Init()
{
CSurface c;
x = 100;
y = 100;
texture = c.loadTexture("player.png");
}
void Player::Move()
{
x += xVel * (delta / 1000.0f);
y += yVel * (delta / 1000.0f);

//...
}
If you create a Map or Player within a function, it creates a new Map or Player, not the one you used previously.

You have to create them once, by placing them in the Game declaration.
class Game
{
public:
Game();

//...other stuff.

private:
Map map;
Player player;

};


And in the constructor, you need to initialize Player with the Map, in the Game's constructor.
Game::Game() : player(map) //Pass 'map' into the Player constructor.
{

}


...And then you can use 'map' and 'player' normally, without re-creating them.
void Game::OnInit()
{
p.Init();
}

void Game::OnLoop()
{
p.Move();
}

#include <vector>

class Map
{
public:
[...]

private:
int width, height;
std::vector<int> tiles;

//Converts from a two-dimensional x,y to a one-dimensional index into our vector.
int _GetIndex(int x, int y)
[...]

//Makes sure that we aren't going out of bounds, which will crash the program.
bool _IsValid(int index)
[...]
};


Just a note here so people don't get into any bad habits: identifiers starting with an underscore followed by an upper case letter should never be used, as they're reserved for the implementation.
[size=2][ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]
Wow, thank you Servant of the Lord. Everything works now :D
Thanks ApochPiQ and everyone else who helped :)

This topic is closed to new replies.

Advertisement