title: How do I design very difficult games?

text:
# Question
Title: How do I design very difficult games?
I would like to design games with very high difficulty levels. I have read these questions:

Yet they focus on general game design and balance, and not on the particular topic of increasingly adding to the difficulty of a game.

I understand that difficulty is different for every game, so I would like to know if there are any general guidelines I could follow to avoid falling into common problems that there may be while designing games and levels on the hard side of the difficulty line, regardless of the genre of the game.

Some sub-questions that come to mind are:

* How to ensure 'beatability' while designing insanely hard parts of game?
* How to know it is possible to actually beat my game?

For instance, when designing a platformer, I could make a really hard sequence of jumping and dodging. Now, as developer, I know precisely how far the player character can jump, how fast projectiles are moving etc, but how can I ensure that the designed level is actually beatable?

I know that the most obvious answer is to try and play it, but then, the game would be only as hard as how good at playing it the developer is.

Does anybody with actual experience making hard games know of any tricks or guidelines I can use to successfully create a difficult game?

# Answer
> 19 votes
It certainly depends on the type of game, and as always, there are no foolproof ways to increase difficulty, but in my experience, I have found that making difficult games/levels is much, much more difficult than making easy games/levels. Some reasons that come to mind are:

* It is very easy to cross the line between difficult and plain impossible. I really enjoy very difficult games, but many times I see that a specific game or level is just too difficult, or even impossible, that I get frustrated. Remember balance is paramount.
* Difficult games and levels are mostly about training and repetition. A player should feel that he's getting closer to finishing the level each time he plays and gets better at it. Making a level that creates this feeling is very difficult.
* Difficult games and levels tend to have much more variables/entities than easier ones. Be it more enemies, more bullets, more curves or whatever, every single entity has to be placed and set up. Just the setup takes much more time than simpler levels.
* The more complex the game becomes, the more possible it is to have a vulnerability that renders your entire difficulty scheme useless. Making sure that the game remains difficult for various playing styles is very difficult.

There are no foolproof ways to make your game/level more difficult, but I have some recommendations for the level designer:

* I think you can only make a game as hard as you could play it yourself, not harder. Or in other words, "if you can't beat it yourself, make it easier". Because of this:
* Make sure you like the game genre you're playing, and you have plenty of experience with similar games. That means that you're VERY good at the genre. I would say that at least 100~250 hours of play for *each* of at least 5~10 similar games would give enough experience to lead the design of moderately difficult levels. Extremely difficult games/levels (like IWBTG and similar) may require more time.
* Make sure you keep on playing other games while you design yours. It's very easy to get too involved in your levels and make them just too difficult. Also by making levels you will notice new things that you may had not noticed before, and you may want to check other games to see how they deal with those things.
* Even so, show the game to other people who have less experience with the title, at least to make sure that the goals of the game/level are clear even for newcomers.
* Play, play, play and play the game. For a single action game, it may take dozens, or even hundreds of times to playtest each level to make sure they are balanced. Of course, the more difficult the levels are, the more you have to test them.
* Make sure the game is easy to test. If you can change a level without recompiling, cool; if you can change a level without rebooting the game, awesome; if you can change a level without having to go through the entire game sequence, super; if you can change the level as you play it and rewind it to test your changes immediately, ultra-awesome. The shorter it takes for you to retest your game, the more you can play it and the better you can make your game come out.
* Don't be afraid to throw away a level and remake it afterwards. As you learn more about the game you're making, your levels will be more fun. The first levels you made will probably have to be rewritten at the end. This also means that:
* Leave the first level until last. The first level people play will probably have to be the best designed one, as first impressions count very much.

I have two specific experiences of two indie games I worked on, I would like to share (disclaimer: I made these games. I am including this information for illustrative purposes only. If you want more information about them, there are some links in my user page)

### Game 1: action shooting game

Gameplay video: https://www.youtube.com/watch?v=n2t3nw4KQXQ

This was my first full game. Enemies shoot bullets at you, and you have to dodge the bullets while attacking the enemies.

Making the levels for this game was tough. I had played several action and shooting games, and cleared some on moderately hard difficulties, but I have to admit I am no pro-gamer.

The first thought I had was to simply have more enemies as the difficulty increases, and have enemies shoot more bullets at you. Certainly, that makes the game more difficult, but sometimes you will end up in places where there are so many bullets there are simply no way to avoid them. Simply increasing the amount of bullets is just not enough to vary the difficulty of the game.

Another thing I tried was to vary the speed of the bullets fired. It is not trivial whether faster bullets make the game easier (faster bullets mean less bullets on the screen at the same time) or harder (faster bullets require better reflexes to dodge)

It is also possible to make the bullets harder to dodge, by having them move in unconventional paths, or have them follow you or something.

Additionally, it is possible to make enemies take more damage to destroy, or make the player take less damage to destroy. If you're mixing this with other techniques, make sure you don't go overboard, as it is possible to make the game unfair.

The game turned out to be very difficult. To be honest, it turned out a bit more difficult than I had wished, even on the easy difficulty. I made a huge effort to make sure the game was beatable, but I certainly believe I could have made a better job. I am considering making an improved version of the game with more balanced levels.

However, making this game was a huge learning experience for me, which takes us to:

### Game 2 (rhythm action game)

Gameplay video: https://www.youtube.com/watch?v=tAYrbmpoS-8

Packed with more experience, my second action game was of a genre with which I am much more comfortable with: rhythm games. I have played pretty much every rhythm game in Japan, and have gotten pretty high in the world rankings of a few of them. Making and balancing this game was much more enjoyable, but certainly not without problems.

The game consists of moving left and right while avoiding getting hit by bullets. The bullets are designed to come out in a way so you can easily avoid them if you move to the rhythm of the music that is being played. If you get hit by a bullet, you die. Lose all lives and it's game over. Live to the end of the song and you move to the next level.

Balancing rhythm games is much easier. Making the rhythm faster as the difficulty increases makes the game more challenging, but not unfairly so.

However, double the speed means at least double the bullets, and quadrupling the speed means four times as many bullets. I also made the more difficult levels have more bullets horizontally, so a hard version of a level has 10~15 times as many bullets as the easy version. We put every single one of those bullets by hand, so making the hard levels took the vast majority of the time to make and test.

So, The faster the rhythm, the closer the bullet pattern has to be to the actual rhythm of the song. Bullets on every second beat are much easier to place that bullets on every half beat. I went to make the game engine support changing the bullet patterns -during- play, which greatly made the level design much more enjoyable than having an external editor.

I really wasn't expecting the hard levels to take so much time to make (about 3 days for just the initial design of one hard stage vs 2 hours for an easy stage), that we had to made some sacrifices in other parts of the game to finish development on time.

But even so, the level design was pretty ambitious. I wanted to have a speed based level, a technical level, a reaction-type level, and I think we pretty much achieved what I wanted. The hard stages ended up pretty hard, but not impossible.

I believe the most critical factor in getting a much better result for the second game was the fact that I play MUCH more rhythm games than action shooting games.

So to sum it up: yes, making hard games is very tough.

I wonder what I'll do for the next action game...

# Answer
> 3 votes
Platformer difficulty is about perfect timing of player actions.

I would use 3 main approaches:

**Playtesting** Let you level be played by players and adjust the difficulty appropriately.

**Simulating** That will work for simple levels and parts of levels. Make a simulation with all the moves required to pass the level part and see how much they are allowed to change to still let the player win. The stronger the restrictions are, the harder the level is to beat.

E.g. if player needs to jump over and crouch and jump over again, you can start off with making the perfect sequence mapped to time. Any imperfections (e.g. jumped 20px too early, crouched 100ms too late) could lead to loose. Now you can relax this schedule by allowing player to jump within -40..40 px interval and crouch within -200..200ms by making the jump platform wider and enemy attack shorter.

**Reverse-simulating** \- Make a run on the empty level and then add pits/turrels/etc to make that run as restricted as possible, so that any change in sequence of key-presses makes the player exposed to an attack and loose. The more restrictions - the harder the level becomes.

# Answer
> 1 votes
Rule 1: Do not use random behavior in traps and enemies. This is why Roguelikes could be problematic if they are not fine tuned as randomness could create massive difficulty spikes if not handled correctly.

The point is only making the game hard to beat; this may sound obvious but you also need to convey to the player what challenge they are facing and why they failed, otherwise it would be just one of those trial and error "trapformer" games.

## Platformers

---

tl;dr 1. Make the level completely unpassable. 2. Then slowly trim traps and bullets/projectile' timings that no test players were able to beat. Keep the traps that the test players managed to avoid. You can draw statistics on how many times a certain trap was avoided to measure it's approximate difficulty level. 3. To increase or lower difficulty dramatically, you can make a trap that normally does damage insta-kill the player instead and vice versa.

longish version:

1. Throw in all the possible traps, turrets, spikes and flaming balls of lava you can think of to an excess into the room you wish to make **extremely difficult**.
2. Make them run automatically on a timer (so the behavior repeats itself) or make them activate as a response to player movement (i.e the lava ball spawns when the player approached). The point here is do not use random behavior as it is extremely hard to test.
3. Play the level over and over while doing your best and avoiding as many collisions with death-traps as possible (you could also let a *very skilled* alpha-tester play instead).
4. Have the game code record every collision between your character and a death trap. Remove the traps you were never able to avoid in any of your attempts.
5. To make this easier, you could slow down the game without changing it's rules, physics and behavior. This will let you simulate the playing skills of a player with extremely fast reflexes and lots of patience.
6. You could increase the size of the bounding box of the collidable test character to make things a bit easier for the real players.
7. Record you winning play through and systematically add obsticles that would have been avoided during your victorious run.

Just to be clear, when I say remove I mean that if the lava pit spawns 20 lava balls per 5 seconds and your test character touches two of them, remove these two spawns from the timed spawner. If you can't avoid a specific spike that is there 100% of the time, you could remove it completely or turned it into a timed trap that is active only 50% of the time (like an electrical barrier, a flamethrower or a laser). The same principle regarding the lava balls applies to turrets as well.

Also it's assumed you already have an idea for a level design.

## Racers

---

Racers are surprisingly simple to tweak. You play the game and get the playtesters best times. Now you simply make the enemies drive nearly as fast as that. You could make them a slightly slower ghost version of the best player or alternatively, make them faster but allow the player to slow them down using weapons, collisions and what not.

You could also record the player's car behavior and path during the run i.e break, accelerate, turn right and left and then construct a course based on that path. Placing oil spills, rocks and other obstacles on the road that would likely lead to a loss (similar to platformers).

