Simple 2d game. Adding background elements

Want to try creating your own 2D game? Here are the best tools for the job, even if you're new to the business.

Making games is difficult. The more you know about this process, the more you will be surprised that someone actually goes through with it. As one of the former authors of PC Gamer, Tom Francis, said when describing the process of programming the game Gunpoint: “During the work on the game, I came to one conclusion: My game is a real madness. This is a mental hospital patient. She has completely lost her mind, and you need to be prepared for the fact that all reasonable arguments will be met with insane screaming delirium. "

It's easy to get stumped at the sheer amount of work that will have to be done designing and coding your game, but we reached out to several independent developers and they all gave the same advice to newbies: just do it. Immerse yourself in the work with your head, no matter how scary it may seem. To help you take the first (daunting, but ultimately justifiable) step, we've prepared a list of 2D engines for aspiring game developers. We hope that, together with the recommendations of experienced game designers, it will be useful to you.

GameMaker Studio 2

License cost: $ 100 for the PC version; free trial available

Suitable for: short 2D platformers and RPGs; cross-platform games

Examples of games: Nidhogg, Hyper Light Drifter, Undertale, Risk of Rain

pros

Mark Essen, author of the Nidhogg and Nidhogg 2 games, says GameMaker is great for beginners because its scripting system is as simple and straightforward as possible, and the Yoyo Games portal has a collection of tutorials and guides on the topic. There are also plenty of add-ons on the internet to customize the engine to create a top-down platformer or RPG.

Alex Preston, creator of Hyper Light Drifter, says the GameMaker engine community is invaluable in helping newbies. He notes that aspiring developers should "... connect with the developer community and learn all the engine's tools to get what they want - and for that it is worth seeking advice from seasoned developers."

Minuses

Of course, you are unlikely to be able to immediately create a game that can be published on Steam. “Because GameMaker is so easy to use, projects are very often unbalanced,” says Essen. "I love that in the early stages of development, you can quickly outline the skeleton of your game and focus on its design, but in the future this can turn out to be sideways, especially if you do not adhere to organizational standards!"

Duncan Drummond, author of the beloved Risk of Rain, also points out that GameMaker's ease of use can be a developer's nightmare. “You can quickly create a game on the engine, but if you overlook mistakes in the early stages, then later it will result in an increase in the cost of the game,” he says. Drummond notes that the specifics of working with GameMaker are very different from working with other engines, so if in the future you plan to switch to Unity or any other engine, then you are probably better off looking for another option.

“Don't forget to delete your old work! The more often you start a game from scratch, the more experienced in game design you become. ”- Mark Essen, Nidhogg

“Just get started! Start the engine, read the manuals and get to work, even if you really can't. The more mistakes you make, the more lessons you learn. ”- Alex Preston, Hyper Light Drifter

“Don't be afraid to start! It's an interesting and relatively easy way to develop, and it only wastes your time. ”- Duncan Drummond, Risk of Rain

Unity

License cost: Free Starter Pack, $ 35 / month for Unity Plus, $ 125 / month for Unity Pro

Suitable for: almost any indie game

Examples of games:, Galak-Z, West of Loathing, Cuphead

Unity is one of the premier platforms for developing popular indie games, and while it has impressive 3D capabilities, it has produced many amazing 2D games. Unity is more difficult to learn than the rest of the engines on this list, but a large developer community and a huge number of tutorials that can be found online will help you get started.

On the official Unity website, you can also find special add-ons that allow you to customize the engine for developing 2D games. For example, the free 2D Platformer extension or tools like Corgi Engine and Rex Engine that offer game physics, controls and features tailored specifically for platformers.

We spoke with Joseph Humphrey at inkle and Victor Thompson at Asymmetric Publications who shared their experiences with Unity.

pros

Thompson, who previously created games in the classic way, quickly became a fan of Unity, the engine on which the recently released West of Loathing was created. “After 2-3 years of working with the engine, what I'm most excited about is how quickly concepts and prototypes can be combined,” he says. "I have used many different engines, both small for my own projects and large ones for developing AAA games, but Unity is by far the best engine I've seen because it allows me to be the most productive."

Minuses

However, if you are going to use one platform for all your development, you will face certain limitations. If you find a bug in Unity, you have to wait for the authors of the engine to fix it, and this is not always fast. "Although the engine officials say bug fixing is their top priority, the developers at inkle still see debugging stability as one of the engine's biggest problems," says Humphrey.

“First of all, try to create in your head the final image of the game and focus on it - your final goal should not be the experience gained in the process, but the finished product. Of course, it is useful to learn a couple of lessons from failures, but I think it is much more important to set a goal, learn everything that is necessary to achieve this goal, and ultimately realize it. ”- Victor Thompson, West of Loathing

Ren'Py

License cost: Is free

Suitable for: 2D visual novels, simulations

Compatible with: Python

Examples of games: Long Live the Queen, Analogue: A Hate Story

Ren'Py is an easy-to-learn open source engine. And while it does require some basic programming skills, in the very early stages you only need to know how to work with a word processor and photo editing applications. It is a convenient starting point for those planning to learn the Python programming language in the future.

pros

"Ren'Py's open source and cross-platform capabilities provide many opportunities for all users of the engine," says Bensley. “I also consider it a plus that the engine is designed for beginners, but at the same time requires making edits to the game's code. It's better than a graphical drag-and-drop interface as it shows that there is nothing to worry about programming. "
Ren'Py is for you if the very prospect of creating a game from scratch scares you:

“One of the biggest hurdles that most people who haven’t worked on creating games face before is the belief that programming is“ too hard, ”and therefore simply beyond their power. And this engine allows you to quickly and successfully create a simple game, which gives confidence to novice developers, even if they do not plan to release only visual novels in the future. Once you create something that others can play, even a simple project, you no longer question your abilities. "

