# Question
Title: Are there alternative game distribution methods?
According this source, publishers account for about half the cost of a game's price to consumers. Could there be an alternative means of distribution that allows people to pay game developers more directly without a publisher?

i.e.: something like peer-to-peer torrents be used for distribution, while using something like Paypal to pay for keys to unlock the games?

# Answer
The alternative is to not use a publisher and sell the game directly.

This isn't a novel concept; it's been done forever. "Shareware" distribution and subsequent direct-sales to interested consumers was a popular early example. More recently, one might have seen games sold directly to customers via a developer's own website.

The services publishers provide aren't really necessary for success (although they certain improve one's odds). In the past, publishers were basically one's only real option to get console platform access and retail distribution channels. But the difficulty (and importance) of those perks has waned somewhat. It's arguably more possible than ever to successful self-publish a game, or in other words, to be *independent*.

Today there are also useful compromises available, as well; options that provide *some* of what a publishing deal might as well as only *some* of the long-run cost.

For example, distribution via Steam is *far* more open than distribution to yesteryear's major retail outlets ever was. Valve provides basically no other services on top of what everybody gets on Steam by default, but what they ask from you in return is similarly much less.

And companies like Kickstarter provide a more direct, grassroots mechanism of raising funding. Kickstarter doesn't ask for recoupment, they simply take a portion of the money you raise.
> 6 votes

# Answer
Yes, you can sell your game directly. In this day and age there are plenty of ways to do that. Getting physical copies into a brick and mortar store can still be difficult without a publisher. But 80% of game sales are digital nowadays, so this isn't a problem. And digital distribution channels have very low entry barriers nowadays.

Smartphone app stores have almost no quality control. Steam now accepts every game if you can caugh up a mere $100 (which you get back after you sold $1000 worth of copies). And selling through your own website is also much easier than it was 10 years ago. Most of these channels will skim a bit of your revenue, usually around 30%. But that's still much less than it would cost to go through a publisher (and your publisher would likely pay about the same fees to the distribution system. Rumor has it that some publishers negotiated better deals with various platforms, but they are unlikely to be *that* much better).

However, there are still reasons why developers might choose to work with a publisher. Many game developers are skilled in the craftsmanship of game development, but not so much in the business side. They know how to design 3d models, but not how to cut a good trailer. They know how to guide AI agents through a navigation mesh, but not how to guide gamers to their social media presences. They know how to write an NPC dialog, but not how to write a press release. They know how to balance the attack power of their units, but not how to find the optimal launch price for their game.

But a good publisher can fill these gaps.

A good game is nothing without good marketing. So if half of your revenue goes to the publisher, but you sell three times\* as many copies as you would without one, then your publisher increased your personal profit by 50%.

<sub>\*your mileage may vary</sub>
> 2 votes

---
Tags: publishing, distribution
---


# Question
Title: Persistent elements of offline players interacting with online players
For a long time I was thinking about a quite abstract game design problem, to which I didn't see a good solution yet. In abstract: How can a player have owned bases, units and infrastructure in a persistent multiplayer world, which can be interacted or attacked by other players, all the while the owning player may be offline and unable to give his input?

As a concrete example:

Assume you have a very large 2D world, in which you can build bases and have units guarding them. The bases can be visited or used by other players as automated trading stations, in which you represent the vendors. But the bases should also be able to be contested by hostile players - be it plundering or outright destruction.

How can I solve the issue that the owner of the base may be offline during an attack? Or that a player attacks at times where people are usually not online (sleeping, working, school)? Or that a player may actively go or stay offline in order to exploit potential protection mechanisms? How can I avoid forcing players to go online for a certain time at certain time ranges in order to maintain such protection?

Ideas (which are not satisfactory though):

1. Bases cannot be attacked in normal ways. People can send "troops" with a delay hopefully long enough to ensure the other player can give his optional input. The outcome of these battles is an automatically calculated result. Such sieges may go over multiple days.
2. Bases can only be attacked while their owners are online - or have been offline for too long. The explanation why those cannot be attacked is severely lacking though - given that trading should still be possible.
3. When a player intends to attack, both players somehow have to make an appointment in order for both to be online and to start the battle. This is a bad solution for obvious reasons.
4. Bases are inactive and invulnerable while their owners are offline or setting it inactive, and trading/other activities continue only temporarily based on the previous online/active time. This raises issues with visible bases and ongoing infrastructure, as they'd essentially need to be hidden or hideable, and other players may get bothered by it becoming inaccessible.

What other methodology does exist or could be employed in order to tackle this online-offline issue with persistent elements? I am also open for mathematical or systematic solutions. Be reminded that other players should be able to assist either side as well, and that their online/offline times would require some consideration as well.

# Answer
> 30 votes
Players have lives outside of the game, so you can not expect them to protect their property 24/7. You can be a bit more cruel about this when properties are not owned by individual players but collectively by large groups of players, because if the group is large enough then at least someone will be online most of the time. But this still creates a lot of unnecessary pressure for players to play more than they want to.

So if you want online PvP battles for the control of property, then you have to balance some conflicting interests against each other:

* The interest of the defender to defend the property when it is convenient for them and not lose property because their life outside of the game came in the way.
* The interest of the attacker to be able to conquer any property they want as long as they are strong enough to do so.
* The interest of the game to have both attacker and defender present for the battle, so you have a fair contest of skills.
* The interest of everyone to play your game when they want to and not neglect their life outside of the game.

In order to balance these interests, you need some game mechanic which allows players to **negotiate a date for when the battle is going to take place**. The negotiation mechanic must be designed in a way that it is in the interest of both parties to have the battle as soon as possible (so no party can win or grief by biding time), but still allows both parties some degree of control in order to find a time window where both parties are present.

---

A good subject for a case study in this regard might be **Eve Online**. Disclaimer: I read a lot about Eve Online, but I never played the game myself. So please write a comment if I misunderstood something.

Players can own stations, which still exist while the player is offline. Other players can attack these stations. But as soon as the station drops to 25% shield strength, it enters what is called Reinforced Mode.

While the station is in reinforced mode, other players can not damage it anymore, but the station also loses functionality and starts to consume a resource which can not be replenished while in this mode. When there is enough of that resource in stock, then it can last for more than a day.

So when the attacker wants to take the station, they either need to wait until the station runs out of resources or until the owner shows up to defend it.

The effect of this game mechanic is that the defender decides when to fight for the station. The attacker is the one who needs to stay online and prevent the defender from refueling. But it is still in the interest of the defender to react early, because while the station is reinforced, the station consumes resources without doing anything productive.

---

A mechanic I have seen in another MMO game (unfortunately I don't remember the name) was that the owner of a base can explicitly **set time windows in which they are vulnerable to attacks**. So the player can make sure that they are only attacked during times where they are usually online.

# Answer
> 21 votes
The text-based game 1000AD handles this by letting players be attacked as normal. The way the game works, you obtain one "turn" every 15-30 minutes (depending on game speed), and one turn lets you execute one month's worth of orders.

Thus, players tend to log in every few days with 500-1500 turns available, and spend the first few pulling down their defenses, the bulk of them handling research, expansion, or attack, and the last few setting up defenses (towers, siege weaponry, armies of various compositions).

In fact, this setup has lead (over the years) to a meta where it's considered very rude to attack someone while they're online!

You could thus possibly build mechanics in order to enforce that structure, something like for the first 30 minutes of each 24-hour period that you're logged in, you're invulnerable from attack, and *center* the game around attacking offline foes (or at least foes that have depleted their 30-minute window).

# Answer
> 9 votes
Automatic defense and high turnover. Let the base defend itself automatically without input from the player. Optionally allow the player to provide some form of support if they are active at the time. If a player loses their base(s), it should be easy enough to either build more or take over somebody else's (not *too* easy, but not insurmountable enough that their experience is ruined by losing their one of their bases while they were offline). This allows players who are actively playing the opportunity to actually do things (take over other players' bases) at the time they are playing, regardless of the status of other players (if the base owner is online and providing whatever defensive support is available, it's more challenging/fun), and prevents players from essentially taking bases out of play by making them inactive/protected or going offline forever (or logging in for 3 minutes a day/week to seem "active" and prevent it from being attackable).

You could also have two separate types of bases: one lightweight, low-cost (to build or conquer), easier to take base as described above, and a more heavyweight, protected base that has gameplay/scheduling measures in place to ensure (or make it more likely) that the defending player - and/or their allies - are active participants in battles for control. These would be more difficult/expensive to conquer/build. Once a player gains control of one, give them an option to allow a time (within the near future) that they expect to be playing and able to actively defend. Lock the time in so they can't keep pushing it into the future forever, but give them a window (maybe an hour or two) to make the decision, so if they have a job/family/travel/school/etc. they can choose a reasonable time. If they don't, just pick a time. Most players will understand that online multiplayer games need to cater to a wider audience than just them.

As far as preventing attacks on a base while it's still accessible for trade, there are plenty of options. The mechanics are simple enough, either don't allow attacking at all, make attacking excessively costly and very ineffective, or provide severe consequences for doing so outside the allowed window. You just need some world-/story-based justification for it:

* Environmental constraints make access by a single traveler/small caravan trivial, but access by an army impossible. Maybe seasons change or tides come/go or an event happens that opens up access to allow attacks
* Magic fairy protects for X years, then goes away
* Peace treaty forbids attacking, with swift and sever consequences (much larger military, advanced tech, magic, whatever) for some time
* This is all an elaborate online game, and this player is not available. Come back later :)