## General

---

It does not matter what game you are making, record the winning key strokes, add an epsilon room for mistake and let the player lose otherwise. It could be DDR, endless runner and what not in this case. The idea is to visualize the obstacles in a compelling way instead of making an invisible wall of death or something that confuses the player. You need to let the player understand why they are losing over an over or they would quickly rage quit and for a good reason.

# Answer
> 1 votes
This may not be exactly on-topic, but I want to add my two cents about the global experience on high difficulty :

Please give a focus on player frustration. When I'm confronting a very difficult level that requires lot of deaths/replays, any tiny thing can make the player rage, especially if he can't focus on the difficult passage. More precisely:

* how far is the checkpoint from the difficult part. If the difficulty is far away, the 2 minutes you have to play before going back to it is just so boring and frustrating that the player may abandon without having really tried the harsh part.
* make restarting very quick. I can't stress out how frustrating it is when you retry for the \>5th time, and then you can't skip/accelerate lose screen (or starting screen, or loading screen, for that matter). I've seen games which do this very well: for instance there is a countdown before starting but you can skip it by touching the screen.

# Answer
> 0 votes
You suggested testing it with a real player, however as the developer, you can create an ideal player (i.e. a computer) and test it with them - this works wonders for deterministic games (i.e. not random chance, the same moves will always end up in the same result). You can also use a real player and allow "cheats" like say turning back the clock 5 seconds instead of being forced to re-start the level - doing so will allow you to test faster, but still determine if the level is possible to beat or not.

# Answer
> 0 votes
Here is a way to do that on a platformer; this is probably possible on other kind of games, but I won't develop here.

* First, implement a record/replay feature in your game \[\*\]
* Create the platforms of the level, and be sure they require a fair amount of jumping
* Record yourself finishing the level (it should be easy at this point since there is no trap yet)
* Add lava pits/killing spikes/enemies everywhere you can without interfering your recorded game (make sure that if player jumps a little sooner or later he will hit one of those killing things
* Add some moving obstacles: Be sure that they will cross the position of the player moments sooner or later when he is supposed to be there (make sure that if he pauses too long or not enough, he won't be able to pass)
* Check by replaying your saved game

Now, if you want just a couple of hard passages in your games, you can do that by hand but if you want an almost impossible to play game from start to end you may want to automatize the process: You may do that by writing a modified replay engine that will not kill the player when he hit a trap but instead delete the trap from the level

* After you've performed the 3 first steps above (up to the recording), randomly add a bunch of traps (like a few hundreds/thousands depending of your level size)
* run your recorded game on the modified replay engine to create a possible route and save the modified level.
* That's it: you can move to the next level

Extra thought: you may even make the game procedural with a few changes: \- Just create all your levels without any trap. Whenever the user starts a level, your game engine would have to: \- add a bunch of traps (you may have various difficulty level with more or less traps) \- run in the background an AI run of the level which delete the traps in the way \- display the level and let the player trying to pass the level

Or you could script the game entirely, like in "I wanna be the guy" but then it's closer from "movie making" than "video game design".

\[\*\] this is for level design only but you may consider leaving it in the final game since players which successfully finish the level will be very happy to brag about it by sharing the video :o)

# Answer
> -2 votes
Just think, what can i do to make this harder? - on an entirely possible level.

Given that the game is a platformer (like mario)

More advanced enemies, less power-ups, moving screens/timers and less breathing room will guarentee that the player is on their toes.

Or, if you're really thinking of 0.001% possible, take an entirely possible game and take away that one feature that would stop them 100% of the time and replace it with a 99.99%

---
Tags: game-design, playtesting, difficulty
---


# Question
Title: Unity3d how to show an image downloaded from HTTP
I am bit new to Unity3d. I am fine with any solution either of the scripts.

Can we render an image in unity3d (which we have to download from HTTP path)? If yes then how or do you have any reference?

Thanks Vandana

# Answer
You should be able to download images using HTTP with WWW.texture

WWW.texture

Should be straight forward. Just provide the path to an image and apply the texture to a material.
> 2 votes

# Answer
I recently faced the same problem. I was creating an scrollable image gallery in Unity, where images are downloaded in real-time from the a web server. On iOS devices I was reaching very fast the memory limit (with consequent app crash). That was caused due to a very big number of www objects leaved in the memory and never deleted or released. Also a very big number of Texture2D objects leaked. The main misunderstanding is considering a Texture2D like a variable of an object that self-contained the image information. Texture2D only point to a referenced asset so we need to create one before assigning to our GUI object. Without creating one we will overwrite the referenced asset in our project, leading to very crazy behaviour. So this the code that works for me on iOS and just use the minimum of memory

```
    public void DownloadImage(string url)
    {
        StartCoroutine(coDownloadImage(url));
    }

    IEnumerator coDownloadImage(string imageUrl)
    {

        WWW www = new WWW( imageUrl );

        yield return www;

        thumbnail.mainTexture = new Texture2D(www.texture.width, www.texture.height, TextureFormat.DXT1, false);
        www.LoadImageIntoTexture(thumbnail.mainTexture as Texture2D);
        www.Dispose();
        www = null;
    }

```

A brief comment: You receive a url you will download the image from. Start the coroutine that manage the download Create the www object in the local scope yield waiting the download to complete Create a new Texture2D object/asset with parameters and assign to your final object mainTexture or what do you want Use the "www.LoadImageIntoTexture()" function to COPY the image inside the created asset (this is the fundamental part) Dispose and set to null the www object to prevent memory leaking or orphans

Hope it helps who will face the same problem.

An interesting lecture is this website where they implement a WebImageCache system to avoid re-downloading the same image many times.

http://studiofive27.com/index.php/unity-cached-web-images/

ADD-ON Also try to **avoid the direct assignment** like:

```
myGameObjectMaterial.mainTexture = www.texture;

```

Unless you are conscious that you want to overwrite your asset and you don't to do this inside a loop or update.
> 2 votes

---
Tags: unity, mono, unityscript
---


# Question
Title: D3D11_SAMPLER_DESC::MipLODBias vs ID3D11DeviceContext::SetResourceMinLOD
When implementing a max-texture-detail functionality for a game, which approach is better to use, out of:

* Setting the `D3D11_SAMPLER_DESC::MipLODBias` value of a sampler state object, or,
* Setting the min resource LOD of each texture resource with `ID3D11DeviceContext::SetResourceMinLOD()`?

I'm thinking it's probably the second option, because using `SetResourceMinLOD()` means that only the relevant subresource will be uploaded to the video memory, correct?

If that is the case, I assume that setting `SetResourceMinLOD()` will cause Direct3D to remove unused detail levels from video memory (if necessary) if they're already on there?

Thank you

# Answer
> 1 votes
SetResourceMinLOD : For Direct3D 11, this functionality is extended from the sampler to the entire resource. Therefore, the application can specify the highest-resolution mip level of a resource that is available for access. This restricts the set of mip levels that are required to be resident in GPU memory, thereby saving memory.

---
Tags: directx, directx11, level-of-detail
---


# Question
Title: How to move around in a map and remember position?
I am working on sound labyrinth game. My game is about a person getting trapped in the basement and the only way to navigate and get out is through sound. I have created a map over the basement and for each square there has to be a sound.

The player starts in b5 with an intro sound and then has to move forward using the arrow keys. I've created this bit of code that plays a sound when forward arrow (`keycode === 38`) is pressed:

```
var thriller=new Audio("thriller.mp3");

document.addEventListener('keydown',
function (background) {
    if (background.keyCode === 38){
        thriller.play();
    }
}, false);

```

My question is:

* How does the code know in which square the player is situated? Is there some smart way in which I can systematize the squares and the sounds they represent?

# Answer
Remember that what you display (or don't display) to the user doesn't have to be the same as the information you keep about the player and the game world.

Design your game as if you were to display the player's location on a map, then instead of showing which square they're in, play the sound for the square they're in.

That means designing a map and keeping track of player position. The arrow keys will change the player position. When the player position is inside one of the zones you've specified in your map, you play the sound for that zone.
> 1 votes

# Answer
http://www.needsmorejquery.com/

Perhaps something like ...

HTML:

```
<div data-role="map">
  <div data-location="a1" data-role="tile" data-sound="thriller.mp3" />
  <div data-location="a2" data-role="tile" data-sound="thriller2.mp3" />
  <div data-location="a3" data-role="tile" data-sound="thriller3.mp3" />
  ...
</div>

```

JS:

```
$(document).on("enter", "tile", function() {
   var tile = $("this");
   var soundName = $("this").data("sound");
   var sound = new Audio(soundName);
   sound.play();
});

```

Now you just need to raise this enter event on your tiles ...

So presumably you have some sort of character object that you can handle move events on?

This is where you game logic comes in to play, how does your character move? about exactly?

```
$(document).on("keydown", "#avatar", function(background) {
   if(background.keyCode === up) {
     avatar.move("up");
   }

   ...
});

var avatar = {
  isInNewTile: false,
  move: function(direction) {
    move logic in here ...
    if(avatar.isInNewTile) {
      tile.enter();
    }
  }
}

```

Ok so some final thoughts ...

1. Lots of assumptions made here.
2. This is "seudocode" thus I don't claim it works in any manner but it should help to explain the approach to you.
3. Hopefully from here you can (from your game code) figure out the exact solution.
> 0 votes

# Answer
You need to declare variables that will contain the played character's position. Decide if the game is 2d in nature or 3d. You need to do collisions an play a sound during a collision like any other game using tutorials to guide you. To compute the sounds intensity, define sound sources in the map and then compute the distance from them, the sound intensity could something like ~100% / distance. You could also consider walls as something that dampens sound.
> 0 votes

---
Tags: game-design, javascript, grid, sound
---


# Question
Title: Finite-state machine with more than one concurrent state
I am using a FSM for the player entity and it is working fine. Currently the entity has one state and only one (e.g. paralyzed). The entity's state process() method is called every turn.

It is necessary however, that each entity can have more than one state simultaneously (e.g. paralyzed and blinded). Each state affects the entity attributes e.g. paralyzed reduces the walking range to 10% and blindness reduces it to 50%. Vision range is not affected by paralyzed state, but by blindness (set to 0).

Now it is important in which order the states are processed. I either end up with a wrong walking range or a wrong vision range. I could do checks in every state's process() whether the entity has any other states and alter the code accordingly, but this gets very messy the more states I add.

Currently I think it's a better choice to attach only one state to the entity, but to create more states, some of them a combination of two states (e.g. a blindedAndParalyzed). This way I'll and up with a lot more states than I currently calculated with, because ever state has to be combined with other states. I'm wondering if that is the best solution?

A state is a Singleton with an enter, process and exit method. Process is called each turn. Currently process() for paralyzed looks like this: `public void process(){
 walkRange = 10% * walkRangeBase;
 visionRange = visionRangeBase;
}`

and process() for blinded looks like this `public void process(){
 walkRange = 50% * walkRangeBase;
 visionRange = 0;
}` At the moment the result is always fine becvause only the process() method of only one state is executed. If I switch to multiple states both get executed and the result is either walkRange = 50% and visionRange = 0 or walkRange = 10%. THe desired result would be a walkRange of 10% and a visionRange of 0, because the walkRange should be limited to the smallest one. I could do something like that: `public void process(){
 if(state != paralyzed)
 walkRange = 50% * walkRangeBase;
 visionRange = 0;
}` But i have around 20 different states, so I have to create a lot of if cases. Choosing the smallest value for e.g. walkRange doesn't work either because there are some states with positive effect on walkRange. So I am wondering if it is better to avoid a state machine with more than one concurrent state and live with a bigger amount of states (about 50), or if there si another solution to this problem.

# Answer
If you built an FSM for the player entity you should have at least 2 different states or more. With only one you lose the point to have a FSM. Also you'd better think to states as conditions/moods/actions that the entity is actually doing. With this I mean that a state is a **collection of properties values**, while *blinded* and *paralyzed* are simply *boolean* properties and *vision range* and *walking range* are *float* properties/attributes.

1) The easiest solution would be maintaining the 2 bool variable and making some IF...ELSE during update. But it's not scalable.

2) So if you see that, for your game, you are going to need an independent management of legs and eyes you'd better split the control over 2 independent FSM, one for the legs state and the other one for the eyes. (DIVIDE ET IMPERA). Each one of the FSM is only modifying attributes relatives to legs or to eyes and they both receive any meaningful message to them.