Minuses

Ren'Py is a bit limited in terms of graphics and gameplay features. If you intend to create games with 3D, Live2D, damage system and other features, then you should look for other options.

ink

License cost: Is free

Suitable for: text adventure games

We are conscientious with: Unity, C #, HTML

Examples of games: 80 Days, Sorcery!

Ink is a good free add-on for Unity if you want to spice up your game with conversational branches and advanced storytelling. It's easy to learn, doesn't use any advanced code, and integrates seamlessly with Unity. According to the creator of ink, Joseph Humphrey, this engine is "intermediate" - after creating a script in ink, it can be transferred to a larger game on the Unity engine. However, the Inky Editor allows you to create web games as well.

pros

Writing a large-scale script with many conversational threads can quickly turn into a mess, so ink will help you not get lost in the process. “Game writers can use the engine's tools to create dialogs and text in a user-friendly interactive script with key cues,” says Humphrey. "Then the ink engine running inside Unity will be able to read these scripts and display the text on the screens in the game itself."

Open source plays an important role in the development of ambitious projects. Humphrey notes that “text generated in ink does not have to be displayed as text. For example, in the game Heaven's Vault, the ink engine creates a dynamic scenario that is interpreted by the game itself in the form of an interactive graphic novel with adventure elements. "

ink is also a great tool for those more interested in game scripting rather than pure programming. “… The number of writers using ink to write interactive stories is constantly growing,” adds Humphrey. “Where The Water Tastes Like Wine is one such example. It was created by the authors of the game Gone Home using the ink engine. Famous writers such as Lee Alexander, Emily Short and Kara Ellison worked on the game. So if you enjoy writing and are interested in game development, ink can be a great place to start. "

Minuses

ink is best used for games developed with the Unity engine. Humphrey says, “ink is not an alternative to Unity - it's more of an add-on. What's more, ink is the only interactive scripting tool that was intentionally created in the middle. "

“I have only one piece of advice - just try to create a demo game. If you want to fill your portfolio with examples of what you are good at, then it's time to start filling it. Create these examples! "

In early 2017, we wrote about the sudden appearance of RPG Maker on Steam platform and how the engine is rapidly gaining popularity among aspiring indie developers. But there are other tools to look out for:

HaxeFlixel open source and cross-platform.

Stencyl- a tool for creating games without programming.

Four ways of realization
There are four main approaches that platformers can be implemented. In order of increasing difficulty, they are:

Type # 1: Tile Based (Simple)
Character movement is limited to tiles (tiles), so you can never stand between two tiles. Special animations can be used to create the illusion of smooth movement, but the player will always be standing directly on a tile. This is the simplest way to implement a platformer, but it imposes severe restrictions on the control of the character, which makes the approach unsuitable for the implementation of the gameplay of platformer games we are used to. However, it is often used for puzzles and cinematic platformers.
Examples: Prince of Persia, Toki Tori, Lode Runner, Flashback
How it works
The map is a grid of tiles, each of which stores information about whether it is an obstacle or not, which image is used, which sounds of the character's footsteps should be used, and so on. The player and other characters are represented as a set of one or more tiles that move together. In Lode Runner, for example, the player is made up of one tile. In Toki Tori, the player is 2x2 tiles. In Flashback, the player is two tiles wide and five tiles high when standing (which is unusual due to the smaller size of the map tiles, see picture above), and three tiles high when seated.
In this form of play, the player will rarely - if ever - move diagonally. But, if necessary, the movement can be decomposed into two separate stages. The character will most likely move one tile at a time. Movement across multiple tiles can be done in multiple steps of 1 tile each (in Flashback, you always move through two tiles at once). Algorithm:
1. Create a copy of the character, move it to its destination (for example, if you move one square to the right, you need to make a copy of the character, where each of its tiles moves 1 tile to the right)
2. Check this copy for intersections with the background and other characters.
3. If an intersection was found, the character's movement is blocked. You need to enable the appropriate animations, etc.
4. Otherwise, move the character. The animation plays as you move, so the transition looks smooth.
This type of movement is very poorly suited for traditional arched jumps - for example, games in this genre often do not use jumps at all (Toki Tori, Lode Runner), or there may only be vertical or horizontal jumps (Prince of Persia, Flashback), which are nothing else. , as a variation of the described method.
The advantages of this system include simplicity and precision. Since games are more deterministic, glitches will occur much less frequently. The gameplay is more controllable, you need to make less changes to the implementation depending on the circumstances. Game mechanics(like climbing on ledges and one-sided platforms) is very easy compared to the more complex ways of creating platformers - all you have to do is check in the right place whether the player's tiles are located on the map for performing some action.
In principle, this system does not allow steps less than one tile wide, but this can be improved in several ways. For example, the tile can be slightly smaller than the player (say a 2x6 player), or you can allow visual entry into the tile without affecting the logic of the game (this approach, I think, is used in “Lode Runner - Legend Returns ”).

Tsp #2: Founded on tiles (with smoothing)
Here interaction with the game world also defined by a grid of cells, but characters have the ability to move freely around the world (usually 1px is assumed, rounded to integers). This is the most common method of developing platformers for 8-bit and 16-bit consoles. It is quite popular and is still, due to its relative simplicity, and therefore editing the levels of the game is an easier task than working with more advanced types. This allows you to create inclined platforms in the level, as well as set a smoother trajectory for jumping.
If you want to make a 2d action game, but are not sure what type of platformer you want to develop according to, I suggest you do just that. It is very flexible, relatively easy to implement, and provides more control than the other three types. Unsurprisingly, most of the best action platformers of all time were designed this way.