# Answer
> 8 votes
# Have you considered how it was done historically?

In most games that work similar to the type of game you seem to be developing (I've thinking Travian, Goodgame Empire and another one that got me so salty I can't be bothered trying to remember the name (but I remember that it had a shitty marketing technique)) combat is just a slow movement of troops, instant maths to resolve the combat and then a slow returning of troops. This is not how combat works! This is not how you would take a base historically! Conquering a fortified position is a very significant and time consuming task. Fortifications are much harder nuts to crack than game developers either realize or care to properly emulate.

My suggestion is going to make attacking another player a much larger investment of time and resources and it's also going to make defence more costly. However, it will also open up a whole lot more options for both sides. So much so that it might become a different game than you had originally intended.

## Besiege them!

Assuming that the defenders have any kind of wall protecting their base, then instead of instantly resolving combat when the attackers arrive, the attackers should set up camp around their target. In other words, they should besiege them.

The siege can be strengthened by adding more troops to it. This is one way to work together with your allies. However, this goes for the defender's allies as well who can send a force to relieve them.

## Supply issues will be the main driving factor

While the siege is in place the defender should be unable to gather resources as their access to the surrounding lands are cut off. Instead they start eating into their food and water\* stores until they are depleted as well as burning all their wood, coal and oil for heat, light and cooking. Once the food has run out the castle surrenders unconditionally.