For example let's say the legs are in the state *walking* and they received the message *player poisoned*. The legs FSM switch to state *reduced mobility* and set the *walking range* properly. Then they received the message *player blinded*. The legs FSM switch to state *paralyzed* and set the *walking range* accordingly. If the order of the 2 messages is switched due to different events in your game you can simply decide to ignore the message *player poisoned* if you are in the state *paralyzed* and the *walking range* will not change maintaining the correct lowest value. You can do the same example for your eyes.

Resuming, you split the FSM and then send messages to both about what is occurring to your player and they will decide what to do to their relatives attributes.

EDIT: referring to your code you should change the attributes in the **enter** method and not on each **process**
> 1 votes

---
Tags: fsm
---


# Question
Title: How do I create the visual effect of transitioning between night and day?
I am making an open-world project in Unity 4.5.5 and I want to create a visual effect of transitioning from day to night? *The Legend of Zelda: Wind Waker HD* has a great example of such a transition.

How can I achieve this? Can I use a script or do I need to create multiple scenes with different skyboxes to make this possible?

# Answer
First off, use this shader for your skybox: http://wiki.unity3d.com/index.php?title=SkyboxBlended

The default Skybox shader won't allow you to transition between two skyboxes (eg. one for day, one for night). The "blended" value of this shader can be adjusted in code, so adjust it over and over a little bit every frame.

Meanwhile, besides the skybox you also have to adjust the lighting. This depends on how your scene is illuminated; this could be as simple as gradually decreasing the intensity of your main directional light.
> 1 votes

# Answer
today I just crossed with the same need and I can point you towards some interesting resources.

Basically the technique implies: 1) blending various textures of your skybox over time: that implies writing a shader that blend in and out different versions of your skybox at different daytimes/exposures.

2) maybe you also want to blend different Lightmaps to maintain the world static illumination coherent

This is an asset that animate the skybox day cycle (the second link is a demo) http://u3d.as/content/o4karit-o/animated-day-night-skybox/5V2 http://sea-estate.ru/demo.html

This is a shader in the unify community that blends skyboxes: http://wiki.unity3d.com/index.php?title=SkyboxBlended

Another shader with smooth transition taken from an article: http://www.galawana.com/unity3d-advance-skybox-blending/

This is a package that allows you to animate and blend lightmaps. https://www.assetstore.unity3d.com/en/#!/content/5674
> 0 votes

---
Tags: unity, graphics, skybox
---


title: OOP design, keeping track of entities

text:
# Question
Title: OOP design, keeping track of entities
First, I would like to say that I have no experience with this and am still getting my head around OOP, so if something is really obvious, just point it out :)

I am designing a game and I am not sure of the best OOP design patten to use or if I am going on the right track. I have entities, but I don't know the best way of storing them. I am going to put them in a vector based on what I have seen on GDSE, but am not sure where to put that in my games code. I thought of putting them in a singleton manager class, but have read up on singletons and don't think that it would be wise to use them.

Or could I store entities in a world object? Like here ?

Is a singleton entity manager class fine in this case, or can you point me in the right direction for a different way of managing them.

EDIT: Oops.Even though I did multiple searches only now have I seen this (http://tinyurl.com/kv963nu) Although this seems to tell me to use global variables or singletons..

# Answer
A singleton works. A global works. I'll stand by that statement. I don't think they're the best solution for this particular case, though.

Yes, you can put all your `GameObject` instances into a `World` of some kind. The `World` then likely needs to be managed by an object if you plan to have more than one of them, e.g. some kind of `WorldManager`. This manager might itself by managed along with another collection of managers in some kind of `Engine` or service locator or the like. That object can be created on the stack by `main()`.

You want to avoid too many layers of cruft but you don't want to remove layers that you need to stay flexible.

Example:

```
class GameObject final
{
  World& _world;
  vector<unique_ptr<Component>> _components;

public:
  GameObject(World& world) : _world(world) {}

  World& GetWorld() { return _world; }
};

class World final
{
  vector<unique_ptr<GameObject>> _gameObjects;

public:
  void Spawn()
  {
    _gameObjects.emplace_back(make_unique<GameObject>(*this));
  }
};

class WorldManager final
{
  vector<unique_ptr<World>> _worlds;
};

int main()
{
  WorldManager worldMgr;

  // initialization code

  // main loop

  // cleanup code
}

```

The tricky part comes in to other managers that some components might need access to. There's lots of contortions you can put yourself through so e.g. your `PlaySoundOnEventComponent` can actually play a sound via an `AudioMgr` constructed in `main()`. A global might end up being a far easier and more efficient option for things like that, though.
> 5 votes

---
Tags: c++, oop
---


title: Game Maker x and y coordinates wrong

text:
# Question
Title: Game Maker x and y coordinates wrong
I'm making a game which the user can use the arrow keys to scroll left and right to view the map. I had an issue with the health bars of my enemies being drawn way off even though I set them to be drawn at the x and y position of the enemy.

I tried to debug using the following line to draw something at mouse\_x and mouse\_y:

```
draw_text(mouse_x, mouse_y, "X");

```

The X on screen would be at the correct position (the mouse position) when the mouse was at 0, 0, BUT as the mouse was moved farther right or down, the respective x or y offset became bigger and bigger, almost like I said to draw the X at `mouse_x * 1.5, mouse_y * 1.5`.

I'm using a view (view\[0\]) to allow the user to scroll through the map, and I thought this might be the source of the issue. This is the code I used to allow the user to scroll left and right:

```
if (view_xview[0] < room_width - view_wview[0]){
    view_xview += clamp(room_width - view_xview[0], 0, 10);
}else{
    view_xview[0] = room_width - view_wview[0];
}

```

The same code was used for moving left, but reversed.

# Answer
Make sure that you haven't accidentally chosen "Draw GUI" rather than "Draw" to put this code in. These are two very different things in Game Maker. Draw uses the absolute x and y coordinates, whereas Draw GUI uses the position relative to the window.
> 1 votes

---
Tags: game-maker
---


title: How to animate clouds

text:
# Question
Title: How to animate clouds
I am creating an open-world in Unity 4.5.5 and I do not know how to make the clouds move. This video of The Legend of Zelda: Wind Waker HD is a perfect example of the clouds moving in the sky. How can I create this?

# Answer
You might want to look into Skydome - it's a Unity package that allows for animated skyboxes.

http://www.pixelstudio.nl/?p=138
> 0 votes

---
Tags: unity, sky, skybox, clouds
---


title: Java 2D RPG Game smart pathfinding

text:
# Question
Title: Java 2D RPG Game smart pathfinding
Hello I have a top down survival game where you shoot bad guys(green squares). The player can collide with certain tiles and so can the mobs but I want the mobs to go around the tile if there is a path and not juts look in the direction of the player. How could I do this. Here is my mob class, collision class and block class

```
public class collision {

public static boolean iscolliding(Point p,block b){
    return b.contains(p);

}

```

}

```
public class block extends Rectangle {
private static final long serialVersionUID = 1L;

public static int blocksize = 40;
private int id;

private Image i;

public static Rectangle r = new Rectangle(Comp.mx, Comp.my, 1, 1);

public static boolean c = false;

public block(int x, int y, int id) {
    setBounds(x, y, blocksize, blocksize);
    this.id = id;
}

public void render(Graphics g) {
    g.setColor(Color.green);

    if (id == 0) {
        ImageIcon i62 = new ImageIcon("res/tiles/air.png");
        i = i62.getImage();
        g.drawImage(i, x - play.camx, y - play.camy, null);

    }
    if (id == 1) {
        ImageIcon i62 = new ImageIcon("res/tiles/dirt.png");
        i = i62.getImage();
        g.drawImage(i, x - play.camx, y - play.camy, null);

    }
    if (id == 2) {
        ImageIcon i62 = new ImageIcon("res/tiles/roots.png");
        i = i62.getImage();
        g.drawImage(i, x - play.camx, y - play.camy, null);

    }
    if (id == 3) {
        ImageIcon i62 = new ImageIcon("res/tiles/hellgrasses/hellsoil.png");
        i = i62.getImage();
        g.drawImage(i, x - play.camx, y - play.camy, null);

    }

}

public void setID(int id) {
    this.id = id;
}

public int getID() {
    return id;
}

```

}