Frame from games Mega Man X.Visible boundaries cells and hitbox (zone defeat) player.
Examples of games: Super Mario World, Sonic the Hedgehog, Mega Man, Super Metroid, Contra, Metal Slug, and practically all rest platformers 16- bit epochs.

How this is works.

Information about the card is recorded and stored in the same way as in the first type, the difference lies in the interaction of the characters with the game background. The character's hitbox is a bounding rectangle aligned along the coordinate axes (AABB, or, more simply, a rectangle that does not rotate). Typically, the bounding box is an integer multiple of the cell size. Standard measurements: one cell in width, and one in height ( little mario rolled into a ball Samus), two (large Mario, Mega Man, Samus in the "sitting" position) or three cells (Samus in the "standing" position). In many cases, the character's own sprite is larger than the logical hitbox, as it is more visually acceptable. The gameplay thus becomes "fairer", because it is better for the player to be able to avoid being hit by the enemy, when in theory it should be, than to receive damage when a projectile passes by on the screen. In the picture above, you can see that the sprite resembles a square in shape (in fact, it is 2 cells wide), but at the same time has a rectangular hitbox (1 cell).

If we assume that there are no inclined and one-sided platforms on the map, the algorithm is simple:

1. Sequentially step the movement along the X and Y axes. If you then plan to enter slopes, start staking out from the X axis, otherwise the order does not really matter. Then, for each axis:

2. Find the coordinate of the forward edge (leading edge). For example, when moving to the left, this is the X coordinate of the left side of the bounding rectangle, when moving to the right, the X coordinate of the right side, when moving up, it is the Y coordinate of the top side, and so on.

3. Determine which grid lines the bounding rectangle intersects with - this will give you the minimum and maximum values ​​for opposite axes (i.e. when moving horizontally, we will find the numbers of the vertical cells with which we intersect). For example, if you move to the left, the player crosses rows 32, 33 and 34 (that is, cells with coordinates Y = 32 * TS, Y = 33 * TS, and Y = 34 * TS, where TS = cell size).

4. Follow the grid line in the direction of travel until you find the nearest solid obstacle. Then walk over all the moving objects, and identify the nearest obstacle among them in your path.

5. The minimum of two values ​​(the distance to the nearest obstacle and the distance you were going to move initially) will be the value of the distance we move the character.

6. Move the player to new position... From a new position, repeat the steps, and so on.

Slopes

Mega man xwith marked cells tilt.

Slopes (the cells indicated by the green arrows) can be difficult, since they are essentially obstacles, but the player can still partially enter these cells. They also assume that the Y coordinate of the character changes depending on the movement along the X axis. To avoid problems, you need to make the cell contain the “floor y” parameter of each side. If in the coordinate system designate the upper left cell as (0, 0), as shown in the figure, then the point (0, 3) is the cell located slightly to the left of the character (the first slope cell); the cell on which it stands is point (4, 7), then (8, 11), and (12, 15). Then the cells begin to repeat, from a new point (0, 3) and further, and then the descent becomes steeper and consists of two points (0, 7) and (8, 15).

Cell {4, 7} v details

The system that I will now describe allows you to enter arbitrary slopes, although, for purely visual reasons, these two types of slopes are most common and include only 12 cells (6 indicated above and their mirror images). The collision algorithm for horizontal movement changes as follows:

■ Here you must first shift along X, then along Y.
■ We consider that the collision with the slope cell occurred only if its nearest edge is high (in the picture - the lower y coordinate). This will prevent the character from falling through the slope with opposite side.
■ It may be useful to prevent slopes from ending “halfway” (ie at cell (4, 7)). This limitation is used in Mega Man X and many other games. If this is not done, you may run into more difficult situations in which the player will try to climb from the bottom of the descent cell. These situations are solved, for example, by preprocessing the level with the marking of all such conflict cells. When defining a collision, set an additional condition: the player's bottom Y coordinate must be larger (lower on the axis) than the protruding edge of the cell (tileCoord * tileSize + floorY).
■ A regular obstacle cell adjacent to the incline cell on which the player is positioned in this moment time should not be considered an obstacle if it is directly connected to the slope, i.e. if the character (namely, its lower middle pixel) is located on a slope cell of type (0, *), skip the cell to the left, and if on (*, 0) - skip the cell to the right. You may need to apply this for more cells if the character is wider than 2 cells - you can just skip a whole row if the player is heading towards the top of the slope. This is done so that the player does not get stuck in the cells (highlighted in yellow in the figure) while moving up the slope, since his foot will continue to be on the “surface” at the moment of contact with a solid cell.

For vertical movement:

■ If downhill travel is driven by gravity, ensure that the minimum gravitational displacement is compatible with the actual downhill and horizontal speed. For example, on a 4: 1 slope, as in the case of cell (4, 7), the gravitational displacement should be at least 1/4 of the horizontal velocity (if rounded), and on a 2: 1 slope (cell (0, 7 )) - at least half. If these values ​​are not set, the player will continue to move horizontally for some time after leaving the ledge until gravity brings him down. This will cause the player to bounce on an incline instead of smoothly downhill;
■ As an alternative to gravity, you can calculate how many pixels above the floor level the player was before moving, and how much this value changed after. Then you should adjust the position of the player so that these values ​​match. For calculations, you can use the formula from the next paragraph.
■ When moving down, instead of the top edge of the tile, the bottom coordinate of the tile on the given vertical should be taken beyond the contact boundary. To calculate this coordinate, define a value between that represents the player's position along the cell (0 = left, 1 = right), then use that to linearly interpolate the floorY values. The program code will look something like this:
float t = float(centerX - tileX) / tileSize;
float floorY = (1-t) * leftFloorY + t * rightFloorY;
■ When moving down, if there are several cells with a common Y coordinate (for example, the character is between the descent and a regular solid tile), then create a collision with the slope and ignore all others, even if other cells are closer. This will ensure the proper behavior of the player near the edges of the slopes: he will "fall" into a virtually solid cell due to the fact that the slope begins here.