Of course, the attackers also need to eat and feeding an army away from their home is no small task. Their choices for this is...
**1. Supply caravans.** This will be the main way to resupply your troops. You can provide it yourself, rely on an ally to provide it or negotiate for it with third parties (perhaps on the threat of besieging them next if they don't).
**2. Scavenge.** This will only be able to provide a little bit of food. It's not enough for a large force for a long time, but it works as a stop gap if you're having trouble with supply lines.
**3. Raiding.** This is more effective than scavenging, but it causes significant collateral damage to the surrounding land, which is bad if you intend to conquer the land for yourself. It also puts a limit to how much you can raid. Raiding can however be an end goal in and of itself as you weaken your enemy and then leave without actually trying to take their base.

Both scavenging and raiding the countryside requires the besieger to disperse some of their troops for some time, which is a perfect opportunity for the defender and their allies to sally out of the base to strike at the besieger's main camp or for allies outside the siege to pick off these smaller scavenging/raiding parties.

Supply caravans might seem like the superior choice now, and they should be, but you might want to make them vulnerable to interception in some way.

## Lots of choices!

You now have a siege in progress. This gives both sides a number of options to consider.

**Defender:**
**1. Wait...** Hope that the attacker will leave or that an ally will come and relieve you. If nothing happens your base's inhabitants will begin to starve when supplies run out and eventually surrender unconditionally. However, it takes two to have a siege and your besieger's troops are locked in their position unless they want to abandon the siege.
**2. Sallying out** is an option for the confident defender faced with an attacker who tries to bite off more than they can chew. End the siege early by defeating the besiegers while they are at their weakest.

**Attackers:**
**1. Wait...** As long as you have a steady stream of supplies to keep your troops from starving and disbanding you can win by just waiting out the enemy to consume theirs.
**2. Raid the countryside** to spite the enemy into attacking you or just to weaken them for future engagements.
**3. Assail the walls** to try to take the castle with overwhelming force. This is very difficult as a well-built fortification can be defended by a handful of men in the face of a many times larger foe.

**Both:**
**Negotiate!** You want to take the castle for yourself? Save yourself time and resources by offering the defender safe passage for their troops to leave. Your attacker wants resources? Offer to pay them off to break the siege. Maybe you and your allies can make an offer juicy enough that one besieger abandons his allies who then become easy pickings.

Maybe the besieger has some other purpose with the siege? Just about anything can be negotiated! Just make sure that there's no penalties for breaking a siege and going home or at least that they are much lower than the penalties for continuing the siege. You don't have to develop for all the possible outcomes from negotiation. Let the players resolve matters by sending each other messages and they will find ways to achieve the outcome within the game mechanics.

The siege mechanics should open up a lot of strategical options as well. Consider that the A-Alliance wants to conquer the B-Base of the C-Coalition. A-A will send their main forces to B-B. But they also send smaller forces to besiege some nearby bases. These forces aren't large enough to take those bases, but they are large enough to prevent the enemies in those bases from sallying out and coming to the aid of B-B. C-C has the option of sending forces from further away to relieve B-B or they could start dislodging the enemies around the surrounding bases to free up more troops and supply sources in preparation to finally relieve B-B. However, doing so may cause them to arrive too late. Choices are fun. Making the right choice is a challenge in and of itself and it turns warfare into more than just a contest of who can amass the most troops and throw them at sleeping players.\**

## Combat

Here's the crux of the matter. This is the part which the question focused on. This suggestion has so far lessened the problem by reducing the amount of combat by instead implementing a war on resources and time. This makes it more historically accurate, but combat is still an important aspect of the game and perhaps the most fun part for some players. How we deal with it depends how you intend for combat to work in your game. I will explore those options further down, but first we deal with the issue of players being overwhelmed by enemies they are not prepared for.

The siege mechanics deal with this by forcing an attacking enemy to first besiege the base. However, this is pointless if the enemy can just attack and overwhelm the defender right away. Sieges take time. Therefore, after arriving there should be a cooldown before the besiegers can attack. This time represents the time it takes to build ladders and siege engines\*** and preparing your forces for an attack. The cooldown should be longer the better fortified their enemy is and the timer should reset after every attempted attack. The defender might have a good view of the surrounding area and thus be able to tell how long it will take before their besiegers' cooldowns finish. Though the besieger doesn't have to attack as soon as the cooldown runs out. They can take their merry time just sitting about if they wish.

Also remember to give the defender a significant advantage! Attacking a fortified base is difficult and costly, which is why sieges were the overwhelmingly most common form of warfare historically (if you have a fortress then why not use it, you know?). This needs to be true in your game too or the whole siege mechanic becomes pointless. If the attackers doesn't need to commit a lot of forces to win a siege without waiting it out then it becomes too hard to defend against even an alliance of equal strength. You want your players to be able to stand a decent chance of defending against a superior enemy alliance or whomever attacks first will simply steamroll their enemies.

**Instantly resolved combat**
If you want the Travian style battles which are instantly resolved mathematically rather than having the players play the actual combat, then we're done here. The siege mechanics and attack cooldowns will give the defender and their allies plenty of time to react to the attacker. You don't need to be present for the actual battle, you just need to know ahead of time when a battle might happen so that you can prepare in time.

The movement of enemy troops and the attack cooldown should give enough time to make you aware of the threat unless you stay offline for a long period of time, like over 24 hours. As long as you check in once a day that should be enough, so that an entire alliance doesn't just decide to gang up on you while you're sleeping so that you wake up to having lost your strongest castle without any warning.\**

**RTS/TBS**
If you want combat that requires the players to move pieces on a field to actually play out the combat, then there's no way around it, your players *must* negotiate for a time to play out the combat. You should build a system around it and you may have to do some time jumping to achieve it.

For example, if the attacker suggests one time to fight and the defender suggests a later time then you shouldn't allow allies of the defender coming to relieve the siege in between those two times to take part in the combat, as that would be unfair to the attacker who wanted to fight before the arrival of more enemies. If the relieving ally tries to negotiate for combat with the attacker upon arriving, then that combat should not be allowed to be held before the combat which the attacker tries to negotiate a time for with the defender, because that would screw up the timeline and make the attacker fight with a weakened force in a battle that was supposed to take place before he was weakened.

In other words: the timeline of the battles, and thus the order in which they should be fought, should be determined by the initial time suggested even if that did not become the agreed upon time. Which players that can participate in the battle should also be determined by who was at the siege at the initially suggested time. Cooldown effects should only take the initially suggested time into account. Name the battles using the in-game time of the initially suggested time to make it more clear to the players.

If the sides have trouble organizing a time on which to fight and there are multiple fights being queued then that could lead to a series of fights which -according to in-game time- only takes a few days end up spanning a whole week or two IRL. This is fine though. By implementing the suggested siege mechanics you've already determined that your game will be the long con kind of game where things elapse more slow and steady.

After a battle the attacking or relieving force should get the option of retreating back home and thus cancelling their participation in upcoming battles. Or course, the defenders who are trapped in their base don't get a choice. If any player doesn't show up for battle at the predetermined time then their forces will be played by an AI. If no one shows up then the battle will be auto-resolved mathematically. This is so that upcoming battles can continue as expected. To prevent decimation of anyone's forces because they weren't there to cancel their upcoming battles you could implement a moral mechanic which causes troops to automatically retreat back home if they are poorly supplied and/or losing too many battles.

## Downsides?

If you implement the siege mechanic as suggested then you are probably going to end up with a game that works very differently than you had originally imagined. The overarching strategical part of the game has to become more slow paced for the siege mechanic to work and the players needs to put more consideration into their strategical actions. This will appeal to some players and it will turn other players off, just like with any major design decision. However, the important part of the question -how to prevent players who are sleeping or otherwise pre-occupied with real life from being curb-stomped by alliances of opportunistic hyenas\**- has been solved. Because you now have a game where players are fine if they just check in once a day or so due to the slower pace.

---

\*Water is an essential resource which is consumed in large amounts. If your base doesn't have a well then it will need to store a massive amount of water. Normally a base *would* have a well, but if you choose to build your base on an easily defensible mountain top then it might not be possible to find water.

\**Yes, I'm salty.

\***Unlike what most strategy games suggest, you don't actually drag siege towers and trebuchets with you from home. You build them at the siege with locally sourced lumber.

# Answer
> 5 votes
There are a few ways to deal with this, which can be combined as desired.

## Rate-limit attacks

This can be done in two ways:

**Any given player can only be attacked so many times during some time period (by anyone).**

If you don't allow outright destruction, the in-game explanation can be that there are only so many resources that can be taken from a base. If you do allow outright destruction, the best explanation might be honour - in-game it's viewed as disgraceful to "kick someone while they're down", and generals would outright refuse to launch such an attack.

It might make sense to incrementally do this, as in each successive attack on the same player reduces the rewards.

**Any given player can only attack so many times during some time period.**

This indirectly addresses the problem by limiting how many attacks can happen overall, thus also limiting how often any given player can be attacked (especially if you combine this with the locality suggestions below).

You can have attacks take some time, just have a delay between attacks (for soldiers to heal and rest) or have each attack cost some soldiers, which requires time to be replaced.

## Don't punish the defender (much)

The extreme here is that you only "punish" the attacker - their attacks cost them resources and soldiers, and they gain resources if they win, and the defending player isn't punished at all. This isn't really ideal for a "proper" multiplayer game, as you want your actions to affect others.

The middle ground is to "punish" the defender less severely than the attacker (they only lose certain types of resources, or they just lose *less* of it). *How much* less severely is something you'll need to play-test and optimise.

## Limit rewards from attacking weak or far away players

This is a less direct way to deal with this.

Attacks come with some overhead, which is dependent on the size of your army and the distance they must travel (you need to deploy your army, feed everyone on their way there, maybe lose a few soldiers to wildlife, disease or weather, etc.).

If you attack someone much weaker than you or far away, this overhead may very well be greater than the most you can hope to gain from such an attack (and you can also just refuse to execute such an attack for this reason).

The way this addresses the problem is by limiting who can attack who, which also limits how many times someone can get attacked.

You should be careful here to try to avoid situations where players can only attack a few small number of other players (or no other players).

## Note: coming online to find your base severely damaged is generally just not fun

That's not to say there's no way to make a fun game where this happens, but you should be careful here. I'd only really recommend this if you don't spend too long building a base from scratch to a point where you have something decent (e.g. a few minutes), you have many bases at the same time, thus losing one is not really a big deal, or losing your base still allows you to keep most of your wealth (have a global bank?), which will allow you to quickly get a decent base up and running again.

# Answer
> 4 votes
**Give allied players an incentive to defend on behalf of offline players.**

The MMO Dark Age of Camelot featured three warring player factions. A faction could gain advantages by capturing and holding bases in the PvP area. These bases were not owned by individual players; they gave their bonus to an entire faction and could be "claimed" by a guild for prestige.

You could come up with some variation on that for individually owned bases. For example, individual control of a base could give some bonus to a player's guild or faction, or players could be awarded XP for defending the base of an offline friendly player. Even just alerting online players that a friendly player's base is under attack could attract them there for PvP action.

# Answer
> 2 votes
Many MMO RTS games delay attacks based on distance, and limit the size of the attack based on supply lines. They also tend to grant defense bonuses to defenders that are not available to attackers. For example, attackers may be limited from sending only X troops, but defenders might have unlimited troops (e.g. as many troops as they can build), walls, traps, and so on, which can be upgraded.

Make it more difficult for attackers to succeed, and they'll consider their choices carefully, especially if there's also a real-time attack delay (e.g. an attack will take one hour to reach a target, and you'll lose those troops for defense during the duration). If practical, allow an option to send a push notification or some other means to alert offline users of an imminent attack. Attacks should also probably be rate-limited so that throwing a large number of smaller waves won't wear down an opponent that can't respond readily.

As mentioned elsewhere, reaching some critical threshold should trigger a protective mechanism of some type. For example, attacks become less effective, no further resources can be farmed from the target, auto-build troops or allow "wounded" troops to return to battle at some time. A defeated player should still have a decent chance of rebuilding after a severe attack.

# Answer
> 1 votes
OK maybe a contrarian answer here, and totally opinion based, but...

**Don't be ashamed to make people a slave of the game (and money)**

Basically, people will put an insane amount of time (and money) into a game if it's really good. So let the fear of consequence of offline attacks encourage more play time (and more money spending).

**Ideas**

Let bases for offline players suffer and defend very weakly. That encourages players to play more. Or conversely, may actually drive them away from your game.

Send players live alerts telling them they are under attack. This gets them to login and play, or decide to just let the base die.

Charge them extra money for levels of auto-defense that make offline-player bases a lot harder to attack.

**Caveat**

This will fail miserably if your game isn't good. If you can't get players addicted, this will fail. And it won't work for any kind of "casual" game.

# Answer
> 1 votes
How about a system where you have a certain amount of time to defend yourself, like a day or so.

Imagine this: Attacker sends the attack, and is told by the game something like "Your attack will be completed in 1 day" So they have to wait a day for the result of their attack.

The defender then gets a notification "You are under attack! You have 1 day to defend yourself!" So they can choose a moment of the day to defend themselves. If they don't however, it will be an automatic loss.

If you want to, you can even make the defender pay whatever currency you use to extend that time.

This would allow the both parties to act whenever they want, and allow the defender to fully prepare themselves for the attack, without allowing them to stall for much time.

However, this would also mean that the attacker can't act live, so they'd have a big disadvantage, meaning you should make attacking easier than defending.

This also causes problems if the defender cannot be active for the day. In that case, I'd implement an "AFK" feature, where you tell the game that you'll be inactive for some time, so the game will pause any progress from you during that time. Attackers may still be able to attack, but their attacks won't start until the defender is no longer "AFK".

# Answer
> 1 votes
**From a player perspective**

A pet peeve of mine, as a game player, is when a game tries to hard to get me to play more, so much so that the games advertise themselves as "addictive" are the ones I stay away from the most.

However, I realize that a game that doesn't get played is of no benefit to anyone, so games should provide some draw to continue playing, and play somewhat regularly.

Having said that, I would propose a combination of 2 elements:

First, an automatically adjusting difficulty on the AI for the offline player and, second, something like a "difficulty" setting manually selected by the players themselves, but related to how often they expect to be online.

Some examples:

If an offline player selected an "Easy" difficulty, then their base might be invulnerable for 24 hours after their last login. After that, their base can be attacked, but their are given a defending AI with a 99% success rate (or whatever number is reasonable for the specific game mechanics) at defending the base. That percentage then slowly decreases over time, for as long as the player doesn't log in, until it reaches 1% (or other applicable pre-set minimum). Logging in takes it back to halfway between the min and max AI levels, and slowly increases from there for each consecutive day they log in or for the length of each gameplay session, etc.

If an offline player selected a "Hard" difficulty, then their base might not have the 24 hour invulnerable period after their last login. Instead, the defending AI starts at 99% success rate (or whatever number is reasonable for the specific game mechanics) at defending the base, as soon as they log off. That percentage then slowly decreases over time, for as long as the player doesn't log in, until it reaches 1% (or other applicable pre-set minimum). Logging in doesn't take it back to halfway, but immediately starts slowly increasing for each consecutive day they log in or for the length of each gameplay session, etc.

Add intermediary "difficulty levels" and fine tune the numbers and concept as needed for the specific game mechanics and application.

# Answer
> 1 votes
Perhaps, to make the first option less unsatisfactory, you could have your deterministic battles play out in real time to the attacker (and to the defender if they're on), with the means by which the battles are decided being some manner of tactical 'programming' done by the players that gives both sides small scale agency without requiring active participation. Possibly also restrict battles to, say, one per day to make it more difficult to exploit flaws in a defender's strategy once it has been observed without giving them the opportunity to remedy them.

# Answer
> 0 votes
A few simple rules:

1. Ongoing sieges when logging off procede as normal.
2. Once all ongoing sieges have been resolved, apply a defensive boost that gradually declines over a set period.
3. Succesful attacks on other players (while online, obviously) increase this period, succesful attacks on you reduce it.
4. Once the defensive bonus decreases to 0, mark the player 'inactive' such that no interactions, positive or negative, are possible.

# Answer
> -2 votes
This sounds like a game I used to play called Ogame (initially a German game I think). You had a fleet which could only be attacked while in orbit around one of your planets, so when you went offline, you'd send it on an 8 hour (for example) round trip so that you know what time you had to log in to interact with it again.

Good player would determine when your fleet was due back and send theirs to arrive (hopefully) seconds before yours arrives back and crash it. You'd be left with the survivors.

---
Tags: game-design
---


title: DX11 Handle Device removed

text:
# Question
Title: DX11 Handle Device removed
I get the DXGI\_ERROR\_DEVICE\_REMOVED error on some machines. According to this (https://msdn.microsoft.com/en-us/windows/uwp/gaming/handling-device-lost-scenarios) MSDN article this can happen and it should be handled by your application.

I've managed to recreate the device but I'm unsure how to handle all content. It seems I have to create all vertex buffers and textures again, which essentially means I have to reload almost the entire scene. Is this really the correct way?

# Answer
> 4 votes
There are two places you can potentially get this scenario: When calling `ResizeBuffers` or `Present` and you get either `DXGI_ERROR_DEVICE_REMOVED` or you get `DXGI_ERROR_DEVICE_RESET`. In both cases, the video device and driver have been fully reset and all video resources are lost: render targets, textures, vertex buffers, index buffers, etc.

When this happens, you have two choices:

* Release all Direct3D and DXGI objects and start over including recreating all Direct3D resources
* Display an error to the user and tell them to restart

The first one is nicer for the user. Many games just return to the initial menu with an error message--assuming they don't just crash out like many of the less robust PC console ports do because you never encounter device removed on the Xbox One.

In general this shouldn't happen all that often, but it does happen. The most common reason is that a user leaves your game running when Windows Update installs a new driver in the middle of the night--or as is often the case, while someone is up way past bedtime gaming. The other case happens because of driver bugs or if you have a DirectCompute shader that is too complex to run within the timeout.

> For Universal Windows Platform apps, this scenario happens a little more often because it is used to handle migration of displays in laptops, tablets, phones, etc. This can also happen when you are resumed from a suspended state.

The best way to test your application is to open a Visual Studio Developer Command Prompt with administrator rights, and with your application running issue this command:

```
dxcap -forcetdr

```

Remember this will cause removed device for all apps running as it's system-wide including your debugger if you are using local debugging.

Take a look at the Direct3D Game VS Templates including the DeviceResources class for details on detecting and handling this properly.

```
    HRESULT hr = /*m_swapChain->ResizeBuffers(...) or m_swapChain->Present(...) */

    if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
    {
#ifdef _DEBUG
        char buff[64] = {};
        sprintf_s(buff, "Device Lost: Reason code 0x%08X\n",
        (hr == DXGI_ERROR_DEVICE_REMOVED) ? m_d3dDevice->GetDeviceRemovedReason() : hr);
        OutputDebugStringA(buff);
#endif
        // If the device was removed for any reason, a new device
        // and swap chain will need to be created.
        HandleDeviceLost();
    }
    else
    {
        // Any other failed result is a fatal fast-fail
        DX::ThrowIfFailed(hr);
    }

```

> Note this applies to both DirectX 11 and DirectX 12

# Answer
> 1 votes
While Chuck's answer is correct, you can cause a device removed error through mistakes in your own code. Stuff to look out for includes vertex indexes out of bounds and bad mapping of buffers.

Call `ID3D11Device::GetDeviceRemovedReason` to get a more detailed error code. If it returns one of the below, you may be the cause rather than a random driver upgrade:

* DXGI\_ERROR\_INVALID\_CALL: The application provided invalid parameter data. If you get this error even once, it means that your code caused the device removed condition and must be debugged.
* DXGI\_ERROR\_DEVICE\_HUNG: The graphics driver stopped responding because of an invalid combination of graphics commands sent by the app. If you get this error repeatedly, it is a likely indication that your app caused the device to hang and needs to be debugged.
* DXGI\_ERROR\_DEVICE\_RESET: The graphics device failed because of a badly formed command. If you get this error repeatedly, it may mean that your code is sending invalid drawing commands.

There are also these:

* DXGI\_ERROR\_DEVICE\_REMOVED: The graphics device has been physically removed, turned off, or a driver upgrade has occurred. This happens occasionally and is normal; your app or game should recreate device resources as described in this topic.
* DXGI\_ERROR\_DRIVER\_INTERNAL\_ERROR: The graphics driver encountered an error and reset the device.

Source: https://docs.microsoft.com/en-us/windows/uwp/gaming/handling-device-lost-scenarios

---
Tags: directx11
---


# Question
Title: Possible to yield a coroutine when it is taking too long to run?
Suppose I have a function that raycasts from (0,0,0) to every object in the scene. Sometimes the scene contains just a couple objects and sometimes it contains several hundred. Is it possible to setup the raycasting function in a way that ensures a good framerate? For example, within the "for" loop that shoots the rays could I somehow evaluate how much time has passed since the loop started and "yield return null" if the time in seconds is greater than the target time of each frame?

# Answer
> 8 votes
You can use `Time.realtimeSinceStartup` as reference for the time passed:

```
IEnumerator Test() {
    float startTime = Time.realtimeSinceStartup;

    foreach( Raycast rc in RaycastArray) {
        if( Time.realtimeSinceStartup - startTime < 0.01f ) { //Process stuff for 10 miliseconds
             //PROCESS A RAYCAST
        }
        else {
            yield return null;
            //Its important that the new time is assigned AFTER the yield
            startTime = Time.realtimeSinceStartup;
        }
    }
}

```

# Answer
> 3 votes
This is my version of Leo's answer. Pretty handy tool for splitting up the workload of certain loops to help with FPS. Bit hard to predict how long each loop will take though, but probably something I'll work on further.

```
IEnumerator ForOverTime (int fpsLimit, float timeLimit)
{
    float processStartTime = Time.realtimeSinceStartup;
    float frameStartTime = processStartTime;
    fpsLimit = System.Math.Max(0, fpsLimit);
    fpsLimit = fpsLimit == 0 ? 1 : fpsLimit;
    timeLimit = System.Math.Max(0f, timeLimit);

    for (int i = 0; i < 10000; i++)
    {
        if (Time.realtimeSinceStartup - frameStartTime < 1f / (float)fpsLimit ||  (timeLimit > 0f && Time.realtimeSinceStartup - processStartTime > timeLimit))
        {
            print("Do Something. " + Time.frameCount);
        }
        else
        {
            yield return null;
            frameStartTime = Time.realtimeSinceStartup;
        }
    }
    print("Time taken: " + (Time.realtimeSinceStartup - processStartTime));
}

```

---
Tags: unity, optimization, coroutines
---


# Question
Title: Calculating speed between two objects is not working when one of the objects is moving very fast. How can be solved?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Playables;

public class SpaceshipCutscene : MonoBehaviour
{
    public Transform player;
    public Transform[] npcs;
    public Transform console;
    public Camera FPSCamera;
    public Camera mainCamera;
    public Animator[] anim;
    public float rotationSpeed = 3f;
    public float distanceFromConsole;

    private bool moveNpc = false;
    private float sp = 0f;
    private float distance;

    // Use this for initialization
    void Start()
    {

    }

    private void Update()
    {
        distance = Vector3.Distance(transform.position, npcs[0].transform.position);
        if (moveNpc)
        {
            // Soldier 2 rotating and looking at player
            Vector3 dir = player.position - npcs[0].position;
            dir.y = 0; // keep the direction strictly horizontal
            Quaternion rot = Quaternion.LookRotation(dir);
            // slerp to the desired rotation over time
            npcs[0].rotation = Quaternion.Slerp(npcs[0].rotation, rot, rotationSpeed * Time.deltaTime);

            var dist = Vector3.Distance(npcs[1].position, console.position);
            if (dist < distanceFromConsole)
            {
                sp += Time.deltaTime;
                sp = Mathf.Clamp(sp, 0f, 1f);
                anim[1].SetFloat("WalkingSpeed", sp);
            }

            Vector3 dirToComputer = console.transform.position - npcs[1].position;
            dirToComputer.y = 0;
            Quaternion rot1 = Quaternion.LookRotation(dirToComputer);
            npcs[1].rotation = Quaternion.Slerp(npcs[1].rotation, rot1, rotationSpeed * Time.deltaTime);

        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (HoriDoorManager.doorLockState == false && distance < 5f)
        {
            if (other.gameObject.tag == "SpaceshipCutscene")
            {
                FPSCamera.enabled = false;
                mainCamera.enabled = true;
                moveNpc = true;
                anim[0].SetBool("Aiming", true);
                anim[1].SetBool("Walktouse", true);
            }
        }
    }
}

```

When moving the player(transform) too fast it will not pass inside the line:

```
if (HoriDoorManager.doorLockState == false && distance < 5f)

```

But if I'm moving the player slow very slow or much slower then it will pass inside the line and make the rest of the code in the Update.

Before using the distance at all it was working fine but now I want to calculate the distance to make sure it will work only when the player is exit at specific direction.

But for some reason on high speed movement the distance calculation is not working good. It's not giving errors or exceptions it's just does nothing when exiting.

I did a test now and on the line:

```
if (HoriDoorManager.doorLockState == false && distance < 5f)

```

And changed it to:

```
if (HoriDoorManager.doorLockState == false)

```

And now it's working on any speed the character/player is moving. So the problem is when calculating the distance on high speed.

# Answer
Your distance computation is just fine but your logic is broken.

The distance is just a plain math, you put values in it and get the result but then you check if it's less than 5, and what if it's not? You end up with a situation where in one frame your object is way before some trigger, but in the next frame your object has moved so far that it passed the trigger and is still far away, but on the different side. This is a well known problem in physics with fast moving objects and it's called `tunelling`.

To solve this issue you can use lower speeds, shorter timestep for simulation or use special kind of collision algorithms known as sweep tests. In such tests you extrude your moving object along it's movement direction, so fast moving ball would become a cylinder from balls position in one frame to position in the next frame. Then you test collisions between cylinder and walls instead of ball-walls.
> 1 votes

---
Tags: unity, c#
---


# Question
Title: Pathfinding to Get In Attack Range with "Transparent" Tiles
Currently I'm using A\* and a raycasting algorithm to determine the path an entity **(Player)** should take to get close enough to the enemy **(Enemy)**. The player has an attack range (it's illustrated around the enemy to show how close the player has to get to the enemy in order to attack it).

This works pretty well, but as soon as I add tiles that prevent entities from moving from them, but allows them to attack through them (imagine a river).

Using my current implementation the player entity takes the purple route to attack the entity, but I want it to take the yellow path.

I came up with the following, but this is highly inefficient:

* Mark the tiles around the enemy (cyan circle), which are in line of sight to the enemy (raycasting) as possible destinations
* Run the pathfinding algorithm to find which one of those destinations is the closest to the player

I know A\* is good for finding a single destination and Dijkstra is better for multiple destinations, but since I already got this working with A\* I wanted to know if it's possible to achieve this is an efficient manner.

Side question: how are the tiles where you cannot walk through, but can shoot through called in the industry? I know the wall likes entities are mostly called "solids".

# Answer
> "I know A\* is good for finding a single destination and Dijkstra is better for multiple destinations"

I would not categorize them this way.

A\* is just Dijkstra accelerated by a goal-seeking heuristic, so as long as you can come up with an admissible heuristic distance to the closest goal, it handles multiple goals as well or better than Dijkstra thanks to this acceleration.

The only reason to throw away the heuristic of A\* is if you need *all* paths to everywhere (not just ones toward a goal), or if your goal is so complex it can't be captured by an efficient heuristic.

Here, this heuristic suffices:

```
h = max(0, (target.position - tile.position).length - attackRange)

```

This predicts a distance of zero for any tile within the attack range, and the shortest distance to the attack ring for any tile outside it. This is an admissible heuristic since it never over-estimates the remaining distance to get a good shot.

(This particular version accelerates the approach, but doesn't help us much once we're inside the attack radius, so that's an area where we could hope to improve the heuristic further. By this point we're hopefully close to a workable shot, so we should find a firing position without an undue amount of added searching)

Next, we can expand our concept of a goal tile from "a tile that was designated in advance as a goal" to "a tile for which the `IsGoal()` predicate evaluates to `true`"

When you expand a tile from A\*'s priority queue of candidates, you can evaluate whether it satisfies these goal conditions by...

1. Checking whether it's within the attack radius - if not, early out.
2. If so, check whether it has line of sight to the target.

If so, the tile counts as a goal and you terminate the search.

Since each tile gets expanded only once, and we only do the expensive line of sight check for tiles in the attack radius (and you can cache results for the tiles along the line found, so you don't need to repeat sub-steps), this should generally evaluate the line of sight check fewer times than the exhaustive approach of marking all possible firing locations in advance.
> 3 votes

---
Tags: path-finding, raycasting
---


# Question
Title: How to mitigate speed effects on moving platforms?
I am implementing horizontal moving platforms in my 2D platformer.

The way it's implemented currently, when my player lands on a moving platform, he is reparented to it so that his position updates in line with the moving platform.

The player is moved perfectly in sync with the platform, which has a constant velocity. The player's acceleration and velocity are not altered in any way to achieve this movement. It's free because the player is now a child of the platform.

Because I use local position in all of my player's movement code, my player is still free to move left and right relative to the moving platform.

This works really well.

I notice, however, that when my player runs along the platform in the same direction as it's moving, there is a sense of moving fast. When he runs against the platform, there is a sense of sluggishness.

I know that relative to the platform my player is moving at the same velocity in both directions, but because he traverses more global distance than normal when moving with the platform, there is a sense of speed, and because he traverses less global distance than normal when moving against the platform, there is a sense of sluggishness.

I believe the sense of speed and sluggishness are like psychological illusions. If my player stands on my moving platforms, it takes the same amount of time for him to traverse them from left to right as right to left, so I know that local velocity with respect to the platforms is working. It's more of just a psychological effect I'm trying to mitigate, I think.

So my question is: **Are there any ways of mitigating these effects? How do you deal with this problem?**

I am working in Godot, but would prefer an engine-neutral explanation of ways to avoid this effect.

It may or may not be relevant, but I have a smoothly scrolling camera which lerps to my player's position, as well as parallax backgrounds.

# Answer
Although I haven't seen code, I believe you experience this problem because you add the platform's speed with the player's speed.

For example, imagine a moving platform is moving towards the +X axis, then you increase character's speed on the X axis by the platform's speed. When you move the character independently towards the +X axis, you add the character's speed as well, so the final result is the character will move towards the +X axis with a speed of `platformSpeed + characterSpeed`.

Similarly, if you move the character towards the -X axis, the result will be `platformSpeed - characterSpeed`. Assuming that `platformSpeed` is half of `characterSpeed`, on the first case the character moves x1.5 times its normal speed when moving on the same axis as the platform, but x0.5 times when moving to the opposite direction.

How do you solve this? I'm not sure how you've implemented speed in your project, but a good solution would be to separate platform's and character's movement. When the platform moves 5 units to the +X axis for example, the player moves the same amount of units with it, without touching its speed or any other value. When the character is to be moved around, it has already been affected by the platform, so only move it based on its speed.

---

If everything is functionally working, and you are only concerned about the visuals, like the character seems to be moving rightwards faster, but in reality it moves at the same speed, then you should take a look at the camera.

If your camera is moving smoothly towards the character, it moves that as long as the character is on the platform, the camera will constantly move towards the platform. So if the character moves on the same direction, the camera will look like its moving extra fast, because it will have to scroll more distance.

A solution would be to make the camera not move smoothly while the character is on the platform, or make it move faster to its looking target, so it doesn't move around for that long.
> 1 votes

# Answer
In your movement code get the velocity of your parent. If it's not `0` then multiply it by some constant, like 0..1 and subtract from Players speed.

By changing the constant parameter you could scale and tweak this effect.
> 0 votes

---
Tags: 2d, movement, platformer, moving-platforms
---


title: Tetris Glitchy Movement Fix

text:
# Question
Title: Tetris Glitchy Movement Fix
Usual tetris game has 2D arrays for arena/piece and collision check with matrix comparison. To add smooth movement and auto alignment of pieces:

* x and y are pixels on the screen
    + xMatrix \[the cell that piece in it related to the x value\]
    + yMatrix \[the cell that piece in it related to the y value\]
    + xCheck \[(x +- amount) cell equivalent for collision check\]
    + yCheck \[(y +- amount) cell equivalent for collision check\]
    + xOffset \[x mod cell size\]
    + yOffset \[y mod cell size\]

With These Updates New Game Loop:

```
if not collide(down)
    piece.y += amount
else
    merge

if left
    if not collide(left)
        piece.x -= amount
    else
        align

else if right
    if not collide(right)
        piece.x += amount
    else
        align

if key_release
    calculate_offset

if offset
    piece.x +- amount

```

is playable. But causes glitches on corner movements and out-of-bound errors for repetitive key presses sometimes. What can be the improvements on this code or what changes needed to be done?

# Answer
> 1 votes
This approach will make you drown in details with every new feature you'll want to add so maybe you could find some better way.

First, let's notice that this smooth Tetris is still grid-based. The frame-by-frame movement may be smooth but in the game logic you still can't move by half of the grid. With this in mind you can move all this smoothness to separate layer that's only visual.

* You can start with 2D array of bools for empty/filled fields.
* Implement your piece with `x,y` position as index of field in grid (not pixels!). Implement entire movement logic, like in old-school Tetris. When the piece goes down it fill up you 2D array. At this point you have a working Tetris clone.
* Add smoothness:

At this point you have a piece and movement code, so at some point you do something like:

```
piece.x += 1;

```

You need to split piece position into `logical` position and `visual`. You can leave current `x` as logical one so we need to add visual:

```
int x;
float drawX;

```

Then we need to update piece position frame-by-frame like:

```
if( piece.drawX < piece.x ) {
   piece.drawX += speed;
   if( piece.drawX > piece.x )   // Did we went too far?
       piece.drawX = piece.x;
}

```

This way your logic stays completely the same and it operates on `x/y` values, which are the `target` positions for your piece. Every frame you check the current position and if the piece didn't reach the target you move it further and drawing is done with `drawX` position instead of `x`.

# Answer
> 1 votes
As far as I can tell, gameplay-wise this is yet another Tetris clone. It *appears* like pieces move smoothly, but they still collide on a cell-by-cell basis.

It seems like the gameplay itself is just the same, but the visual representation uses interpolation.

If you want to replicate this for educational purposes, then it might be a good opportunity to learn how to separate your game mechanics from your visual representation. A clean software architecture almost always does this separation. The reason is that by loosely coupling your rendering with your mechanics you can make changes to one without having to think much about what the other is doing. So it is something you should definitely learn how to do well.

In this case it would mean that each block has two representation:

* A logical representation which includes all the information relevant for gameplay. Coordinates would be cell coordinates. The logical representation is updated by the game update loop based on the game mechanics and the player input.
* A visual representation which includes all the information relevant for rendering. Coordinates would be pixel coordinates. The rendering loop checks if the visual representation still matches the logical representation and updates it accordingly. Then the rendering loop renders it.

Your rendering loop would check the logical representation of the block and convert its coordinates to pixel coordinates. This tells it where the block *should* be. It then compares those intended coordinates with the actual pixel coordinates of the block. If they differ, it moves the pixel coordinates a bit closer to the intended coordinates.

Or in other words: The sprites chase the invisible blocks they represent.

---
Tags: collision-detection, tetris
---


# Question
Title: Why is my Zombie enemy not chasing the player?
I am using C++ and SFML to make a top-down Zombie shooter. For now I have a player I can move around who can shoot but I am trying to have a basic AI for a Zombie who chases the player based on player position.

For some reason the zombie is moving in a straight direction rather than chasing player. I believe that the problem has to do with incorrect player position being used to calculate the direction of the zombie. But I can't seem to figure out how to fix the problem. Any help will be appreciated. Thanks!

Here is my code so far:

**Player.cpp**

```
//GetPosition() is getting player position
//I even tried getting output of player's x and y position in this class and
//its correctly showing player's position
sf::Vector2f Player::GetPosition()
{
  xPos = playerSprite.getPosition().x;
  yPos = playerSprite.getPosition().y;

  sf::Vector2f position = sf::Vector2f(xPos, yPos);

  //Correctly outputs position
  std::cout << "X: " << position.x << " Y: " << position.y << std::endl;

  return position;
}

void Player::movePlayer(sf::RenderWindow& window)
{
playerPosition = GetPosition();
//std::cout << "X: " << GetPosition().x << " Y: " << GetPosition().y <<
std::endl;
mousePosWindow = sf::Vector2f(sf::Mouse::getPosition(window));
if (mousePosWindow.x < 0.f || mousePosWindow.x > window.getSize().x ||
mousePosWindow.y < 0.f || mousePosWindow.y > window.getSize().y)
{
    "";
}

aimDirection = mousePosWindow - playerPosition;
aimDirNorm = aimDirection / sqrt(pow(aimDirection.x, 2) +
pow(aimDirection.y, 2));

//Player
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left) ||
sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
    playerSprite.move(-5.f, 0.f);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right) ||
sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
    playerSprite.move(5.f, 0.f);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) ||
sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
    playerSprite.move(0.f, -5.f);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) ||
sf::Keyboard::isKeyPressed(sf::Keyboard::S))
{
    playerSprite.move(0.f, 5.f);
}

//Rotate player relative to mouse position
const float PI = 3.14159265;

float dx = playerPosition.x - mousePosWindow.x;
float dy = playerPosition.y - mousePosWindow.y;

rotation = (atan2(dy, dx)) * 180 / PI;

playerSprite.setRotation(rotation + 180);
}