public class blob {

```
public double x,y;

public boolean dead;

public Rectangle r = new Rectangle((int)x, (int)y,20,20);

public boolean canmove;

public blob (int x, int y){
    this.x = x;
    this.y = y;
}

public void tick(){
    r = new Rectangle((int)x- play.camx, (int)y-play.camy,20,20);

    if(!play.isPaused){
        if(x > play.p.x+ play.camx){
        x-=.2;
        }
        if(x < play.p.x+ play.camx){
        x+=.2;
        }
        if(y > play.p.y+ play.camy){
        y-=.2;
        }
        if(y <  play.p.y+ play.camy){
            y+=.2;
        }

        if(r.intersects(play.p.r)){
            play.p.health-=1;
        }
    }

    if(dead){
        if(new Random().nextInt(100) >= 95){
            play.hp.add(new healthPack((int)x,(int)y));
        }
    }
}

public void render(Graphics g){
    g.setColor(Color.green);
    g.fillRect((int)x - play.camx, (int)y -play.camy, 20, 20);
    g.setColor(Color.red);
    g.drawRect((int)r.x , (int)r.y, 20, 20);
}

```

}

if you need any other info just leave a comment

# Answer
You might want to implement a 2Ds pathfinding algorithm and call it in your tick() method. There are several pathfinding algorithms, but the A\* algorithm might be the best for you as it is rather simple to understand and code.
> 0 votes

---
Tags: java
---


# Question
Title: Sending RPC calls from server to client inside Unity
In my game inside Unity, I have two scenes setup. One for the main server ( acts like authoritative server ) and the other scene for my client. The game starts once my client connects to the server.

Now I am able to send RPC function calls from my scripts in my client scene to the server but I am not able to do it the other way around.

\** Further edit to my code after comments \** \*********** This is my client side script attached to GameObject CursorDetection inside Scene2 \*****

```
 using UnityEngine;
    using System.Collections;

    // ON THE CLIENT SIDE
    public class CursorDetectionScript : MonoBehaviour {

        private bool hasGameStarted = false;
        void Update()
        {
           if (Input.GetMouseButtonDown(0))
           {
              networkView.RPC("mouseDown", RPCMode.Server,true);
           }
        }

        [RPC]
        public void mouseDown(bool isMouseDown)
        {

        }

    }

```

\**** On the server side script inside scene1 \*******

```
private void OnPlayerConnected(NetworkPlayer player)
{
    Debug.Log(" PLAYER CONNECTED " +player);
    networkView.RPC("AddNetworkPlayer", RPCMode.AllBuffered, player);
}

[RPC]
public void AddNetworkPlayer(NetworkPlayer player)
{
    playersList.Add(player);
    Debug.Log(" FIRST PLAYER IS " + playersList[0]);
}

 if(startGame)
 {
    networkView.RPC("SendMessageToClient1", RPCMode.AllBuffered, playersList[0]);
 }

[RPC]
public void mouseDown(bool isMouseDown, NetworkMessageInfo sender)
{
    isMouseDown = true;
    Debug.Log("CAN PLACE PANELS NOW" + " VIEW IS " + sender.sender.guid);
}

```

\**** back on the client side script inside scene2 I called the SendMessageToClient1 function call \*******

```
[RPC]
public void SendMessageToClient1()
{
    Debug.Log(" INSIDE CLIENT 1 ");
}

```

# Answer
When communicating between client and server you're using RPC calls. These RPCs are possible with the `NetworkView` script attached to an object. For simplicity, it's easiest to attach your communication scripts (the ones making invoking the RPCs) to the same object that the `NetworkView` script is attached to. This needs to be done on both Client and Server.

The easiest way to accomplish this is to create a communication relay object. This object has both the communication scripts and NetworkView script attached to it.

Your communication scripts will contain the RPC signatures for both the server and the client, in the same file.

So for example, your communication script might have a `MouseDown` RPC:

```
public void MouseDown(bool state) {
    if (Network.isServer) {
       //If we're the server, just call the method directly
       SetMouseDown(Network.player, state);
    } else {
       //Otherwise we're a client, make an RPC call on the server
       SendMouseDown(state);
    }
}

private void SendMouseDown(bool state) {
    networkView.RPC("SetMouseDown", Network.player, state);
}

//This method will only be called on the server.
[RPC]
public void SetMouseDown(NetworkPlayer clientID, bool state) {
     //dictionary for client mouse down states
     mouseDownState[clientID] = state;
     ConfirmMouseDown(clientID, state);
}

private void ConfirmMouseDown(NetworkPlayer player, bool state) {
     if (Network.isServer) {
        //If we're the server, print a message locally and call an RPC on the client
        // to activate the else clause of this method
        PrintMessage("Player: " + player + " set his mouse down to " + state);
        networkView.RPC("PrintMessage", player, "Server received my mouse down state change to " + state);
    }
    // this should be called on a client, so there is no 'else'
}

[RPC]
private void PrintMessage(string message) {
    Debug.WriteLine(message);
}

```

Now a call to `MouseDown` will work on either the client or the server. This is pretty useful in the case of the server being a player as well. They share RPCs and the server and client can communicate easily.
> 1 votes

---
Tags: unity, networking, multiplayer
---


# Question
Title: How would you declare a Texture object in the libgdx skin json file, using a region from a texture atlas?
I have a texture atlas that is linked to my `skin.json` file. The atlas contains a region named "game-title".
I would like to declare a `com.badlogic.gdx.graphics.Texture` object in the json file, to retrieve it later in my code via `skin.get(name, Texture.class)`.
I tried declaring it as follows, but it does not work - exception gets thrown - `com.badlogic.gdx.utils.SerializationException: Class cannot be created (missing no-arg constructor): com.badlogic.gdx.graphics.Texture`:

```
"com.badlogic.gdx.graphics.Texture": {
  "game-title": {name: "game-title"}
}

```

What am I doing wrong here? What would be the correct way to do this? Is trying to declare a `Texture` in such a way a correct thing to do, in the first place?

Many thanks in advance for your feedback.

# Answer
All of the atlas regions are automatically available through the skin as TextureRegions. I just tried it, and works without modifying the json file.

You can just call `skin.get(name, TextureRegion.class);` or `skin.getRegion(name);`

Unfortunately, the skin docs are not very clear about this. libGdx docs
> 3 votes

---
Tags: java, libgdx, texture-atlas, skinning
---


# Question
Title: Why Is My AABB Collision Detection Not Working
I am going to be making a 3D game and I need to be able to test for accurate collision. I was able to get bounding sphere collision working (too inaccurate to be used for the whole game), but AABB collision is much harder (and more accurate!). I used the code from this website and I can't seem to get it to work. I have my code below for the AABB collision method:

```
public boolean isColliding (AABB other) {
Vector3f otherMax = new Vector3f(other.pos.x + other.w, other.pos.y + other.h, other.pos.z + other.d);
Vector3f otherMin = new Vector3f(other.pos.x, other.pos.y, other.pos.z);

Vector3f thisMin = new Vector3f(this.pos.x + this.w, this.pos.y + this.h, this.pos.z + this.d);
Vector3f thisMax = new Vector3f(this.pos.x, this.pos.y, this.pos.z);

return (otherMax.x > thisMin.x && otherMin.x < thisMax.x
        && otherMax.y > thisMin.y && otherMin.y < thisMax.y
        && otherMax.z > thisMin.z && otherMin.z < thisMax.z);
}

```

I'm not quite sure where this is going wrong, any ideas?

# Answer
You have your `thisMin` and `thisMax` declarations reversed.

```
Vector3f thisMin = new Vector3f(this.pos.x + this.w, this.pos.y + this.h, this.pos.z + this.d);
Vector3f thisMax = new Vector3f(this.pos.x, this.pos.y, this.pos.z);

```

should be:

```
Vector3f thisMin = new Vector3f(this.pos.x, this.pos.y, this.pos.z);
Vector3f thisMax = new Vector3f(this.pos.x + this.w, this.pos.y + this.h, this.pos.z + this.d);

```
> 1 votes

---
Tags: java, collision-detection, 3d, lwjgl, aabb
---


# Question
Title: How do I calculate the distance between a point and a rotated rectangle?
This question is similar to another one about axis-aligned rectangles. However, I specifically want to calculate this for *rotated* rectangles.

---

I have a rectangle with a *(cx, cy)* for the center point and a *width*, and *height*, and a *(x, y)* for the test point, as well as a *θ* for the angle of rotation.

What's the fastest way to determine the distance between that point, and the nearest edge of the rectangle? If the point is inside the rectangle, the distance should be zero.

I believe that there is going to be only a small change to the equation in the linked question, but I have no idea what it might be.

# Answer
> 2 votes
Just rotate the point at an angle of -θ around the center of the rectangle.

```
relx = x-cx
rely = y-cy
rotx = relx*cos(-theta) - rely*sin(-theta)
roty = relx*sin(-theta) + rely*cos(-theta)
dx = max(abs(rotx) - width / 2, 0);
dy = max(abs(roty) - height / 2, 0);
return dx * dx + dy * dy;

```

Also, remember this is still the distance squared, so you need to take the square root of it to get the actual distance

---
Tags: java, collision-detection, mathematics, geometry
---


# Question
Title: Is object-oriented underestimated for game development?
I'd like to understand whether the object-oriented paradigm applied to game programming is bad, or whether it's just an urban legend.

A friend of mine is developing a game with HTML5 and Javascript using data-oriented paradigm, and he's trying to convince me about the issues of the object-oriented design.

His best example is this:

"If you have a Tree (a static object in the game) and a Warrior (an object which can perform some action, like movements, attacks..) and suddenly you decide to put in your game a Warrior Tree, how do you do it by object-oriented?"

He is right or he is underestimating the "power" of the object-oriented paradigm?

# Answer
> 0 votes
If your programming language supports multiple inheritance, you can inherit from both the Tree and the Warrior and get a TreeWarrior. C++ supports multiple inheritance:

```
class TreeWarrior : public Warrior, public Tree{
    ...
};

```

In Java you can't do this since it doesn't support multiple inheritance. The problem with programming languages like JavaScript is that there is no type safety.
I don't think object oriented programming languages are a limitation. In fact, JavaScript is an object-oriented programming language. I think your friend was thinking of Java as the limitation. Although there are tricks to simulate multiple inheritance in Java, I agree that it is a bit limited.
To answer the question about if he is underestimating the power of the object-oriented paradigm, I think yes. Just think of any AAA game. Most of them are programmed using C++.

# Answer
> 3 votes
It's not that object oriented paradigms are bad for game development, they do the job just fine. Though, there are downsides to doing everything with a typical OOP mindset.

1) Inflexible, you can't reassemble behaviors and properties of your game objects on runtime as they are tied to fixed class hierarchies.

2) Slower unless you mix OOP with data oriented design. Putting your data in classes potentially loose around the heap is a lot slower to process, while keeping all data of a given domain in a contiguous chunk of memory will provide a lot faster iteration times.