Unilateral platform

Super Mario World: Left Mario passes through unilateral platform, on right costs on her the same.

A one-sided platform is a platform on which the player can stand and through which, at the same time, it is possible to jump. In other words, they count as an obstacle if you are already on it, and do not count under any other circumstances. The previous sentence plays a key role in understanding the algorithm of their behavior. It is modified as follows:

■ On the X-axis, the cell is never "solid";
■ On the Y-axis, a cell is an obstacle only if the player was entirely above it before the start of the movement, that is, the player's bottom coordinate was at least one pixel above the top coordinate of the one-sided platform. To ensure this condition, it is advisable to maintain the starting position of the player before starting the movement.

You may find it a good approach to determine that a collision has occurred when the player's vertical speed is positive (for example, when falling). However, this approach is incorrect: the player can jump so that he actually crosses the platform, but does not jump to its top and, therefore, must fall down. In this situation, the player should still pass through the platform, although the vertical speed will be positive.

In some games, it is possible to “jump down” from such platforms. There are few ways to set such a possibility, but they are all relatively simple. For example, you can turn off one-sided platforms for one frame and make sure that the vertical speed is at least one - so, on the next frame, the player will be out of the contact zone. Alternatively, you can set an exceptional condition in which the player stands on one-sided platforms and, if this condition is met, manually move the player one pixel down.

Stairs (vertical)

Mega Man 7:visible boundaries cells, highlighted cell stairs and Staircase hitbox player (v red frame).

Ladders may seem tricky to implement, but they simply represent a different state of the character: while on a ladder, the player ignores almost the entire collision system and introduces a new set of rules instead. Usually, the width of the stairs is one cell.

The transition to the "ladder" state is possible in the following ways:

■ The player's hitbox crosses the stairs at floor level or in flight, the player presses the "up" key (in some games, the transition is also possible by pressing the "down" key);
■ The character stands on the upper "staircase" cell (which is most often in fact a one-sided platform so that you can walk on it from above), the player presses "down".

Thus, there is the effect of instantly aligning the player's x-coordinate with the ladder. To move down from the top of the stairs, you need to move the y-coordinate of the character so that the player is inside the stairs. Some games introduce an alternate hitbox for these situations, tracking the player's position within the ladder. For example, in Mega Man, it is a single cell that matches the top cell of the character's sprite.

You can leave the stairs in the following ways:

■ The player reaches the top of the ladder. Here, a special animation is usually turned on, in which the player moves a few pixels up along the Y-axis and is above the stairs in a standing position;

■ The player reaches the bottom of the hanging ladder. In this case, the player simply falls, although in some games this is not allowed;

■ The player moves left or right. If there are no obstacles, the player descends the stairs in the appropriate direction;

■ The player jumps. Some games allow you to release the ladder this way.

While on the stairs, the player's actions are limited to up and down movement, and it is also sometimes possible to attack.

Stairs (oblique)

Castlevania: Dracula X.Visible boundaries cells.

This type of staircase is rare. Basically, inclined stairs are inherent in the games of the Castlevania series. Their implementation is largely the same as that of regular ladders, with a few exceptions:

■ The player's step is either a whole cell, or half a cell (as in Dracula X);
■ During each "step" on the stairs, the player moves simultaneously along both axes by a predetermined value;

In other games, there are stairs that behave like slopes - here they serve for purely visual purposes.

Moving platform

Super Mario World

Moving platforms are fairly easy to implement, although at first it may seem different. Unlike conventional platforms, they obviously cannot be represented by fixed cells. Instead, they must be an ABBA rectangle (the one that does not rotate). From the point of view of defining contact, these platforms are in fact ordinary obstacles, but if you do not introduce certain changes, they will be very "slippery" (that is, move, constantly crawling out from under the character).

There are several ways to solve this problem. Consider an algorithm like this:

■ Before moving anything on the map, set the condition under which the player is considered to be on the moving platform. Let the program make sure that, for example, the lower middle pixel of the character is located exactly one pixel above the surface of the platform. If this is true, save the platform pointer and position to the character
■ Move all moving platforms one step. Be sure to do this before moving characters and other objects;
■ For all characters standing on a moving platform, determine the delta-position of the platform, that is, the total movement made by it along each axis. Then, move the character according to this value;
■ Move the characters further as usual.

Other peculiarities

Sonic the Hedgehog 2

There are games that use much more complex and unique techniques, and especially in this regard, the Sonic the Hedgehog series stands out. These techniques are beyond the scope of this article, but may serve as material for future ones.

Type of #3: Bitwise mask

It is similar to the previous one, only for collision detection, not large tiles, but pixels are used. This technique allows for improved detail, but it also increases execution complexity and memory usage. The level editor looks more like paint. Tiles are often not used to create graphics, so each level may require large, intricate, individual images. Due to all this, this technique is not common, but with its use you can achieve better results than types based on the cellular principle. It is also suitable for creating dynamic environments, such as destructible terrain in Worms - you can "paint" in a bitmask and thus change the level model.

The game Worms World Party with destructible terrain

Examples: Worms, Talbot's Odyssey

How this is works

The basic principles are similar to those described for the type "based on tiles with anti-aliasing" - you can simply count each pixel as a tile (1px wide), apply the exact same algorithm and everything will work as it should, with one important exception - slopes. Since slopes are now indirectly determined by the arrangement of nearby cells, the methods described above do not work, and it becomes necessary to apply a more complex algorithm. Other aspects, like stairs, are also more difficult here.

Slopes