```

**Zombie.h**

```
#pragma once
#include <SFML/Graphics.hpp>
#include "Player.h"
class Zombie
{
public:
  Zombie();
  Player player;

  sf::Texture zombieTexture;
  sf::Sprite zombieSprite;

  sf::Vector2f zombiePosition;
  sf::Vector2f playerPosition;
  sf::Vector2f direction;
  sf::Vector2f normalizedDir;

  int xPos;
  int yPos;
  float speed;
  void Move();

};

```

**Zombie.cpp**

```
void Zombie::Move()
{

// Make movement
xPos = zombieSprite.getPosition().x;
yPos = zombieSprite.getPosition().y;

zombiePosition = sf::Vector2f(xPos, yPos);

playerPosition = player.GetPosition();

//Incorrectly outputs player position
//This outputs 0 constantly. But why?
std::cout << "X: " << player.playerPosition.x << " Y: " <<
player.playerPosition.y << std::endl;

direction = playerPosition - zombiePosition;
normalizedDir = direction / sqrt(pow(direction.x, 2) + pow(direction.y, 2));

speed = 2;

//Rotate the Zombie relative to player position
const float PI = 3.14159265;

float dx = zombiePosition.x - playerPosition.x;
float dy = zombiePosition.y - playerPosition.y;

float rotation = (atan2(dy, dx)) * 180 / PI;

zombieSprite.setRotation(rotation + 45);

sf::Vector2f currentSpeed = normalizedDir * speed;

zombieSprite.move(currentSpeed);
}