Other than that, if you want to make a full game in the OOP paradigm, feel free to, it has been done countless times before from indie to AAA games and it worked. Chances are you will come to the same conclusions as everyone else and end up switching to data oriented design in full scale too. With this, I mean mostly going into the Entity-Component-System paradigm, as it seems to be the golden standard for today's AAA development.

I personally use a fully fledged ECS setup, and then have a thin layer of OOP referencing entities and components through handles, so I have utility methods to control each type of entity and its data. It works like a charm.

Check the ECS posts here: http://bitsquid.blogspot.pt/ I found them to be really GOOD in many ways for modern development.

---
Tags: java, data-oriented
---


title: How to temporarily disable input?

text:
# Question
Title: How to temporarily disable input?
I have made a jump script and I want all input to be ignored when you are in mid air (so that way you don't have infinate jumps). How to do this?

# Answer
> 1 votes
The solution is not to disable input, it's to check to see if the user can jump. If you disable input: A. The players not going to be able to do anything. They won't be able to guide the character. They wont be able to grab ledges. Nothing. B. You'll still need to check to see when the user can jump because you'll need to know when to enable input again.

As a basic concept:

```
if (!isInAir) // if you are not in the air
{
    // do jump
}

```

If we were to implement this as a generic test:

```
using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour
{
    private bool IsInAir;

    void Start()
    {
        IsInAir = true;
    }

    void OnFixedUpdate()
    {
        bool attemptJump = Input.GetButtonDown("Jump");

        if (!IsInAir && attemptJump) // if we are not in the air, and we are attempting to jump
        {
            rigidbody.AddForce(0.0f, 10.0f, 0.0f);
        }
        // other movement stuff

        IsInAir = true; // This will be set back to false if we are contacting an object.
    }

    void OnCollisionStay(Collision other)
    {
        // we are contacting an object. We can jump off this object.
        IsInAir = false;

        /* Todo: Limit jumping posibilities by checking contact normal and object information
            contained in 'other'. */
    }
};

```

The above sample has not been tested, and should consider you as able to jump whenever you are contacting a game object.

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


# Question
Title: Building a C-E engine in a high level language, how can I integrate optional lower-level components that own overlapping state?
To clarify, by overlapping I do not mean overlapping between said components, but rather, let's say I have:

* My entity contains components, and a parent-children system. Call it a mandatory `Hierarchy` component if you may.
* A `Transform` component that has `x`, `y`, `r`, `sx`, `sy`, and `relative` properties.
* A `Drawable` component family that is drawn by a `RenderingSystem`, it uses position information from `Transform`.
* Script components that can read and manipulate position of objects.

Now, what I want to add is a `Box2DPhysics` component family(shape(s), body) and a `Box2DPhysicsSystem` that internally just updates the physics world, but the problem is: The `Transform` component is not compatible with that. Box2D has its own internal position, rotation, velocity information, that here can only be accessed via getter and setter methods. Now, it's not impossible for me to wrap the Transform component's fields and methods to use said getters/setters, but then I'm implementing half of the functionality in the `Transform` component...

Now, what should I do? Some options that come to my mind would be:

1. Make the physics component override the `Transform` component, somehow. Either by writing its position info into `Transform` every frame, or something like that
2. Allow some components to be two or more subcomponent, such as `Box2DPhysics` being both a `Physics` component and a `Transform` component.
3. Not use Box2D whatsoever, write my own verlet-based physics engine, likely significantly slower, but functional and fully interoperational with the rest of the code.
4. "Freeze" some of the components and functionality, effectively making it 100% built-in - prohibit the user from replacing or implementing few basic most important components, and handle things like this interally.

I feel like personally I'm leaning towards #2, but honestly, I just don't know. It's probably my anxiety/indecisiveness that is at fault, but I feel like I simply cannot proceed without getting someone's opinion.

# Answer
While you may find it useful to cache your entity's position in your `PhysicsComponent`, it's primary purpose should be to supply physical characteristics about the entity such as mass, volume, rigid properties, etc.

Your `PhysicsSystem` would be responsible for obtaining the current position from your `Transform`, the velocity/accelleration from your `Velocity` component and using those in conjunction with the physics library to force the entity to move appropriately. After the simulation, the system in turn updates the `Transform` position and orientation appropriately as well as notifies objects of collisions.

The benefit here is that if you replace your physics library, the remainder of your code should continue to work and only the `PhysicsSystem` needs to be adjusted to work with the new library. This doesn't conform to any of your points exactly, but does lend itself to being very compartmentalized and decoupled to permit ease in refactoring as needed.
> 1 votes

# Answer
Here is another thought, Although I'm not sure how good it will perform:

The thing is, the Transform component is mandatory, but it doesn't really matter the internal class is, as long as it provides position, rotation and other details about an object's spacial properties.

What I mean is, you can have to classes, both providing all the information necessary. But a class doesn't need to have both of those components. In fact those two (physics and transform) can not be present at a same time, but only one them should be attached to each entity. To make it even easier they might even share a base parent component class.
> 0 votes

# Answer
In my implementation I have a `ITransform` interface. The transform is implemented either with a standalone `Transform` (implementing the `ITransform`) or when using 2D physics with the `Box2DComponent` (which also implements the `ITransform`).

This way I can chose to directly use physics or not depending on each entity's purpose and both types can coexist in the same game even if their transform components don't register in the same systems.

An entity can only have one `ITransform` so this setup works well and I can even switch basic entities to use Box2D with minimal changes in the game logics.
> 0 votes

---
Tags: component-based, lua, love2d, entity-component
---


# Question
Title: How do I balance skill/luck in a forum game?
I am trying make a forum game where members of the forum can play daily, with role-playing elements, and tactical decisions. I've hosted werewolf games before, but I want this to be a little more involved. Mt new venture is a U-Boat game, where 10 members of the forum can sign up. The game takes places in several phases, such as Patrol, Intercept, Attack, Evasion, Re-engage/Escape. In each phase the forum spits out some situations based on random numbers generated by the forum. The players make decisions and the results of their decisions advance the game to the next phase (or not).

For example: in the Patrol phase, the players basically roleplay, chat, and BS...entertain themselves. Each day the random number generator cranks out a number for contact. Let's say the RNG spits out a 90, which means enemy convoy spotted. (89 and less, no contact; 90 and up = contact).

The game moves to the Intercept phase, and the RNG spits out a number that tells the player the course of the convoy. In simple terms, the convoy can be moving away from the U-boat, parallel, towards, etc.

**Here's where I need help:** the players should make some kind of decision, such as "flank speed toward the convoy", "flank speed 45 degrees port" to intercept a convoy on a parallel course, etc. Now, how do I grade the decision?

How do I construct it so that the smarter/safer his choice, the better the results? Obviously, I cannot use the RNG for the outcome, there has to be some way to balance his skill in making a good decision.

Anyone have any ideas? I apologize if this is not the right place to ask this type of question. thanks! Neal

# Answer
> 1 votes
What you need are game mechanics.

Game mechanics are rules which govern how a game works. They usually consist of three things:

1. Variables which make up the game state. Some variables might be known to the player (like their current depth, position and heading or obvious damage to their boat), some might be hidden (whether or not the enemy has already spotted them or non-obvious damage to their ship).
2. Actions each participant in the game (player or NPC) can perform, which have a different chance of succeeding depending on the variables and which then change the variables depending on whether or not they are successful.
3. Win- and lose conditions, which are combinations of variables which cause one player to win or lose the game. In the context of an u-boat RPG, a lose-condition could be that all crewmembers are either dead or left the ship. The win-condition could be to fulfill some mission and return to a friendly port.

The goal of every player is to perform actions to alter the game state variables in a way that their win-condition occurs and their lose-condition does not occur.

Variables you could trace are distance to target, current heading and speed of target and u-boat, depth of u-boat, damage to either ship etc.. How far you want to go into detail depends on how much realism you want and how much bookkeeping you are willing to do. For narrative RPGs it is often better to not go too far into detail to still leave room for imagination, improvisation and narrative freedom (having a game mechanic which governs when the first ship appears, is for example something I would not make a game mechanic for, so you retain the narrative freedom to decide to make a ship appear the moment you notice that the game becomes dull and needs some action).

Possible actions the player could perform is change their heading and/or speed or change their depth. They could fire their weapons, where the success chance depends on the current game state. I don't know much about naval warfare, but I would assume that the current distance to the target is at least one variable which would be important for the probability to hit the target with a torpedo. There could also be other variables which are more or less important (size of target, what kind of torpedo, experience of crew, weather and ocean currents, phase of the moon, whatever).

One question you need to ask yourself is: **Do you want the players to know your game mechanics?**

Some mechanics should be shared because they are character knowledge, like for example the minimum, optimum and maximum range of their weapons. These are things every real-life u-boat captain should know about, so your players should know them too.

But when you reveal too much about how the game works, the players will focus less on the roleplaying experience and more on the metagaming. Smart players will be more concerned with finding loopholes in your rules which give them an unrealistic advantage than with figuring out what their character would do in the current situation.

But when they do not know about your rules, they might feel cheated when events don't turn out the way they expect them to. You will also have a bit of a communication problem because players aren't aware of what actions actually have a meaning for your game mechanic and might talk at great length about details of their actions which you don't actually simulate while not saying anything about those details which actually matter. You can control that by asking specific questions ("do you go to *slow* speed, *medium* speed or *high* speed?"), but then you risk revealing too much about your mechanics which you wanted to avoid.

---
Tags: board-game
---


# Question
Title: Required number of images for octagonal tiles
I'm planing to write a game based on octagon tiles. Currently I'm wondering how many images I really need. That is something about graph theory, I know that, but not only.

I want to connect each side of the eight sides, but in some cases I also want to connect all eight sides or just two so the complexity grows immense. If I'm not totally confused that ends in 88 which is 2048. Well of cause there are already many dublicated e.g. left to right is equal with right to left. When I'm very tricky I can rotate the image of left to right which I rotate by 90° to get top to buttom. I'm sure there are quiet more things like like mirroring.

My question is now how many images do I really need?

Here is my basic idea as image, of cause it still has some problems, as you can see on my image too but I think it should not be too hard to find a simple solution for such cases.

# Answer
> 3 votes
If you write a 1 for a connection and 0 for lack of connection, and have 8 sides, then you can write out the configuration of an octagon as a bit string. I'll order them as east, northeast, north, northwest, west, southwest, south, southeast. If north and west are connected to neighbors and other directions are not, this would be written 0 0 1 0 1 0 0 0.

First question is, how many possibilities are there? There are 8 numbers, each with 2 possibilities, so that's 2^8 = 256 possibilities.

However, rotation and mirroring mean we can reuse some of them. I'm not 100% sure this code is correct, but I found that there were no mirrors to remove after removing rotations:

```
def all_sequences(n):
    if n == 1: return [(0,), (1,)]
    rest = all_sequences(n-1)
    return [x + (0,) for x in rest] + [x + (1,) for x in rest]

def rotations_of(seq):
    return [seq[i:] + seq[:i] for i in range(len(seq))]

unique = set()
for seq in all_sequences(8):
    for rot in rotations_of(seq):
        if rot in unique:
            break
    else:
        unique.add(seq)

print(len(unique))

```

It prints 36 different octagon neighbor patterns. Is there a mathematical way to compute this? Probably, but I don't know what it is. I found this entry in The On-Line Encyclopedia of Integer Sequences, if you want to read more.

There might be more ways to reduce the number of sprites, but I think 36 is the upper bound.

# Answer
> 1 votes
Unless you want to allow octagons to overlap (when you would, you would be in quite a lot more trouble), it is impossible for two adjacent edges (a diagonal and an orthogonal) to be both connected to another tile. This makes stuff a lot easier.

Separate each of your octagons into 9 tiles like this:

You need one set of tiles where the diagonals are connected and the orthogonals are not:

And one set where the orthogonals are connected but the diagonals aren't:

The center tile is identical in all cases. Also, the connected edge-tiles opposite of each other are identical in both of above images, but the unconnected edge-tiles aren't. So you need a total of 1+2+4+2+4 = 13 images.

---
Tags: 2d, mathematics, tiles, game-theory, graph-theory
---


# Question
Title: Unity: Why do my normals flip during an animation?
This problem boggles my mind. I have an animation running on a face object (imported from Blender). At a few points in the animation, the normals switch direction! It causes the mesh to blink.

Of course this animation won't work in its current state. Even odder, I slowed down the animation sample in Unity to 1 so I could isolate the frames it happens on. There are no keyframes on the face when this happens!

What could be causing this? It only happens on this one animation. I can't find anything with extensive web searching. I've also tried recalculating normals and applying transformations, but it doesn't help.

---

These screen shots depict the same two frames, one frame before it happens (left) and the frame when it happens (right), just from different angles.

I'd very much appreciate any input or guidance to fixing this!

# Answer
I 'think' I know what this is. This is not about the normals, it's about the choice of Binormal and Tangent vectors that the mesh exporter plugin chose - they are usually selected based on UV and don't consider the Winding Order of the polygon: the Binormal and Tangent have the wrong handedness sometimes, and if I remember correctly, there is a way we can detect and flip it in the shader. If I'm completely off track, it's still probably a bug in the exporter, not a bug in the engine.
> 1 votes

---
Tags: unity, animation, blender, normals, bug
---


# Question
Title: Handling differing inventory items on use interactions
Hey there my fellow programmers. Looking for a little input into a potentially smelly code problem (I was about to post this on the Code Review SE, let me know if that's the more proper place).

After looking at a few of the answers here on setting up an rpg like inventory and using a component based system, I've come up with a format to creating items, here are a couple of examples.

```
Entity potion = new Entity("Potion", new Item(100,50), new Healing(75,0));
Entity elixer = new Entity("Elixer", new Item(50, 25), new TempStatIncrease(0,5,...));

```

Here are the classes involved.

```
Entity Class
IComponent[] components
string name

IComponent Interface
ComponentType componentType

Item Class : IComponent
int purchasePrice
int resaleValue

TempStatIncrease Class : IComponent
int strength;
int agility;
...

Healing Class : IComponent
int hpAmount;
int mpAmount;
Heal(Character character);

```

Now where I run into a bit of design trouble is how to handle interacting with these items. If I have "Potion" selected, and hit the use key in my inventory, it brings up the character list for me to select a character. When I select a character this is the code that would run:

```
Character Class
UseItem(Entity entity)
{
    foreach(IComponent component in entity.components)
    {
      switch(component.Type)
      {
         case Healing: { ((Healing)component).Heal(this); } break;
         case TempStatIncrease: { ((TempStatIncrease)component).Increase(this); } break;
         case ... //This could get ugly quick.
      }
    }
}

```

I feel like the above approach is prone to disaster. It's a switch for one, I have to modify this every time I want a character to be able to use a new component. Two, I have to do a not-so-nice cast to the concrete component. Add to the fact I have to create a new ComponentType enumeration for each new component, another piece of maintenance.

Any thoughts on how I might be able to re-factor my implementation to remove the potentially disastrous switch statement and that complex component casting?

# Answer
> 2 votes
If `Component` had a method `ActOn(Character)`, you could simply call `component.ActOn(this)`. Each subclass could implement appropriately. For example:

```
Healing.ActOn(Character character) {
    Heal(character);
}

```

# Answer
> 1 votes
There are often lots of items in a game that can be used in varying ways. One generic way to do this is to implement an interface such as the following:

```
 class IUsable {
 public:
   virtual void Use() { /* does nothing */ }
 }

```

For items which are usable on the current player such as potions, their `Use` method send an event to the current player with the heal amount or power amount to be gained followed by a signal to remove the entity (used item) from the player's inventory.

For items that are usable only on targets, the `Use` method might obtain the current target of the owner and if a target could be obtained and is valid, then uses the item on that target; such as a costume or perhaps an aura buffer, etc.

The same concept could be used for `IEquippable`, `IToggleable`, and so forth where the former is for putting on a piece of armor and the latter might be for opening a treasure chest, door, or some other object that essentially has a *true/false*, *on/off*, *0/1* type concept. These interfaces can be linked to a component and system or scripts as needed depending on your design.

---
Tags: component-based, rpg, inventory, refactoring
---


# Question
Title: In XNA 4, how can I access SpriteBatch's transformMatrix in my shader?
I would like to use a custom effect with a regular XNA `SpriteBatch`. I have a 2D camera which computes a transform matrix, so I need my shader to take this into account.

I have put a world matrix property into my shader:

```
float4x4 World;

```

However, it does not get set by `SpriteBatch`:

```
spriteBatch.Begin(spriteSortMode, blendState, samplerState,
    depthStencilState, rasterizerState, effect, camera.WorldToScreen);

```

Everything is rendered properly if I set it manually in the draw loop:

```
effect.Parameters["World"].SetValue(camera.WorldToScreen);

```

How can I set up my shader parameters to make `SpriteBatch` set them up correctly?

# Answer
That is explained here by Shawn Hargreaves, the Xna lead coder

https://shawnhargreaves.com/blog/spritebatch-and-custom-shaders-in-xna-game-studio-4-0.html
> 1 votes

# Answer
In the SpriteEffect source, the world matrix is actually `float4x4 MatrixTransform`
> 0 votes

---
Tags: xna, shaders, hlsl, graphics-programming, spritebatch
---


# Question
Title: How to make the damage inflicted to the enemy and the main character more unpredictable
I am developing a small mobile game. The enemy can damage my player by throwing objects at his side, and the player can damage the enemy by hitting him with a bat.

For the moment, I am calculating the damage that was caused by the player or the enemy in a very simple way. For example, my enemy has 100% of health. When the player hits him with a bat, the enemy is losing 10% of his health. So after 10 hits the enemy is "dead".

But this is not interesting. The game process is very simple and predictable: you are moving, see the enemy, hit him 10 times, and the move to the next enemy. When the enemy hits the player,the player loses 10% of his health. That is not cool (the game process is very static).

An alternative, is to use random integer values to calculate damage values. Can anyone give an idea, how to make damage process more interactive and unpredictable, and how to make proportional link between player health and enemy health and the damage.

# Answer
These are entirely design considerations and there's many ways to go about this. For starters:

1. Instead of strict damage, give it a range. ie. the bat doesn't do "10 damage", instead make it do 8-12 and randomize it between those values.
2. Give the enemy a chance to dodge or the player a chance to miss based upon some small percentage. This must be reflected visually (and audibly?) somehow.
3. Give the enemy/player a chance to crit for 2x or 3x damage.

If desired (and fitting within your design) the player may be given the ability to "upgrade" any of these through the actual weapon or skill.

For the second part of your question regarding linking the player's health that would entirely need to make sense within your design. One example would be that as a character's health is reduced their attacks get weaker. The other side to that coin could be that as a character's health is reduced adrenaline kicks in and their attacks get stronger. It all depends on how you want to spin it and that the mechanic makes some sense as opposed to being arbitrary.
> 0 votes

---
Tags: unity, mobile
---


title: Key mapping for a 2-players game

text:
# Question
Title: Key mapping for a 2-players game
I've been struggling for a while trying to figure out the best way to map two players on a single keyboard. Let's consider something generic:

* Arrows
* Validation
* Cancel (optional)
* Some common actions shared between the two players (start, reset, etc.)

So far, I used:

* **P1:** WASD + \[Space or Tab\]
* **P2:** Arrows + \[Enter or Return\]
* **Common**: R for reset

The problem is that some configuration can be uncomfortable on certain keyboards (especially when there is no keypad). Plus some players like to have the direction on left hand (FPS style) and others on right hand (platformer style). Also SHIFT is usually not a good choice on windows because of the sticky keys feature.

Also I'd like to avoid using a settings screen (kind of heavy for a small game). I guess a config file would be OK, but is there another way to handle this problem that would make every one happy?

# Answer
Let the user configure the bindings from an options menu in the application. Players might be using QWERTZ (German) or AZERTY (French) layout keyboards, Dvorak layout keyboards, joysticks, etc., and they don't want to have to learn Yet Another Config File Language.

But still, a lot of players will want to jump in and play without changing any settings. So you still have to choose good defaults and show them to the player when the game starts. Consider this:

* Right player moves with arrow keys and does actions with apostrophe and Enter.
* Left player moves with RDFG and does actions with Z and X. Do not straddle the line between TGB and YHN because a lot of "ergonomic" keyboards split the left hand and right hand keys here.
* Single player mode should allow input from either side, so that players used to the common emulator default of arrows and ZX can jump in.
* Common actions can be done while the game is paused. Common back/pause is Esc.
* Show these keys to the players at the bottom of the first screen of the game, so that the player can get used to them before being in any real danger.

As Christian pointed out in this question, a lot of keyboards can't handle a lot of simultaneous presses. USB keyboards in particular are limited to no more than six, which isn't enough for a diagonal press and both actions on both sides. So I strongly encourage you to also support USB joysticks, be they Xbox 360 controllers or USB Human Interface Device (HID) class joysticks. SDL and SDL-wrapper libraries such as Pygame will recognize either, but if you're developing a Windows Store game, only Xbox 360 controllers will work because Microsoft forbids DirectInput in Windows Runtime. When you save the input configuration file, also save the VID/PID or name of all connected joysticks. This way, when the application starts with a different set of joysticks than were plugged in last time the application started, it can notify the player that joysticks were added or removed and ask the player to reconfigure the joysticks by pressing a button for each action in turn.
> 3 votes

# Answer
The best way to solve your concerns for flexibility and comfort of the user is to certainly allow them to define their bindings as you have described.

Whether you opt to do this through a configuration file they manually edit or an in-game screen that allows them to select the action and then press the key configurations for said binding is entirely up to you. If it were me, I would prefer the latter mainly because it avoids human error in creating the file and reusing a lot of the existing logic you'll need to decode the file into some internal representation as well (aka text to actual keys).
> 5 votes

# Answer
It depends on the keyboard in question. There are certain combinations of keys that don't result in all the keys registering as pressed. For example, pressing A and Q at the same time might only register Q.

Since this depends on hardware details, there's no one solution for you.

One good solution I saw was the KeyJam for Star Control 2's Super Melee mode. It allowed the user to hold down a bunch of keys, and the program would tell you which keys it thought were held. That way, each user could find a set of keys that worked for his setup.
> 2 votes

# Answer
You could have the users configure their settings when they choose to start for the first time. Some games have you manually set your gamma and screen size, as I am sure you have experienced before. You could prompt each player to select what key they would want to use for the functions you have in your game. A Config file seems less intuitive. A options menu would be ideal, where the user sets the sounds/video options and sets key functions. Since your game consists of 9 keys, it would be a very small amount of work to incorporate, and take care of any keyboard setup the users may be using.
> 1 votes

---
Tags: multiplayer, keyboard, user-experience
---


title: Stop vibration (bouncing efect)

text:
# Question
Title: Stop vibration (bouncing efect)
I have a game with some ball and I want to make it bounce. I already have movement, gravity, collisions implemented, I only need to make it bounce. Thing is, using this code:

```
player.getVelocity().y *= Player.ENERGY_LOSS;
player.getVelocity().y = -player.getVelocity().y;

```

indeed it makes the ball bounce but obviously the .y will get to very small values causing the ball to 'vibrate' and never stop.

How can I 'clamp' this value? Let's say I just want the ball to bounce just 2 - 3 times?

# Answer
> 0 votes
I solved the problem by 'rounding' player.getVelocity.y value

```
player.getVelocity().y *= Player.ENERGY_LOSS;
player.getVelocity().y = -player.getVelocity().y;
player.getVelocity().y = (float) Math.round(player.getVelocity().y);

```

so now, depending on the height the ball falls it bounces from as low as 0 times to 2 - 3 - 4 depending on the height. Of course it no longer vibrates because player.getVelocity().y no longer gets to really low values and istead when it's low enough it gets rounded straight to 0 (stop).

# Answer
> 3 votes
Most physics engines have a minimum velocity at which point it is snapped to zero and moved to a "not moving" set of objects, for example 1e-5 m/s. Obviously the value will depend on the scale of your game.

For example:

```
if(player.getVelocity().magnitude() < 1.0e-5) player.setVelocity(float3(0,0,0));

```

---
Tags: jumping
---


# Question
Title: What sort of AI is applicable to a board game of this complexity?
I am thinking of creating an AI for the card/board game Summoner Wars (by PlaidHat Games). It's a very nice tactical game for two players, with simple rules but quite deep.

I have considered min-max trees, Monte Carlo Tree Search (UCT), expert systems (i.e. a set of coded rules/behaviors) but I don't think any would give a good result.

Here are the facts that make creating an AI difficult:

**1. The basic rules are simple, but each card has its own twist/exception on the rules. The game is of the expandable card game kind.**

This makes it hard to use an expert system. Because of their cards' special rules, some factions play very differently from each other. Coding a strategy for each faction doesn't scale as the number of factions increase and simply doesn't work with custom-built decks.

Because of that, evaluating the board position without simulating what the opponent could do is very hard as well.

**2. The number of possible actions is too big.**

The cards are played on a 8x6 grid battlefield. During your turn you can summon new units, play events (sometimes with a choosable target), move up to 3 units, attack with up to 3 units and discard cards from your hand. Exploring all the possible ways you can do this stuff is just too expensive. You definitively have to prune your search tree (for a min-max AI).

**3. It's hard to evaluate actions without thinking about the future.**

It's hard to prune "bad moves" because depending on your cards (and your opponent's) some seemingly stupid or useless actions can be key to victory.

For instance, some human players kill their own units (a bad move in the short term).

Other example: the last phase of the game allows you to discard some cards from your hand to build more magic. *That's key to be a good player* but very hard to decide. Do I need more Magic? How much? Discarding more cards exhausts my deck faster (which is bad). And if yes: which ones? (knowing that I won't be able to play them.) And of course this is even twisted by the fact that some factions love to discard more cards because of some special effects.