Talbots Odyssey:over images superimposed bit mask collisions.

Generally speaking, it is because of the slopes that this development method is very difficult to work with. Unfortunately, most often you simply cannot do without them, otherwise it makes no sense to take on this technique. Often it is generally used only because of the peculiarities of the slopes.

Here is a general outline of the algorithm used in Talbot's Odyssey:

■ Find the distance by how much you need to move along each axis;
■ Steps must be carried out on each axis separately, starting with the one with the greatest displacement;
■ To move horizontally, the player's bounding box (AABB) must be shifted 3 pixels up (so that he can climb the slopes);
■ Perform a collision check by checking all the obstacles and the bitmask itself, and determine how many pixels the character can move before colliding with anything. Move it to this new position;
■ If the movement was horizontal, move up as many pixels as necessary (usually no more than 3) to compensate for the slope;
■ If at the end of the movement at least one pixel of the player overlaps the obstacle, cancel the movement along this axis;
■ Regardless of the previous condition, apply the algorithm for the second axis.

This system does not distinguish between moving down as a result of a descent and as a result of a fall, so you may need a frame counter. It determines how many frames must pass from the moment the player last touched the floor for the character to jump or change animation. In Talbot, this value is 10 frames.

It is also difficult to accurately calculate the number of pixels a character can move before touching anything. There may be other complicating factors such as one-sided platforms (see “smooth tiles”) and sliding down steep slopes (quite difficult and beyond the scope of this article). In general, this technique requires fine tuning, debugging, and is inherently less stable than tile-based approaches. I can only recommend it if you really need detailed terrain in your game.

Type # 4: Vectors

This method uses a vector approach (lines and polygons) to define the boundaries of the collision area. Despite the complexity of the implementation, it is gaining more and more popularity due to the ubiquitous use of physics engines such as Box2D. The vector method has the same advantages as the bitmask, but without a lot of memory and using a different way of editing levels.

Braid (level editor) with visible layers (top) and ... polygons (bottom)

How it works
There are two main ways to achieve this:
1. Implement motion and collisions in a way similar to a bitmask, but using polygons to compute deviations and get the correct slope.
2. Use a physics engine (eg Box2D)
Obviously, the second method is more common (although I suspect Braid is the first), because it is simpler and allows you to do various things with dynamics in the game.
Unfortunately, you have to be very careful when you go this way, so as not to turn the game into a regular physical platformer.

Composite Objects

This approach has its own problems. Sometimes it can be difficult to tell if a player is standing on the floor (due to rounding errors), hitting a wall, or sliding down a steep slope. When using a physics engine, friction can be a problem if you want to increase it at the feet and loosen it at the sides.

There are various ways to solve this problem, but the most popular solution is to divide the character into several different polygons: so, in addition to the torso, you will have a narrow rectangle for the feet and two narrow rectangles for the sides, another for the head or some other similar combination. Sometimes they are tapered to avoid obstacles. They have different physical properties, and the engine intersection detection functions are used in this case to determine the state of the character. To receive additional information sensors can be used (non-colliding objects used only to check for overlap). They can be used to determine if we are close enough to the floor to jump, or if the character rests against a wall, etc.

