Home > OS >  Should the coordinates, and rotation angles of all the sprites be stored in variables?
Should the coordinates, and rotation angles of all the sprites be stored in variables?

Time:07-20

I've learned that magic numbers are bad in code. However, should the coordinates, and rotation angles of all the sprites be stored in variables? Is the convention in game development to leave those hard-coded values as arguments to set the coordinates or the angles of the transformable?

// Create a texture to hold a graphic on the GPU
Texture textureBackground;
// Load a graphic into the texture
textureBackground.loadFromFile("graphics/background.png");
// Create a sprite
Sprite spriteBackground;
// Attach the texture to the sprite
spriteBackground.setTexture(textureBackground);
// Set the spriteBackground to cover the screen
spriteBackground.setPosition(0, 0);
// Create a tree sprite
Texture textureTree;
textureTree.loadFromFile("graphics/tree.png");
Sprite spriteTree;
spriteTree.setTexture(textureTree);
spriteTree.setPosition(810, 0);
// Prepare the bee
Texture textureBee;
textureBee.loadFromFile("graphics/bee.png");
Sprite spriteBee;
spriteBee.setTexture(textureBee);
spriteBee.setPosition(0, 800);

CodePudding user response:

For small games, it's okay to define these defaults locally in code directly. For anything more complex, it becomes rather unmanageable to keep it all in code.

That's when the data is moved into dedicated external files. This can be a simple JSON file that holds all the different sprites and their initial position. You'd then load this information at the beginning of a map/level/game and create the different shapes/textures/sprites/sounds.

As a side note, only really do this when your game gets bigger, because it introduces quite a bit more complexity, as your code has to be written more generically and can also consume quite a bit more effort to get the loading working smoothly. If you do achieve it though, it offers a lot of flexibility. You can modify the whole level or character with a simple edit of the config file and restarting the game or even implement some hot-reloading.

  • Related