Also, because the rules actually depend on the cards being played, you can't easily evaluate the position at the end of your turn. You also need to simulate your opponent's turn to see if some special abilities may ruin your position.

In my opinion, 2. and 3. make a min-max tree search unsuitable.

**4. It's a game with hidden state.**

There are the shuffled draw piles, your opponent hand... I don't mind if the AI "cheats" and looks at them, but it must not be obvious to the player! For instance there are some events that you can only play if you have less units on the battlefield that your opponent. It would be very annoying if the AI played aggressively all the time... and kills its own units to reduce headcount just the turn before I draw one such event!

**5. It's a game with randomness.**

Drawing cards of course, but I don't think this is a key factor for the strategy. Especially since most cards in the draw pile are the same. On the other hand, combat is done with dice. So if the AI decides to attack a unit, it's hard to say what the outcome will be (with which probability). Especially since many cards in play may change the actual rules regarding this (like: the number of dice rolled, change the value on some dice, remove one die roll, allow re-rolls, change the threshold value for a hit, and so on...)

MCTS was promising, but I have 2 issues with it. First how to handle the random aspects (dice rolls). Second, no paper on MCTS points it out, but I think that it only works well for games where every move brings you closer to the end of the game. Playing Summoner Wars randomly can easily result in an unending game (moving units around on the board)!