General Provisions
Regardless of the type you choose (except, perhaps, type 1 #), a few general provisions apply to them.

Acceleration

Super mario World (low acceleration), Super Metroid (medium acceleration), Mega Men 7 (high acceleration)

One of the factors affecting the playability of a platformer is the presence of character acceleration.

Acceleration Is the rate of change of speed. If it is low, the character accelerates for a long time or slows down for a long time when the player releases the button. This makes the movement of the character "sliding", which creates difficulties for the player. This movement is commonly associated with the Super Mario series. When acceleration is high, the character accelerates to maximum in seconds (or instantly) and stops just as quickly, which leads to very fast, "jerky" joystick control, as, for example, in Mega Man. I believe that Mega Man actually uses unlimited acceleration, i.e. you are either running at full speed or standing still.

Even if the game does not have acceleration in horizontal movement, it is most likely used when jumping in an arc, otherwise, they will be in the form of triangles.

How it works

Implementing acceleration is actually very simple, but there are a few pitfalls to keep in mind.

1. Determine the speed xTargetSpeed. It should be 0 if the player does not press the joystick buttons, -maxSpeed ​​if the Left button is pressed, or + maxSpeed ​​if the Right button is pressed.
2. Determine the yTargetSpeed ​​value. It should be 0 if the player is standing on the platform. Otherwise + terminalSpeed.
3. For each axis, increase the current speed to the target speed using either weighted average or incremental acceleration.

Two types of acceleration:
Weighted average: a number (“a”) from 0 (no movement) to 1 (instantaneous acceleration).
Use this value to insert between the target and the current speed, and set the result as the target speed.

vector2f curSpeed ​​= a * targetSpeed ​​+ (1-a) * curSpeed;
if (fabs (curSpeed.x)< threshold) curSpeed.x = 0;
if (fabs (curSpeed.y)< threshold) curSpeed.y = 0;

Additional acceleration: We figure out which direction to add acceleration (using the sign function, which returns 1 if the argument is greater than zero and -1 if less), then check to see if we are out of bounds.

vector2f direction = vector2f (sign (targetSpeed.x - curSpeed.x), sign (targetSpeed.y - curSpeed.y));
curSpeed ​​+ = acceleration * direction;
if (sign (targetSpeed.x - curSpeed.x)! = direction.x)
curSpeed.x = targetSpeed.x;
if (sign (targetSpeed.y - curSpeed.y)! = direction.y)
curSpeed.y = targetSpeed.y;

It is important to add acceleration to speed before the character moves, otherwise you will introduce lag to the character input.

When a character hits an obstacle, it is best to reduce his speed to zero.

Jump control


Super Metroid, Samus Cosmic Jump (using Screw Attack)

The ability to jump in a platform game comes down to determining whether the player is on the ground (or whether he has been on the ground for the last n frames). In this case, the character is given a negative initial speed y speed (corresponds to the physical term "impulse"), the rest is a matter of gravity.

There are four main ways to control jumps:

1. Pulse: Used in games like Super Mario World and Sonic the Hedgehog. The jump retains the momentum (in game jargon, speed) that the character had before it. In some games, this is the only way to influence the jump arc - just like in real life... You don't need to specifically implement anything here.
2. Air acceleration: Maintain control over horizontal movement in the air. In reality, this is impossible, but in games this function is very popular, as it makes the character more controllable. It is found in almost every platform game, with the exception of games like Prince of Persia.
Generally, acceleration drops significantly in the air, so momentum is important, but some games give you full aerial control. This is usually done by adjusting the acceleration parameter while you are in the air.
3. Lift control: another physically impossible but extremely popular action, as provides more control over the character. The longer you hold the jump button, the higher the character jumps. This is usually done by gradually adding momentum to the character (although the momentum can also gradually decrease) or by resisting gravity as long as the button is held. A time limit is imposed if you do not want the character to jump endlessly.
4. Multiple jumps: In some games, the jumped player is allowed to jump again, possibly unlimited (like Jump to Space in Super Metroid or flying in Talbot's Odyssey) or a limited number of times before touching the ground (“ double jump"- the most common option). This can be achieved with a counter that increases the value by one after each jump and decreases when you are on the ground (be careful when updating it, otherwise you can reset it right after the first jump). Further jumps are possible if the meter reading is low. Sometimes the second jump is shorter than the initial one. Other restrictions may apply - Jumping into Space is only possible after you have performed a spin jump and started to fall.

Animation and control

Black Thorne, character animation slows down before shooting backwards (Y button)

In many games, your character's animation will play until the required action is actually performed, at least in games based on sharp movements. This will frustrate players, so DON'T DO IT! You should prioritize animation when it comes to jumping and running, but if you care, limit yourself to animation so that the action takes place independently of the animation.

Smooth movement
The correct solution is to express the position of the characters in integer data, as the movement becomes faster and more stable. But if you use integer data for everything in a row, you will end up with jerky movements. There are different approaches to overcome this. Here is some of them:

· Use floating point numbers (float) for all calculations and storing position data, and sum up in integers whenever you render an image or calculate collisions. Quick and easy, but as you move away from (0,0), accuracy starts to be lost. This probably doesn't matter if you have a very large playing field, but it should be kept in mind. Otherwise, the double type is used.

· Use fixed-point numbers for all calculations and positions, and sum again in whole numbers when rendering an image or calculating collisions. Less accurate than float and with a narrower range format, but in this case the precision is always the same, and on some devices it is faster to work with (especially slow work with floating point numbers on mobile devices).

· Store position data as integers, but keep the remainder in float. Calculate the delta motion as a floating point number, add the remainder to it, then add the integer part to the position and the fractional part to the remainder field. In the next frame, a value will be added to the remainder. The advantage of this method is that you use integers everywhere except for motion calculations, which ensures that there are no floating point complications and improves performance. This method is also suitable if in your framework the position of the object must be expressed as an integer, or if a float, but the same position is used for drawing to the screen. In this case, you can only store integer values ​​so that rendering is always pixel-aligned.

Testing a fresh 2D kit from Unity and detailing the process of creating our first platformer

send

In mid-February, the creators of Unity released a 2D-kit - an unusual application created for all novice game makers. With its help, anyone can assemble a platformer without bothering to write long code. The program code, models and animations were prepared by the developers, and you just have to delve into the manipulation with them and create the game that you have always dreamed of (if it is, of course, a two-dimensional platformer). We tested 2D-kit, created own level and using his example, we tell you how to quickly get used to the engine and release the first game.

Where to begin

If you have never run Unity or, for some reason, you are hearing about it for the first time, we will briefly explain the basics of the interface. You can freely move all windows and tabs to any place convenient for you, but initially they are located as follows: on the left side there is a hierarchy column that shows all objects in the scene; the scene itself is located in the center, and to the right of it the inspector window shows the properties of the selected object. Below you will see the project menu and the materials that are assigned to it. Now let's figure out what is different 2D-kit from the normal launch of Unity.


In the start menu of the engine, you will have a choice: start new project or go to the training tab, and there run the downloaded 2D-kit. Choosing the second option, you will see the materials of the game instead of an empty canvas and you can create with literally two clicks. First you need to create a scene: find above Kit Tools and select the tab Create New Scene.

The scene was created, a lot of incomprehensible objects were immediately lined up in the hierarchy, but the main thing was that a heroine appeared who would represent the player in the future. Its control is pre-configured, so there is no need to worry about it. For now, it is important to understand that the set of lines under the heading GameUtilities in the hierarchy must move with the main character so that at the start there are no control problems. So we get to the most essential: how to create levels?

On the menu Window there is a tab The palette Is a brush window that lets you paint the foundation. To go to the selection desired texture Press TilesetRockWaterBlockers and choose TilesetGamekit... Now you have two types of brush: grass and stone, imitating alien structures. Unfortunately, you cannot combine them, so plan the level in advance in the same style or mask the seam with improvised objects, such as an acid lake.

Environment creation

Now that you have drawn the level, you can move on to filling it. For this we need interactive objects, that is, such objects that will move by themselves and react to the player's actions. They're called Prefabs and are stored in the project menu folder of the same name. Opening it, you will see a new heap of subordinate folders - these are the types of items that you are free to use.

First of all, we recommend that you look into Interactables- This is the simplest type of item that is very easy to position and customize. For example, there is a "DestructableColumn" - a column that is destroyed when struck with a wand. We put it at the entrance to the cave. To add it to your level, simply drag the column from the folder onto the stage. Other items are added in the same way, such as "MovingPlatform".

You probably noticed that when adding objects, the right inspector window fills up with incomprehensible settings at once, and some red path was marked next to the moving platform. Don't worry, we'll deal with them quickly now. In fact, most of the icons, sliders and numbers are not useful to you in the first step. The main thing is to notice the button Add Node in the platform settings - it adds a new point in the path of the island. All points can be moved with arrows along the coordinate axis. The problem is that initially the platform moves back and forth, and if you form a square, then you naturally want the island to move in a circle. To do this, in the submenu Moving Platform (Script), in the same place as Add Node, you need to select an inscription BACK_FORTH, which means "back and forth", and change it to LOOP which means "in a circle".

Now you have moving platforms, like in some Mario... Moreover, you can rotate and enlarge them by selecting the desired marker in the upper left corner. In order for an object to move along with the platform, for example, thorns, you need to drag it directly to the platform in the hierarchy list. Already on the basis of this, a good game is being formed, but we will go even further.

Now let's add something more difficult to our scene - a feisty NPC. Enemies are in the folder Enemies, which lies there, in Prefabs... It doesn't matter who you throw on the level: a blue or a pink monster, take a close look at its settings. The very first one - Transform- changes the position and size of the object. The second is Sprite Renderer- allows you to mirror it in different coordinates; to do this, check the box next to X or Y... And very far below is Enemy Behavior that controls the behavior of the monster. The most important lines in this window are View Fov and View Direction... The first determines the area of ​​view of the enemy, and the second rotates it. You can also adjust the gaze distance in stitching View Distance by simply specifying the desired number.

Interactive objects

At this stage, you are able to create your own level with hidden caves, flying islands and different types of enemies, all without a single line of code. It's time to complicate the assembled scene with more complex, interconnected objects. We will install a door that will open thanks to a button located in the floor or on the wall. To do this, we need a door lying in a folder already familiar to us. Interactables, but we will not do anything with it. The main work will go on the button PressurePad, which should open the way.

Its location can be anything; setting is important for us Pressure Pad (Script), which is hidden deep below the inspector. It has a small window On Pressed () with a plus sign at the bottom. This plus adds the reaction of anything in the scene to a button press. Since we need the door to open, it is the door that needs to be dragged from the hierarchy window to the line under the caption Runtime only.

We have linked the button and the door together, but have not yet determined what this connection will be. In order to assign it you need to go to the submenu No Function and in the list that will drop out when you hover over Animator, select Play (string)... Voila! Try the result just by clicking on the button Play located above the stage.

In a similar way, completely different objects are connected, for example, teleports, which transport the player both inside the scene and to a completely different location. You will need them in order to create levels of different content and atmosphere. For example, one will be a dark cave, another will be a jungle, and the third will be a tall and light temple.

Connecting transition points is even easier than a door with a button. They are in the folder Scene Control, which, like all other folders with objects, lies in Prefabs... There we need an object TransitionStart, which is the transition point. If you want to create a teleport inside the scene, then you will need two such points, one of which must be renamed to TransitionEnd(this is done in the top line of the inspector).

Be patient, because now you will have to work closely with the departure point settings, which are called Transition Point (Script)... The first field tells us which object will be carried over. Therefore, you need to drag the heroine from the hierarchy into it ( Ellen).

The second line is responsible for the type of transition: inside the zone or outside - it's like a flight within the country or abroad. If you chose Inner Travel, then drag to a new field TransitionEnd- so you indicate where the transition will take place. Usually the movement occurs automatically, so the next line is the inscription On Trigger Enter, but you can change this as you wish, as we did at the ship. Don't forget to also drag Ellen into settings TransitionEnd otherwise the miracle will not happen.

If you move to another location, then you first need to select it, and then the transition point, because there can be several of them on the level, and all of them are marked with letters in alphabetical order. By the way, the destination on the other level is an object called TransitionDestination, which is located there, in Scene Control... Don't mix it up!

Now you know almost everything you need to play a full game. There are only small secrets and tips that we learned in the process of creating this tiny level.

The first secret confined in the portal, sparkling at the very beginning of the location. We will not reveal what is inside, but you yourself can figure it out, if, of course, you get into it.

Second secret Is the design. Trees, grass, pillars, statues and other decorative ornaments are located in the folder Sprites which lies inside the folder Art. There is nothing secret about this, but you can replenish the library from the Unity store or draw yourself in Photoshop... They can either hide behind other objects or overlap them - the number in the line is responsible for this. Order in layer.

Third secret- music. It's quite simple: you throw your soundtrack into a folder. Music and then drag it into settings BackgroundMusicPlayer.

AND last secret- death. If you are building open locations in which the player can easily fall off a cliff, you need to prepare a penalty for him, otherwise he will continue to float endlessly. Invisible death is best suited for this. Create an empty object and attach to it Damager (Script)... Stretching it all over the map, you will receive that very invisible death, from which the player will die, falling from a height.

Our level is available... You can download and try it out to see what the editor is capable of. The game also has developer levels built into the game, which fully reveal the possibilities of the assembly.

You can download the engine from this link, and find more detailed instructions on English language- by this . Happy development!

We hope that our guide was useful to you and encouraged you to create your own masterpieces!

Good day! Before proceeding directly to creating a 2D shooter, I would like to blur this article a little with an introductory part. So, now you are reading my first article on this site. Honestly, I'm not a pro in game development and so far I work mainly with Game Maker in order to get my hands on serious projects. So, in this article, or rather in this lesson, I will try to provide you with some of my knowledge in the field of game development. Specifically, I'll tell you how to make the simplest 2D Contra-style shooter.

OK. Let's start creating a game. First, we need to stock up on sprites:

player_go_right and player_go_left- sprites of the player's movement to the left and to the right (animation).


gun_right- sprite of the gun pointing to the right. For this sprite, set the center of rotation on the handle as shown in the screenshot.
bullet_spr- bullet sprite. No special criteria.
wall_sprite- wall sprite. Preferably 32x32.

When the sprites are ready, it's time to create the necessary objects and naturally tweak them. Let's start with the simplest thing - the wall. Create an object wall_obj and assign a sprite to it wall_sprite... Also for this object, set the property Hardness (Solid).

Next, let's move on to the bullets. Create bullet_obj and assign it bullet_spr... So that in the future the bullet behaves more naturally in the event Collision with wall_obj add action Destroy Instance ()... If you wish, you can increase the depth of the bullet.

All secondary objects are ready. Let's get down to the hardest part. Create a player object player_obj and assign a sprite to it player_go_right or player_go_left... For player_obj in event Create enter script ():

200? "200px": "" + (this.scrollHeight + 5) + "px"); ">
image_speed = 0
right = true
gravity = 1

This script starts gravity for the player and reduces the speed of the sprite to 0. Also, with this code, we we introduce a new variable right, with which we will further determine the direction of the player.

Let's move on to control. In the event Step write the following code ():

200? "200px": "" + (this.scrollHeight + 5) + "px"); ">
// Move to the right
if keyboard_check (vk_right) then
hspeed = 5