```

**main.cpp**

```
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include "Player.h"
#include "Bullet.h"
#include "Zombie.h"
#include <vector>
#include <iostream>

int main()
{
sf::RenderWindow window(sf::VideoMode(1280, 720), "Arcade Zombies :
Multiplayer");
window.setFramerateLimit(60);
window.setMouseCursorVisible(false); // Hide cursor
sf::View fixed = window.getView(); // Create a fixed view

//Background
sf::Texture backgroundTexture;
if (!backgroundTexture.loadFromFile("resources/background.png"))
{
    std::cout << "Load failed" << std::endl;

    system("pause");
}

sf::Sprite backgroundSprite;
backgroundSprite.setTexture(backgroundTexture);
backgroundSprite.setOrigin(sf::Vector2f(backgroundSprite.getTexture()-
>getSize().x, backgroundSprite.getTexture()->getSize().y));
backgroundSprite.setPosition(window.getSize().x, window.getSize().y);
backgroundSprite.scale(sf::Vector2f(1.1f, 0.7f)); // absolute scale factor

//Cursor
sf::Texture cursorTexture;
if (!cursorTexture.loadFromFile("resources/gun-pointer.png"))
{
    std::cout << "Load failed" << std::endl;

    system("pause");
}
sf::Sprite cursorSprite(cursorTexture);
cursorSprite.setOrigin(sf::Vector2f(cursorSprite.getTexture()->getSize().x *
0.5, cursorSprite.getTexture()->getSize().y * 0.5));

//Player
Player player;
player.playerSprite.setPosition(window.getSize().x / 2.f, window.getSize().y
- 50);

//Zombie
Zombie zombie;
zombie.zombieSprite.setPosition(window.getSize().x / 2.f, window.getSize().y
/ 2.f);
zombie.zombieSprite.scale(sf::Vector2f(0.3f, 0.3f));

//Bullet
Bullet bullet1;
std::vector<Bullet> bullets;
int shootTimer = 0;

//Sound
sf::SoundBuffer gunBuffer, footstepBuffer;
if (!gunBuffer.loadFromFile("resources/gun_shot_sound.wav"))
{
    std::cout << "Load failed" << std::endl;
}

sf::Sound gunSound;
gunSound.setBuffer(gunBuffer);

while (window.isOpen())
{
    sf::Event event;
    while (window.pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
            window.close();
    }

    //Update
    player.movePlayer(window);

    //Zombie
    zombie.Move();

    //Shoot
    if (shootTimer < 20)
        shootTimer++;

    if (sf::Mouse::isButtonPressed(sf::Mouse::Left) && shootTimer >= 20)
    {
        gunSound.play();
        bullet1.bulletSprite.setOrigin(
        sf::Vector2f(bullet1.bulletSprite.getTexture()->getSize().x * 0.5,
        bullet1.bulletSprite.getTexture()->getSize().y * 0.5));
        bullet1.bulletSprite.setPosition(player.playerPosition);
        bullet1.currentVelocity = player.aimDirNorm * bullet1.maxSpeed;
        bullet1.bulletSprite.setRotation(player.rotation + 90);
        bullets.push_back(Bullet(bullet1));
        shootTimer = 0;

    }

    for (size_t i = 0; i < bullets.size(); i++)
    {
        bullets[i].bulletSprite.move(bullets[i].currentVelocity);

        if (bullets[i].bulletSprite.getPosition().x < 0 ||
            bullets[i].bulletSprite.getPosition().x > window.getSize().x ||
            bullets[i].bulletSprite.getPosition().y < 0 ||
            bullets[i].bulletSprite.getPosition().y > window.getSize().y)
        {
            bullets.erase(bullets.begin() + i);
        }
    }

    // Set mouse position
    cursorSprite.setPosition(static_cast<sf::Vector2f>
    (sf::Mouse::getPosition(window)));

    //Draw
    window.clear();
    window.setView(fixed);
    window.draw(backgroundSprite);
    window.draw(player.playerSprite);
    window.draw(zombie.zombieSprite);
    window.draw(cursorSprite);
    for (size_t i = 0; i < bullets.size(); i++)
    {
        window.draw(bullets[i].bulletSprite);
    }

    window.display();

}

return 0;
}

```

# Answer
> 1 votes
You create your `Player` in `main.cpp`, inside `main()`. You also set up the player's initial position here, and every time through your main loop you call `movePlayer` on this player to move it around the world. This is all mostly fine.

Your zombie, however, which you declare in `main()` just after the player... the zombie has it's own *copy* of the player, because you declared `Player player;` in the `Zombie` class. The zombie uses the zombie's player, which is always at zero because it is a *different* player than the one in `main()`.

You probably need your zombie to have a pointer to the player it wants to follow, so you should change your Zombie class to look more like:

```
class Zombie {
  public:
    Zombie();
    Player* player; // Note: now a pointer!
...

```

And then, in `main()`, make sure you give that zombie the address of the player to follow:

```
Zombie zombie;
zombie.player = &player;
...

```

Note that because you've changed the type of the player inside `Zombie` to a pointer, you'll need to change how you access it in `Zombie`: you have to use `player->` instead of `player.` to access methods and fields of the `Player` object.

---
Tags: c++, ai, sfml
---


# Question
Title: Detecting overlap with Phaser P2 physics
In a 2D platformer, I'd like to implement a ladder. I have collision working between the player and ground tiles. Now I would like to be able to detect when the player walks through a ladder tile (which can be one of three tile indices). When the player is overlapping a ladder and up is being pressed, the climbing state would be set.

Ideally, I'd like to get a callback when this happens. It seems that the `overlap` method from Arcade physics is not available in P2. What is there instead to implement overlap detection?

# Answer
From a related answer: https://gamedev.stackexchange.com/a/109446/43472

> As for overlap, P2 doesn't support it directly, but there is an equivalent solution known as the "Postbroadphase Callback". Basically this is a callback where P2 collects all potential collisions and then asks you - via the callback - whether to allow those collisions to resolve or be ignored. You return false in the callback to tell P2 not to perform collision resolution, but the fact that the callback was called in the first place means that those two bodies have overlapped, so this is where you put your overlap handling code.
> 1 votes

# Answer
If you know the top, right, left, and bottom positions of the hitbox you can check to see if the character box is within the ladder box by comparing sides of the boxes. This would let you know if the character is within the the ladder tile.

For example, left of ladder is `x.position` 18 and right is `x.position` 42. Left of player is `x.position` 19 and right is `x.position` 32.

```
if (player.left > ladder.left && player.right < ladder.right)
{
    // Player is inside ladder hit box.
}

```

You can also check the top and bottom of rectangle too.
> 0 votes

---
Tags: physics, html5, phaser
---


# Question
Title: Unity2D Register which player colliders have activated
I have a player character that has three separate coliders that form this shape (one for the top, one for the bottom, and one for both sides)

I'm trying to register floor collisions with the bottom collider so that I can reset jumping stuff (double jumps, etc), but since the corners are all touching the floor, I end up having the side colliders enter as well when I use `OnCollisionEnter2D()`.

Is there a way to get which colliders are contacting, or is there a better way to register these collisions?

# Answer
> 1 votes
How about using a single rectangle only? Calculate the distance to the other colliding asset.

The smaller component will tell you the axis, the sign of that component the direction.

For example a positive x could indicate a collision on the right, while a negative value wouldn't indicate a collision from the left.

---
Tags: unity, c#, collision-detection, jumping
---


# Question
Title: Trying to understand exactly how the server sends data to the client to prevent malicious actions
I recently started coding a game with one of my friends and he is taking care of the front end and I am doing the back end.

I read many blogs/articles/tutorials on how the back end communicates with the client side and they all show different ways of doing this.

In our game the player can move his character by right clicking where they want to go. Does this mean the movement happens on the client side or should the client send a coordinate to the server and the server checks if its valid and responds with 'move\_verified' which then allows the client side to carry out the action?

If this is the case how does collision take place because it will have many calculations and can cause major stress on the server. but doing it client side will make it vulnerable to malicious scripts.

The game needs to be in real time and 10 people will be playing simultaneously in a single match.I know the coords of all players have to be constantly sent to the client from the server so each player can see all players.

We are using Unity and socket.io. We successfully got communication with one another. But I just want to make sure I am on the right track before I start going deeper into the code.

I can show my code if its needed but its bare bones connections.

Thanks in advance!

# Answer
> In our game the player can move his character by right clicking where they want to go. Does this mean the movement happens on the client side or should the client send a coordinate to the server and the server checks if its valid and responds with 'move\_verified' which then allows the client side to carry out the action?

Yes, this is what you should be doing. However, in order to improve the user experience, you might still execute the move on the client-side immediately and not wait for the server confirmation. Otherwise the game will appear laggy.

> If this is the case how does collision take place because it will have many calculations and can cause major stress on the server.

But *will* it cause major stress on the server? Have you tested it? I don't know how complex collision detection is in your game, but chance is you are overestimating the required effort.

There are also a lot of techniques you can use to optimize collision detection. For example, you can use axis-alligned bounding boxes to pre-select potentially colliding objects with more complex colliders or you can use spatial hashes and only check for collisions in adjacent chunks. This is a very wide topic, so if you actually notice any performance problems with your implementation, feel free to post further questions.
> 1 votes

---
Tags: unity, node.js, socket
---


title: AABB to AABB collision response

text:
# Question
Title: AABB to AABB collision response
I am currently trying to resolve collision between two AABBs. I already have a function that can detect if the the two boxes are colliding and returns true if the two boxes are colliding.

The problem is that I do not know what to do next. All I want to do is make sure the boxes do not penetrate each other. Where do I start?

I am really confused about how to start and any help would be great. I also cannot use any libraries as this is an assignment

# Answer
There are continuous and discrete physics/mechanics. I do not know which one you are doing. Their main difference is in the detection, which you already have done. Thus, I will skip finding candidate pairs, and skim over the detection process, and then explain the response part.

With that said, the response has two parts:

* Find the collision instant
* Resolve the collision

And resolving collisions in the same thing, regardless of the approach.

Addenum: I will be explaining this for 2D... for 3D replace in your mind "segment" with "plane" and remember there is one more axis (thus, when I mention vertical and horizontal, there is also ern... one more). It is the same deal.

---

For abstract these are the two approaches:

**Continuous** mechanics will try to collide the area that the objects traversed between updates. It can have false positives in the detection, thus we will be doing a double check after finding the collision instant.

**Discrete** mechanics will collide the objects a fixed number of intervals along their path (once or more per update). It can have false negatives (tunneling). I will explain the bulk of the process it in the continuous approach, and then what are the variation for the discrete one.

Both can be done with AABB. And as I said above, resolving the collision is the same thing in both cases.

---

## Continuous

**Detection**

For both objects the candidate pair, get the smaller AABB that contains both the start and end position of the object. Collide those. If the AABB overlap, it means we have a possible collision (we still need to make sure, thus, we will double check on the resolve part).

**Finding the collision instant**

Consider the AABB of each object at the previous update. Consider each one of the four line segments that form it. Consider that those line segments moved according to the speed of the object from the last update to the current one.

We need to find at what instant one the segments of the first object passed over one of the segments of the second object. We only need to consider vertical segments against vertical segments, and horizontal segments against horizontal segments.

Furthermore, we only need to consider one horizontal segment and one vertical segment of each object.

To figure out which… for the first object: take the difference of the movement speed of the first object minus the movement speed of the second object. If the difference is positive on the x axis, you want the segment with higher value on the x axis, similarly for the y axis. For the second object, flip the operation.

Now, on the x axis, we need to solve `a_x + (a_speed_x * time) = b_x + (b_speed_x * time)`:

```
a_x + (a_speed_x * time) = b_x + (b_speed_x * time)
(a_speed_x * time) = b_x – a_x + (b_speed_x * time)
(a_speed_x * time) – (b_speed_x * time) = b_x – a_x
(a_speed_x – b_speed_x) * time = b_x – a_x
time = (b_x – a_x) / (a_speed_x – b_speed_x)

```

The same deal for the y axis.

We now have two instants at which the objects are meant to collide. Discard any negative ones, discard any time bigger than the time from the last update. We pick the smaller one.

We can now compute the position of the objects that time.

*Note*: If we are working in the continuous approach, we want to verify if it was indeed a collision. W do this by checking the collided segment along the other axis. In the continuous approach we can find false positives in the detection (these are near misses), and we should discard them at this step. Errata: do not discard the candidate pair, discard the collision time, if there are multiple possible instants at witch the collision could have occured, try each one.

---

## Discrete

**Detection**

If you are following the discrete approach, you collide the AABBs at least at their final position. You may also want to collide them at intervals from the last update. This is useful to prevent objects tunneling through each other (those are false negatives, a problem that the continuous approach does not have).

Thus, you will be checking the objects for collision once or more times in the interval of time from the last update. How many to do? Perhaps your game does not need too much precision on the collision, perhaps it runs on slow hardware and is better off fudging a little… or a lot, test.

There is an opportunity for optimization here: you can do a detection as the one described in the continuous approach, and then only check at intervals if that collision is positive.

**Finding the collision instant**

This is the same deal as in the continuous approach. Except, remember that if you are doing multiple checks, you need to add the time of the check to the time you get from that computation.

Here you have another thing to tweak for performance… if you are doing many discrete tests, then the interval between them is small. If it is small enough, you may skip computing the collision instant as I describe it for the continuous approach and just use the time of the first check that yielded positive. This means more iterations but simpler code. This is optimization is not appropriate for every game and every platform, test.

I remind you that I described the computation in terms of the starting position. It also possible to work with the final position and compute how much time ago the collision happened. *It leave this for you to figure out, if you want to try it.*

---

## Resolution

The simplest form of resolution is to simply put the objects at the position we found. This is enough to prevent them to appear overlapped.

However, just doing that will mean that is some lost time. For instance, if the update took 16 milliseconds, but we find that they objects collided at 10 milliseconds from the last update, we have lost 6 milliseconds worth of simulation.

We can simulate that remaining time, for instance, if the objects are meant to bounce, we can flip the speeds along the colliding axis and compute where the objects end up after the remaining time.

**Note on constraints**

Resolution can be more complex if we have to deal with complex constraints or degrees of freedom. Collisions and unmovable objects are just the simplest constraints. You could, for example, have objects that must remain at a given distance from another. What you do, is check if the constraint is violated, find out when, and then from that point figure out what should happen that respects the constraint.

It is also possible that as a result you find a situation that violates another constraint. For example, you bounce the object, and the resulting path makes it collide with another object *on the same update*. You can then repeat the process for the other constraint.

Eventually, the system would find a solution that satisfies all the constraints… but we do not have “eventually”, the update should be fast as to not stagger the game, thus, you probably want to set a maximum number of resolutions you do… it can be just one, and it can be simply placing the objects at the last position that violates no constraints, and you may be able to life with the simulation losing a few milliseconds here and there… how many to do? Test.
> 6 votes

---
Tags: collision-detection, collision-resolution, aabb
---


# Question
Title: How do I point with my straight line the point that moves in the figure "infinite" / "8"?
I need a help for my project.

Given a straight line "a" - "b" I have "a" point anchored and "b" can move. I need to make sure that the "b" point of the straight line always points to the "c" point, taking into consideration that "a" is anchored.

I can not use the LookAt () because I need to be able to use the mouse too.

# Answer
> 2 votes
Just take the AC vector, which should contain AB, since AB points at C, then normalize it and multiply by the length of AB. To get B, simply add the resulting vector to A.

# Answer
> 0 votes
I can think of two approaches to try and see which works (or works better).

As both of my computers have committed suicide, I can't test these myself.

# Option 1: using the hierarchy

Assumptions: Your character is directly controlled via `MouseLook`, your camera is a child of the character.

Approach: Add an additional child object between your character and your camera. Add a script to this. Use `LookAt()` as described in the question to rotate this object, which will introduce the jitter to the camera (don't bother jiggling the weapon model, you're going to use the camera to determine shot angle anyway).

# Option 2: direct jiggle

Assumptions: None

Approach: After mouselook runs, do the following:

```
Vector2 offset = InfinityLoop(Time.time);

Vector3 lookPoint = cam.transform.forward * 10 + offset;
cam.transform.LookAt(lookPoint);

private Vector2 InfinityLoop(float time) {
    //calculate your jiggle loop
}

```

For either approach:

When the jiggle is not required, either disable the jiggle script or otherwise don't calculate/apply the jiggle.

---
Tags: unity, c#
---


title: How can I represent a 2d UI?

text:
# Question
Title: How can I represent a 2d UI?
So, I wanted to start building a desktop application, which is of course with an interface, and I thought that OpenGL would be best.

The problem is, once I started following TheChernoProject's tutorials it got me a little confused. I know it's a state machine, but how exactly can I represent, for example, a rectangle I have drawn on the screen? How can I organize it, so I have a couple rectangles with different positions and sizes, which represent the interface?

Here is the code:

```
#include <GL/glew.h>
#include <GLFW/glfw3.h>

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>

#define ASSERT(x) if(!(x)) __debugbreak();
#define GLCall(x) GLClearError();\
    x;\
    ASSERT(GLLogCall(#x, __FILE__, __LINE__))

static void GLClearError()
{
    while (glGetError() != GL_NO_ERROR);
}

static bool GLLogCall(const char* function, const char* file, int line)
{
    while (GLenum error = glGetError())
    {
        std::cout << "[OpenGL Error] (" << error << "):" << function << " " << file << ":" << line << std::endl;
        return false;
    }
    return true;
}

struct ShaderProgramSource
{
    std::string VertexSource;
    std::string FragmentSource;
};

static ShaderProgramSource ParseShader(const std::string& filepath)
{
    std::ifstream stream(filepath);

    enum class ShaderType
    {
        NONE = -1, VERTEX = 0, FRAGMENT = 1
    };

    std::string line;
    std::stringstream ss[2];
    ShaderType type = ShaderType::NONE;
    while (getline(stream, line))
    {
        if (line.find("#shader") != std::string::npos)
        {
            if (line.find("vertex") != std::string::npos)
                type = ShaderType::VERTEX;
            else if (line.find("fragment") != std::string::npos)
                type = ShaderType::FRAGMENT;
        }
        else
        {
            ss[(int)type] << line << '\n';
        }
    }

    return { ss[0].str(), ss[1].str() };
}

static unsigned int CompileShader(unsigned int type, const std::string& source)
{
    unsigned int id = glCreateShader(type);
    const char* src = source.c_str();
    glShaderSource(id, 1, &src, nullptr);
    glCompileShader(id);

    int result;
    glGetShaderiv(id, GL_COMPILE_STATUS, &result);
    if (result == GL_FALSE)
    {
        int length;
        glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length);
        char* message = (char*)alloca(length * sizeof(char));
        glGetShaderInfoLog(id, length, &length, message);
        std::cout << "Failed to compile " << (type == GL_VERTEX_SHADER ? "vertex" : "fragment") << " shader!" << std::endl;
        std::cout << message << std::endl;
        glDeleteShader(id);
        return 0;
    }

    return id;
}

static int CreateShader(const std::string& vertexShader, const std::string& fragmentShader)
{
    unsigned int program = glCreateProgram();
    unsigned int vs = CompileShader(GL_VERTEX_SHADER, vertexShader);
    unsigned int fs = CompileShader(GL_FRAGMENT_SHADER, fragmentShader);

    glAttachShader(program, vs);
    glAttachShader(program, fs);
    glLinkProgram(program);
    glValidateProgram(program);

    glDeleteShader(vs);
    glDeleteShader(fs);

    return program;
}

int main(void)
{
    GLFWwindow* window;

    /* Initialize the library */
    if (!glfwInit())
        return -1;

    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(1920, 1080, "Hello World", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    /* Make the window's context current */
    glfwMakeContextCurrent(window);

    if (glewInit() != GLEW_OK)
        std::cout << "Error!" << std::endl;

    std::cout << glGetString(GL_VERSION) << std::endl;

    float positions[] = {
        -0.5f, -0.5f,
         0.5f, -0.5f,
         0.5f,  0.5f,
        -0.5f,  0.5f,
    };

    unsigned int indices[] = {
        0, 1, 2,
        2, 3, 0
    };

    unsigned int buffer;
    GLCall(glGenBuffers(1, &buffer));
    GLCall(glBindBuffer(GL_ARRAY_BUFFER, buffer));
    GLCall(glBufferData(GL_ARRAY_BUFFER, 6 * 2 * sizeof(float), positions, GL_STATIC_DRAW));

    GLCall(glEnableVertexAttribArray(0));
    GLCall(glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0));

    unsigned int ibo;
    GLCall(glGenBuffers(1, &ibo));
    GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo));
    GLCall(glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * sizeof(unsigned int), indices, GL_STATIC_DRAW));

    ShaderProgramSource source = ParseShader("src/res/shaders/Basic.shader");
    std::cout << "VERTEX" << std::endl;
    std::cout << source.VertexSource << std::endl;
    std::cout << "FRAGMENT" << std::endl;
    std::cout << source.FragmentSource<< std::endl;
    unsigned int shader = CreateShader(source.VertexSource, source.FragmentSource);
    GLCall(glUseProgram(shader));

    GLCall(int location = glGetUniformLocation(shader, "u_Color"));
    ASSERT(location != -1);
    GLCall(glUniform4f(location, 0.2f, 0.3f, 0.8f, 1.0f));
    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        /* Render here */
        GLCall(glClear(GL_COLOR_BUFFER_BIT));

        GLCall(glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr));

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();
    }

    GLCall(glDeleteProgram(shader));

    glfwTerminate();
    return 0;
}