I know this is a long question, but does anyone have any idea how to write an AI for such a game? The goal is not to be a perfect player, but to provide a challenge to a human... and the game is very subtle, tactical and precise (for a human player at least).

# Answer
MCTS can work very well for this kind of game; the principle advantage is that all you have to do is implement the rules, and all the behavior that depends on their complexity is automatically included. MCTS is not troubled by randomness, hidden information, or a large decision space. My AI for "Euphoria" at Boardspace.net, plays as well as most human players.

Randomness (dice rolls, card draws etc.) and hidden information (opponent choices you do not know the value of) are handled by re-randomizing at the top of the move tree before each random game.
> 1 votes

---
Tags: ai, board-game
---


title: Collisions are not working in Unity

text:
# Question
Title: Collisions are not working in Unity
For some reason my collisions are not working. This is what the code I have.

```
void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == "wall")
Debug.Log ("It worked");

}

```

When my object I have the script attached to hits the wall, I don't get a Debug.Log, if anyone knows what I am doing wrong please let me know!

# Answer
> 1 votes
One of the followings is causing the problem :

* One of your colliders doesn't have a Rigidbody2D attached to it, as it says in the documentation, in order to get collisions works, one of the two object **must** have a rigidbody component
* You are checking "isTrigger" and expecting OnCollision response, if your collider set to trigger then you should use "OnTriggerEnter2D" instead
* Everything works but your console doesn't shot any messages, make sure the "bubble" icon is pressed in the console window, to be sure just print something in the Start() method and see if it shows up.

# Answer
> -1 votes
The problem turned out to be that my objects didn't have colliders. Anyways thanks for the help!

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


title: How do I attach UI data to logic data?

text:
# Question
Title: How do I attach UI data to logic data?
I'm attempting to write an inventory system(C++, doesn't need to be huge), that later on should be able to be drawn in a GUI.

In the file structure, I think it would be best to put both information about the item itself and references to graphics, etc. in one file.

But how does that translate into code? How should I tell the renderer, for example which sprite to draw for which item and where to do that. Should I only have the CInventory and the CItem class, containing both logic and sprite information, or should I create separate logic and GUI inventory(in this case meaning both CInventory and CItem) classes which are then linked by a common item-id for example?

Answers are always appreciated :)

# Answer
> 1 votes
At the base of your question lies inventory management. In this case, inventory is simply a container of inventory items, where inventory items can be a plethora of game objects. These game objects could be consumables, armor, quest items, or any other game specific concept. This container includes a way to add a game object to its internal list or remove it; very generic.

You also need a system to render your inventory UI. This system knows how to obtain the player inventory, iterate it and find out what game objects exist in the inventory. This system is what is responsible for taking UI events and delegating those into actions against specific game objects.

When you open your inventory, the inventory UI system iterates the game objects in the inventory, queries each object for a specific component or attribute that identifies what sprite to render and creates the appropriate UI objects so that specific gets rendered in the right UI slot. It is possible that multiple game objects in your inventory represent the same sprite perhaps.

The beauty of the above is that in a client/server situation, the inventory management system would be managed by the server while the inventory ui system is managed by the client. While both can coexist in a non-client/server game, the separation is still useful for decoupling UI from logic.

# Answer
> 0 votes
The Inventory should be a list of Items. When the user picks up the Item from the ground, it is moved into the list, and removed from a list of Dropped Items in the game. When the user moves the item to his equipment, the item is removed from the inventory and moved into a slot in the equipment class.

An Item should only exist in one context.

The Item class should have a draw method that will take care of it being drawn if it is dropped on the ground.

The Inventory class should handle the drawing of its items for each inventory slot you provide.

The draw method of the Item class is no longer called once it has become a child of the Inventory.

If you would like a clear example of this, one can be found on my GitHub : https://github.com/shroeder/GameRPG/tree/LukesBranch/Game/Game. Feel free to reference this code, I think it is tailored to your question.

---
Tags: gui, inventory
---


# Question
Title: How can I change the appearance of the mouse cursor in libGDX?
How can I change the mouse a cursor to a picture using libGDX?

# Answer
> 11 votes
### v1.7.0+