// Move left
if keyboard_check (vk_left) then
hspeed = -5

// Isn't it empty under your feet? Is the up button pressed?
if (not place_free (x, y + 3)) and (keyboard_check (vk_up)) then
vspeed = -15 // Jump
// If nothing is pressed
if keyboard_check (vk_nokey) then
begin
hspeed = 0
image_index = 0
image_speed = 0
end;

This script will allow the player to walk left, right and even jump.

So, there is gravity, there is control, but there is no support. Add an event to make the prop appear Colliding with wall_obj and inject into this event:

200? "200px": "" + (this.scrollHeight + 5) + "px"); ">
vspeed = 0

Well, almost everything is ready. The player can already safely jump on the platform. But unfortunately there will be no motion animation. To fix this in an event press enter the script:

200? "200px": "" + (this.scrollHeight + 5) + "px"); ">
sprite_index = player_go_left // Change the sprite
image_speed = 0.2 // Sprite speed
right = false // The player is not rotated to the right

And into the event press enter a similar script:

200? "200px": "" + (this.scrollHeight + 5) + "px"); ">
sprite_index = player_go_right
image_speed = 0.2
right = true // Player is turned right

It remains only to teach the player to shoot. To begin with, for this purpose, we will give him a weapon. For this purpose, enter into the event Draw following script:

200? "200px": "" + (this.scrollHeight + 5) + "px"); ">
// Determine the direction of the weapon
rotate = point_direction (x, y, mouse_x, mouse_y);

// Is the player turned right?
if right = true then
gun_x = x + 15 // Change Gun X Position
else
gun_x = x + 1

Gun_y = y + 15 // Change the position of the gun in Y

Draw_sprite (sprite_index, image_index, x, y) // Draw the player
draw_sprite_ext (gun_right, 0, gun_x, gun_y, image_xscale, image_yscale, rotate, image_blend, image_alpha) // Draw the gun

I would like to draw your attention to the fact that gun_x and gun_y may have to be adjusted manually. if at the start of the game the weapon is not in the hands of the player.

If everything works great, let's continue. Add an event Glob Left Pressed and transfer the action to it Create Moving () with the following values:

Object = bullet_obj;
x = gun_x
y = gun_y
speed = 10
direction = rotate

So that is all! Feel free to place objects in the room and enjoy your game. By the way, don't forget to leave a comment.

Sooner or later, every person who more or less actively plays computer games, thinks "why not create your own game?" As a result, many people start learning the programming language, game design, and modeling. It should be borne in mind that everything is not so simple, and not everyone will be able to complete the training. To date, professional developers who know firsthand about all the difficulties have created special software packages that provide assistance in creating games.

Most of these programs use graphical representations of functions that are familiar to every programmer. As a result, it becomes possible to create a full-fledged 2D and 3D game using only the mouse. Tempting, isn't it? In fact, there are also disadvantages. The disadvantages include the fact that many such programs are narrowly focused in the genre, while others make it possible only to change the model, texture, background, music, movement, and in any case, variations are meant only on the theme of the same game. If you want to improve already existing game you will need mods and skins http://modminecrafts.com/ which fosters variety gameplay... Let's pay attention to programs that do not have the above disadvantages.

Today Game Maker has evolved from a simple editor of textures and models into a full-fledged functional environment for developing applications. The last eighth version makes it possible to work with 2D and 3D objects, you can also use standard and user-created libraries, etc.

This program is a friendly game constructor program. To create a game, you can use both a mouse and a classic keyboard. In addition, it is provided to support the import of models from different editors, for example, from 3D Max.

The disadvantage of the program, perhaps, should be attributed to the limited support for 3D, which was introduced in the sixth version. The next disadvantage is the required minimum knowledge of programming principles.

This program is intended for creating games, it is more complex than the previous program. This refers to the built-in model editor as well as the most powerful graphics engine which takes full advantage of the capabilities of OpenGL and DirectX. In addition, the tool includes separate programs for creating and processing shaders, landscapes, shadows, physics and sounds, while there is a rich library of scripts.

The disadvantage of the program, perhaps, should be attributed to the minimum knowledge of programming principles. At first it will not be so noticeable, but a little later you will need to use some programming skills.



Solitaire