```

# Answer
> 1 votes
Building an application using OpenGL does not require you to use a specific programming language, since there is binding for pretty much any language you can think of nowdays.

> I know it's a state machine, but how exactly can I represent, for example, a rectangle I have drawn on the screen?

I don't understand how the two problems are correlated; OpenGL is a tool that you use to communicate and send commands to your GPU, also known as a **Graphics API**. Because of that, it has no notion of any "Rectangle" object.

> How can I organize it, so I have a couple rectangles with different positions and sizes, which represent the interface?

One way to do that would be to organize all your Rectangle data inside a class, pass it as a parameter to a **Renderer**, that extracts all the data from it, and renders everything to the screen. This approach is *very* inefficent though.

That's why Batching Renderers are used: they usually contain one or more buffers, to which they write all the Rectangles' data, set them up, and send the whole thing with one or two drawcalls to the GPU. This way we have a `x to 1` ratio, which stands for "x sprites (or rectangles) rendered to the screen for the cost of 1 drawcall" which is much more efficent than having a 1:1 ratio (1 rect to 1 drawcall).

As Mikael already stated in his answer, developing a complete gui from a beginner standpoint is a non-trivial task. I highly suggest you to get very comfortable with OpenGL's basic and advanced concepts (like stencil buffers or text rendering) and your programming language of choice, before going any further.

# Answer
> 0 votes
Welcome to the gamedev stack.

I'll try and address your questions one at a time, let's start off with

> So, I wanted to start building a desktop application

Let's just make sure we're on the same page and say that by application I assume you mean game or game engine. If you want to make a desktop application you'd be better off with something like C# and WindowsForm (For Windows, obviously).

> but how exactly can I represent, for example, a rectangle I have drawn on the screen? How can I organize it, so I have a couple rectangles with different positions and sizes, which represent the interface?

A rectangle in this sense is commonly referred to as a Sprite, which in turn contain little more than X,Y pos, size and a texture. You can then keep track of your Sprites in any number of ways, `std::vector` is for example a great container for such data. In preparation for drawing you'd go through your container (such as std::vector) and build up your buffers (VBO,VAO,IBO) and then in your draw step you'd simply tell OpenGL which buffers to use.

> Are there any specific tutorials which you could recommend me, or books, connected with the 2d aspects of OpenGL and building GUI with it?

Typically we tend not to link tutorials,books etc. since it's highly subjective and doesn't really have a clear answer. However, for what you're doing I'd suggest you hit pause on your TheCherno video marathon and head on over to Learn OpenGL which has been accepted as a good starting point by most people. In the first few tutorials or so you will gain the knowledge you need to draw a Sprite (hopefully!).

For the sake of completeness I would also say that writing an entire GUI library for a starter task might be a bit too big of a scope, you might want to start out smaller while getting the hang of OpenGL particulars. In the meantime you could use something like Dear ImGUI (ImGUI stands for immediate mode gui and the Dear part is their weirdly chosen name, it's a solid lib though and you can easily find out more via your favourite search engine Bing) which is rather lightweight and easy to use.

---
Tags: opengl, c++, 2d
---