```
Pixmap pm = new Pixmap(Gdx.files.internal("cursorImage.png"));
Gdx.graphics.setCursor(Gdx.graphics.newCursor(pm, 0, 0));
pm.dispose();

```

### Before v1.7.0

```
Pixmap pm = new Pixmap(Gdx.files.internal("cursorImage.png"));
Gdx.input.setCursorImage(pm, 0, 0);
pm.dispose();

```

The hotspot parameters represent the "tip" of the cursor. For example, the operating system cursor has the hotspot at the top-left corner, but a crosshair cursor might have the hotspot at its center.

---
Tags: libgdx, mouse
---


# Question
Title: How do you make specific collisions in Unity?
So I have created a "game" where you are automatically running across platforms and you can jump and land on the top of them. I want to set it where if you collide with the the left and right side of the platform a death function executes. How can I implement a collision mechanic to achieve this?What I want the collision to be like

# Answer
> 8 votes
One approach to this issue is to examine the Collision Normal. This is a vector that describes the direction along which the other object is pushing back.

Here is a minimal example of the concept. You will likely want to tune the condition to suit your needs (at the moment a corner collision may be erratic where `x ≈ y`).

```
void OnCollisionEnter(Collision collision) {
    Vector3 collisionNormal = collision.contacts[0].normal;
    if (Mathf.Abs(collisionNormal.x) > Mathf.Abs(collisionNormal.y)) {
        //horizontal collision
    }
}

```

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


# Question
Title: OpenGL - Asteroids clone - shooting bullets from spaceship
I am having a bit of difficulty figuring out how to shoot bullets from the front of the spaceship. I can draw it to screen, but I can't properly figure out how to create bullets each time I press the space bar. The if statement for the bullet is located in the update() method near the bottom.

```
#include "Game.h"

Game::Game()
    : mUColorProgram(0)
    , mVColorProgram(0)
    , mAsteroid(NULL)
    , mSpaceship(NULL)
    , mManualRotation(glm::radians(0.0f))
    , mManualTranslation(0.0f, 0.0f, 0.0f)
    , mSpinnerAngle(0.0f)
    , mSpinnerAngularVelocity(glm::radians(90.0f))
    , mMinX(-1.0f)
    , mMinY(-1.0f)
    , mMaxX(1.0f)
    , mMaxY(1.0f)
    , mBouncerPosition(0.0f, 0.0f, 0.0f)
    , mBouncerVelocity(0.0f, 0.0f, 0.0f)
    , mMinScale(0.5f)
    , mMaxScale(5.0f)
    , mCurrScale(mMinScale)
    , mScalingSpeed(2.0f)
    , mBlendColor1(1.0f, 1.0f, 0.0f, 1.0f)
    , mBlendColor2(1.0f, 0.0f, 0.0f, 1.0f)
    , mAlpha(1.0f)
    , mBlendSpeed(-0.5f)
    , mBlendedColor(mAlpha * mBlendColor1 + (1 - mAlpha) * mBlendColor2)
{
    glsh::InitRandom();  // initialize random number generator

    mBouncerPosition.x = glsh::Random(mMinX, mMaxX);
    mBouncerPosition.y = glsh::Random(mMinY, mMaxY);

    float angle = glm::radians(glsh::Random(-180.0f, 180.0f));
    float speed = 0.75f;
    mBouncerVelocity.x = speed * std::cos(angle);
    mBouncerVelocity.y = speed * std::sin(angle);
}

Game::~Game()
{
}

void Game::initialize(int w, int h)
{
    // set clearing (background) color
    glClearColor(0.25f, 0.25f, 0.25f, 1.0f);

    // import some symbols from glsh namespace
    using glsh::VertexPositionColor;

    VertexPositionColor asteroid[] = {
        VertexPositionColor(0.0f, 0.40, 0.0f, 0.9f, 0.9f, 0.9f, 1.0f),
        VertexPositionColor(0.0f, 0.4f, 0.0f, 0.9f, 0.9f, 0.9f, 1.0f),
        VertexPositionColor(-0.3f, 0.3f, 0.0f, 0.9f, 0.9f, 0.9f, 1.0f),
        VertexPositionColor(-0.4f, 0.0f, 0.0f, 0.9f, 0.9f, 0.9f, 1.0f),
        VertexPositionColor(-0.1f, -0.3f, 0.0f, 0.9f, 0.9f, 0.9f, 1.0f),
        VertexPositionColor(0.1f, -0.4f, 0.0f, 0.9f, 0.9f, 0.9f, 1.0f),
        VertexPositionColor(0.3f, -0.2f, 0.0f, 0.9f, 0.9f, 0.9f, 1.0f),
        VertexPositionColor(0.4f, 0.2f, 0.0f, 0.9f, 0.9f, 0.9f, 1.0f),
        VertexPositionColor(0.1f, 0.5f, 0.0f, 0.9f, 0.9f, 0.9f, 1.0f),
    };

    VertexPositionColor spaceship[] = {
        VertexPositionColor(0.3f, 0.0f, 0.0f, 1.0f, 0.5f, 0.0f, 1.0f),
        VertexPositionColor(-0.2f, 0.8f, 0.0f, 1.0f, 0.5f, 0.0f, 1.0f),
        VertexPositionColor(-0.2f, -0.8f, 0.0f, 1.0f, 0.5f, 0.0f, 1.0f),

        VertexPositionColor(1.0f, 0.0f, 0.0f, 1.0f, 0.5f, 0.0f, 1.0f),
        VertexPositionColor(-0.8f, 0.4f, 0.0f, 1.0f, 0.5f, 0.0f, 1.0f),
        VertexPositionColor(-0.3f, 0.0f, 0.0f, 1.0f, 0.5f, 0.0f, 1.0f),

        VertexPositionColor(1.0f, 0.0f, 0.0f, 1.0f, 0.5f, 0.0f, 1.0f),
        VertexPositionColor(-0.8f, -0.4f, 0.0f, 1.0f, 0.5f, 0.0f, 1.0f),
        VertexPositionColor(-0.3f, 0.0f, 0.0f, 1.0f, 0.5f, 0.0f, 1.0f),

    };

    VertexPositionColor bullet[] = {
        VertexPositionColor(0.2f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f),
        VertexPositionColor(-0.1f, 0.1f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f),
        VertexPositionColor(-0.1f, -0.1f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f),
    };

    // create meshes
    mAsteroid = glsh::CreateMesh(GL_TRIANGLE_FAN, asteroid, 9);
    mSpaceship = glsh::CreateMesh(GL_TRIANGLES, spaceship, 9);
    mBullet = glsh::CreateMesh(GL_TRIANGLES, bullet, 3);

    // build shader programs
    mUColorProgram = glsh::BuildShaderProgram("ucolor-vs.glsl", "ucolor-fs.glsl");
    mVColorProgram = glsh::BuildShaderProgram("vcolor-vs.glsl", "vcolor-fs.glsl");

}

void Game::shutdown()
{
    delete mAsteroid;
    delete mSpaceship;
    delete mBullet;

    glUseProgram(0);
    glDeleteProgram(mUColorProgram);
    glDeleteProgram(mVColorProgram);
}

void Game::resize(int w, int h)
{
    glViewport(0, 0, w, h);
}

void Game::draw()
{
    glClear(GL_COLOR_BUFFER_BIT);

    // activate the per-vertex color shader program
    glUseProgram(mVColorProgram);

    T = glsh::CreateTranslation(mBouncerPosition);
    R = glsh::CreateRotationZ(mSpinnerAngle);
    S = glsh::CreateScale(0.1f, 0.1f, 0.1f);
    glsh::SetShaderUniform("u_Transform", T * R * S);
    mAsteroid->draw();

    T = glsh::CreateTranslation(mBulletTranslation);
    R = glsh::CreateRotationZ(glm::radians(0.0f));
    S = glsh::CreateScale(0.1f, 0.1f, 0.1f);
    glsh::SetShaderUniform("u_Transform", T * R * S);
    mBullet->draw();

    T = glsh::CreateTranslation(mManualTranslation);
    R = glsh::CreateRotationZ(mManualRotation);
    S = glsh::CreateScale(0.1f, 0.1f, 0.1f);
    glsh::SetShaderUniform("u_Transform", T * R * S);
    mSpaceship->draw();
}

bool Game::update(float dt)
{
    const glsh::Keyboard* kb = getKeyboard();

    if (kb->keyPressed(glsh::KC_ESCAPE)) {
        return false; // exit
    }

    // Rotation of spaceship
    if (kb->isKeyDown(glsh::KC_LEFT)) {
        mManualRotation += 3.0f * dt;
    }
    else if (kb->isKeyDown(glsh::KC_RIGHT)) {
        mManualRotation -= 3.0f * dt;
    }

    // Translation of spaceship
    if (kb->isKeyDown(glsh::KC_UP)) {
        mManualTranslation.x += std::cos(mManualRotation) * 0.5f * dt;
        mManualTranslation.y += std::sin(mManualRotation) * 0.5f * dt;
    }
    else if (kb->isKeyDown(glsh::KC_DOWN)) {
        mManualTranslation.x -= std::cos(mManualRotation) * 0.5f * dt;
        mManualTranslation.y -= std::sin(mManualRotation) * 0.5f * dt;
    }

    // Shoot bullet
    if (kb->keyPressed(glsh::KC_SPACE)) {
        // shoot bullet, modify mBulletTranslation

    }

    // update spinner angle
    mSpinnerAngle += dt * mSpinnerAngularVelocity;

    // keep the angle in standard range
    if (mSpinnerAngle > 180.0f) {
        mSpinnerAngle -= 360.0f;
    } else if (mSpinnerAngle < -180.0f) {
        mSpinnerAngle += 360.0f;
    }

    // update bouncer position
    mBouncerPosition += dt * mBouncerVelocity;

    // bounce off of the horizontal boundaries of the screen
    if ((mBouncerVelocity.x > 0 && mBouncerPosition.x > mMaxX) ||
        (mBouncerVelocity.x < 0 && mBouncerPosition.x < mMinX))
    {
        mBouncerVelocity.x *= -1;
    }

    // bounce off of the vertical boundaries of the screen
    if ((mBouncerVelocity.y > 0 && mBouncerPosition.y > mMaxY) ||
        (mBouncerVelocity.y < 0 && mBouncerPosition.y < mMinY))
    {
        mBouncerVelocity.y *= -1;
    }

    return true;
}

```

# Answer
> 0 votes
You already got your position and your rotation, just take those values from the spaceship and create a bullet from them. If you dont want them to start in the middle of your spaceship, move them a few times in velocitys direction.

---
Tags: opengl, c++
---