# Question
Title: How to end the game after the player has defeated all the enemies in Game Maker?
I'm making a simple version of the game asteroids as I'm learning how to develop with Game Maker Studio. Currently, mostly everything works properly except that when the player destroys all of the asteroids, I need the game to exit.

I've tried add the following line of script to the step event for the asteroid, but it resulted in a runtime error:

```
if (!instance_exists(obj))
  game_end();

```

This is a pretty simple problem but I haven't been able to find the answer on Google. What code should I add to check for any instances of asteroids and then to end the game when there are none?

# Answer
> 0 votes
One idea is to keep an array that tracks all of your asteroids. Every time you create an asteroid, add it to the array, and every time an asteroid is destroyed, remove it from the array. You can then use this function to check how many asteroids currently exist. If the answer is 0, end the game.

Someone who knows the GML API better might have a better solution, but this should certainly work. This method has the added benefit that you can check the number of asteroids in existence at any time; you could have a counter on the corner of your screen that tells the user how they're doing.

# Answer
> 2 votes
You could simply do:

```
if instance_number(obj) == 0 {
    game_end()
}

```

This code should be put in a step event.

`instance_number(obj)` gets the amount of the defined objects in the room.

---
Tags: game-maker
---


# Question
Title: How to randomly spawn objects off-screen close to the player?
I am making a zombie game. I want to have it so zombies randomly spawn. My code for this is:

```
instance_create(
  obj_player.x + irandom_range(-300, 300),
  obj_player.y + irandom_range(-300, 300),
  obj_zom_1 )

```

The problem with this is that zombies will sometimes spawn really close to the player. I want to have it so zombies spawn randomly but to NOT spawn on the visible screen, because seeing zombies materialize out of nowhere looks silly.

How would I do that?

# Answer
> 3 votes
I don't know the expected limits of your coordinates so I made them constant-like (i.e. screenLeftX). My snippet chooses a random edge of the screen and then a random value between the appropriate coordinate limits of that edge.

```
var positionAlongEdge = 0;
var which = irandom_range(1,4);
if (which == 1) //top edge
{
  positionAlongEdge = irandom_range(screenLeftX, screenRightX);
  instance_create(positionAlongEdge, screenTopY, obj_zom_1);
  //If the shape of zombies causes them to appear on-screen (at the edge),
  //you can push them further beyond the edge:
  //instance_create(positionAlongEdge, screenTopY - 10, obj_zom_1);
  //or
  //instance_create(positionAlongEdge, screenTopY - zombieHeight, obj_zom_1);
}
else if (which == 2) //bottom edge
{
  positionAlongEdge = irandom_range(screenLeftX, screenRightX);
  instance_create(positionAlongEdge, screenBottomY, obj_zom_1);
}
else if (which == 3) //left edge
{
  positionAlongEdge = irandom_range(screenTopY, screenBottomY);
  instance_create(screenLeftX, positionAlongEdge, obj_zom_1);
}
else if (which == 4) //right edge
{
  positionAlongEdge = irandom_range(screenTopY, screenBottomY);
  instance_create(screenRightX, positionAlongEdge, obj_zom_1);
}

```

# Answer
> 0 votes
I would have done more simply:

```
with obj_player //or in the right place in "step"
{
  var xx=random_range(0,room_width);
  var yy=random_range(0,room_height);
  while point_distance(xx,yy,x,y)<300
  {
    var xx=random_range(0,room_width);
    var yy=random_range(0,room_height);
  }
  instance_create(xx, yy, obj_zom_1);
}

```

---
Tags: random, game-maker
---


title: How to fix this unexpected movement?

text:
# Question
Title: How to fix this unexpected movement?
I am facing a problem below is the detail.

1. There are two scripts(actually more than two but these have the problem) Cannon.cs and Launch.cs and three buttons(up, down, and launch) to move cannon and launch the bullet.
2. Cannon have bullets and each bullet has Launch.cs attached also a RigidBody2D.
3. When specific event occurs the Cannon.cs calls the Launch.cs's `Launch(direction)`; method.
4. Parameter "direction" = Cannon.transform.right.
5. Bullets are being instantiated dynamically and are stored in the list Cannon.cs take one bullet and fires it(firing includes calling the `Launch(direction)`);.
6. `Launch(direction)`; will always be called once no matter what also to double sure myself I destroy the launch script on launch.

The problem is once the bullet is fired or launched in the direction specified by the direction of cannon(since `direction = cannon.right`) and I click on the up or down button the launched bullet changes its direction which should never happen because Launch() method is called only once in the lifetime of the bullet and also I detach the Launch.cs script on launch.

I am using `rigidbody2D.velocity = direction * thrust;` what I think is that rigidbody2D.velocity once called will possess the direction just like a method called by reference. I am totally lost I hope I made my question clear please do help me if you can.

# Answer
Are the bullets child-objects of the cannon? If yes they keep their relative position and direction when you change that of the parent-object. Set `transform.parent = null` on the bullets to turn them into independent game objects.
> 1 votes

---
Tags: unity
---


title: Detect the position of the mouse press?

text:
# Question
Title: Detect the position of the mouse press?
I am encountering an extremely absurd phenomenon. When I run this code on my smartphone **via Unity Remote** or even on the computer, it works as expected. But when I install the APK on the device and run it, the touch distance changes! Does this have something to do with resolution and Vector3.Distance?

```
    distance = Vector3.Distance (Input.mousePosition, button.position);

    Debug.Log (distance);

    if (Input.GetMouseButton (0) && distance > 55) {

        // do something
}

```

# Answer
Actually,

> Input.GetMouseButtonDown returns true during the frame the user pressed the given mouse button.

If you want to get mouse position on click then you can use `Input.mousePosition` in `Input.GetMouseButtonDown` is true, it will return mouse position in pixel coordinates.

```
Update()
{
    if (Input.GetMouseButtonDown(0))
        Debug.Log("Mouse position: " + Input.mousePosition);
}

```

**Edit:** It also works like a charm on touch devices. For single touch on touch devices you can use it without any doubt.

**Edit2:** As I mentioned that `Input.mousePosition` will give you pixel coordinates not world coordinates. Basically you are comparing Pixel point and World point, that'd obviously not gonna do what you want. But you can simply convert screen point to world point through `ScreenToWorldPoint`. Like,

```
Vector3 mouseWorldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

distance = Vector3.Distance (mouseWorldPosition , button.position);
...

```
> 0 votes

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


# Question
Title: LibGDX - Getting Tile Map Layers Problem
While following a tutorial with LibGDX, I am working with tile maps.

This is the method that I'm using:

```
tilemap.getLayers().get("Collision Layer");

```

or

```
tilemap.getLayers().get(1); //1 is the second layer, the collision layer

```

The problem is, is that when I try to get a certain layer from the tile map, it return a null pointer error like so:

> Exception in thread "LWJGL Application" java.lang.NullPointerException at com.mytut.game.Player.Init(Player.java:25) at com.mytut.game.MyTutGame.create(MyTutGame.java:70) at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:147) at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:124)

I have tried various ways of getting the layer but none of them seem to work.

Here's an image of my tile map in the Tiled map editor:

# Answer
After looking through my code over and over again, I found what I did wrong:

The problem was that I hadn't initialized my tile map before I was trying to get the layers of the tile map, so it gave me the exception.

All I needed to do was move the tile map initialization before I found the layers.
> 0 votes

---
Tags: libgdx, tilemap, layers
---


# Question
Title: How to give a value to all elements of an array?
This problem is encountered in Game-maker studio:

I created an array using the following iteration:

```
V_X=0 //these are coordinates of my "pointer"
V_Y=0

repeat(100)
{
    A_CA[V_X,V_Y]=choose(-1,0,1) //now I declare the value of the pointed element in the array

    if V_X<10 //here I move the "pointer"
    {
        V_X+=1
    }
    if V_X=10
    {
        V_Y+=1
        V_X=0
    }
}

```

My goal is, at some point in the game, I would like to give the same value (0) to every element of the array, preferably without using the "repeat" command above, because I think that may hamper performance.

# Answer
> 1 votes
Firstly, you need use `for`, not `repeat`. In this case `for` will works more fast.

If array not initialized (not created), you need fill it from end to begin. Otherwise it will reallocate memory on each record, so it will work very slow (for any JS-targets, like HTML5/Tizen/etc, it's not true - there you need use normal order).

```
for (var i=9; i>=0; i--)
{
    for (var j=9; j>=0; j--)
    {
        array[j, i] = value;
    }
}

```

If array already initialized, then order is not important.

No ways to fill array by value except iterate each element in loop. But 100 elements - it's not much. No reason for worry about it.

Other way - you can use grids and function `ds_grid_clear` for fill it.

---
Tags: data-structure, game-maker
---


title: Libgdx, TiledMap, and tearing

text:
# Question
Title: Libgdx, TiledMap, and tearing
My TiledMap tears when the window is specific sizes, resized, or the camera moves.

The tileset is padded by 2px and have tried as high as 10px. Each tile is 70x70.

Here are the pack.json settings,

```
{
    paddingX: 2,
    paddingY: 2,
    bleed: true,
    edgePadding: true,
    duplicatePadding: true,
    maxWidth: 4096,
    maxHeight: 4096,
    filterMin: Nearest,
    filterMag: Nearest,
    ignoreBlankImages: true,
    wrapX: ClampToEdge,
    wrapY: ClampToEdge,
    grid: true,
    fast: false
}

```

Here is the code.

```
Parameters params = new Parameters();
params.textureMinFilter = TextureFilter.Nearest;
params.textureMagFilter = TextureFilter.Nearest;
TileMap map = new TmxMapLoader().load(file.getAbsolutePath(),params);

```

So what am I doing wrong? If nothing, does that mean libgdx absolutely cannot handle TileMaps of any sort?

# Answer
> 1 votes
70 is not a power of 2.

Adding,

```
pot: false,

```

to pack.json for TexturePacker resolved this.

---
Tags: opengl, libgdx, textures, rendering, tilemap
---


title: building timers in strategy games

text:
# Question
Title: building timers in strategy games
I've got a web-based strategy game in which you build a city. Coding is smooth, but I'm kind of hung up on how long it takes my buildings to build. I want to keep the user playing, but have them long enough to keep them having to come back to the game. I've currently got it where each building has a base build rate that is exponentially increased by the building's level. I can adjust the times by changing the base build rate, but I was wondering if there is a better, or perhaps more widely-accepted way of doing this. I worry that a 113 day build on a level 10 building before reaching the next city level where the user has to start over will discourage further playing.

# Answer
The question is "why do you have timers at all? What's the gameplay purpose?" When your answer is that you want to force the player to revisit the game later ("long enough to keep them having to come back to the game"), you need to consider how often you want them to revisit. Ideally you want to convince your player to make a habit out of playing your game and incorporate it into their daily life. To enforce this usage pattern, design your timers in a way that there is something to do in the intervals you want the player to interact with the game.

* When you are targeting school kids, make the timers exactly 45 minutes long, so the players can visit the game in the breaks between lessons. (Your game *does* work well on lower-range smartphones, does it?)
* When you are targeting adults and want the player to check in on the commute to work, in the lunch break, on the commute back from work and just before going to bed, then a 4-hour rhythm will work.
* When you want the user to incorporate one daily game session into their real-life schedule, then slightly below 24 hour timers are the longest you should go with *most* of your timers.
* Timers which are several days long *can* work to give the player some long-term anticipation, but only when you combine them with lots of shorter timers to ensure there is always something to do at every regular player visit. I would argue that one could even make one single 113 day timer work. It could serve as a tool to motivate players to become long-term community veterans. But only if you have enough shorter timers to keep them busy during this long period.

Also, make sure that your timers *coincide*. When there are multiple sources of timed events in your game, try to make sure that they all enforce the same rhythm. When you have like 8 pending timer events which are 30 minutes apart, the player won't know when to visit. It would be far better when they would all finish at roughly the same time, so the player can schedule a session shortly afterwards. That means that depending on the current progression of the player all timers should have roughly the same length or multiples thereof.
> 2 votes

---
Tags: mmo, browser-based-games, strategy
---


# Question
Title: Animation timeline organization for Unity 5
I create stuff for AssetStore and use 3ds max and Unity 5.

Can someone tell me how I need to work with timeline?

When I create animation for several objects, I need to animate them one by one? (Example: from Frame 0 to Frame 60 object 01 rotates 360 degrees, then from Frame 60 to Frame 120 object 02 rotates 360 degrees) OR I need to animate every one object in same time. (Every one rotates from Frame 0 to Frame 60).

I know that I need to assign animation controllers in Unity, and if I create all animations in same time, I need only one controller for many objects.

If there, any benefits to animate objects one by one and have multiple controllers later in game development?

# Answer
You can add an animation controller in the root object of all your objects so they share it. And then, in every animation clip you want, you can animate every object you want in different times (keyframes).

A single animation controller should be cohesive (https://en.wikipedia.org/wiki/Cohesion\_(computer\_science)); that means, it should focus on the animations that its name tell about. If it is called "CharacterAnimationController", then it should animate characters but never doors. Otherwise you will have difficulties finding it and maintaining it.

You can also use different animation layers if you want semi-independent animation controller states. But try to follow the KISS principle and avoid overengineering everything.
> 2 votes

---
Tags: animation, unity
---


# Question
Title: How do I create a save file for a C++ game?
I am coding my final for a Video game Programming course, and I want to know how to create a save file for my game, so that a user can play, and then come back later. Any idea how this is done, every thing I have done before has been single run programs.

# Answer
> 41 votes
You need use serialization to save your variables in memory to your hard drive. There are many types of serialization, in .NET XML is a common format, though there are binary and JSON serializers available. There is an entry in the C++ FAQ on general serialization techniques:

There are libraries that can aid in implementing serialization. Some are mentioned in other answers. Also refer to this StackOveflow Question for more information.

The variables needing to be serialized are probably going to be related to game state. For example, you will probably want to know this type of information

1. The player was playing level 3
2. The player was at X, Y world coordinates
3. The player has three items in his backpack
4. Weapon
5. Armor
6. Food

You wont really care what textures are being used (unless your player can change their appearance, that's a special case), because they are usually the same. You need to focus on saving important gamestate data.

When you start your game, you start as normal for a "new" game (this loads your textures, models, etc) but at appropriate time you load the values from your save file back into the game state object replacing the "default" new game state. Then you allow the player to resume playing.

I've greatly simplified it here, but you should get the general idea. If you have a more specific question ask a new question here and we can try to help you with it.

# Answer
> 19 votes
Typically this is specific to your game. I'm sure you've learned about writing to and reading from files in your classes so far. The basic idea is:

1. When exiting the game, write the values you want to save to a file.
2. When loading the game, check to see if a save file exists, if it does, load the read the values in to your program. If the file does not exist, continue like you do now and set the values to their starting/default values.

What you write is up to you, it depends on your game. One way of writing is to write out the variables you want in a specific order as a byte stream. Then when loading, read them in to your program in the same order.

For example (in quick pseudo code):

```
SaveGame(FileInput file) {
    file.writeInt(playerLevel);
    file.writeInt(playerHealth);
    file.writeInt(gameProgress);
}

LoadGame(FileInput file) {
    if(file.exists()) {
        playerLevel= file.readInt();
        playerHealth = file.readInt();
        gameProgress = file.readInt();
    } else {
        playerLevel = 1;
        playerHealth = 100;
        gameProgress = 0;
    }
}

```

# Answer
> 6 votes
There are probably a large number of ways to do this, but the simplest that I always found and have used both personally and professionally is to make a structure that contains all of the values I want saved.

```
struct SaveGameData
{
    int              characterLevel; // Any straight up values from the player
    int              inventoryCount; // Number of items the player has on them or stored or what not
    int[STAT_COUNT]  statistics;     // This is usually a constant size (I am tracking X number of stats)
    // etc
}

struct Item
{
    int itemTypeId;
    int Durability; // also used as a 'uses' count for potions and the like
    int strength;   // damage of a weapon, protection of armor, effectiveness of a potion
    // etc
}

```

I then just fwrite/fread the data to and from a file using the basic File IO values. The inventoryCount is the number of Item structures that are saved after the main SaveGameData structure in the file so I know how many of those to read after fetching that data. The key here is that when I want to save something new, unless its a list of items or the like, all I have ever have to do is add a value to the structure some where. If its a list of items then I will have to add a read pass like I have already implied for the Item objects, a counter in the main header and then the entries.

This does have the downside of making different versions of a save file incompatible with each other with out special handling (even if it is just default values for each entry in the main structure). But overall this makes the system easy to extend just by adding in a new data value and putting a value into it when needed.

Again, quite a few ways to do this and this might lead more towards C than C++, but it has gotten the job done!

# Answer
> 4 votes
First you need to decide what data needs to be saved. For instance, this could be the location of the character, his score, and the number of coins. Of course, your game will likely be much more complex, and so you will need to save additional data such as the level number and enemy list.

Next, write code to save this to a file (use ofstream). A relatively simple format you can use is as follows:

```
x y score coins

```

And so the file would look like:

```
14 96 4200 100

```

Which would mean he was at position (14, 96) with a score of 4200 and 100 coins.

You also need to write code to load this file (use ifstream).

---

Saving enemies can be done by including their position in the file. We can use this format:

```
number_of_enemies x1 y1 x2 y2 ...

```

First the `number_of_enemies` is read and then each position is read with a simple loop.

# Answer
> 1 votes
One addition/suggestion would to add a level of encryption to your serialization so users cannot text edit their values to "9999999999999999999". One good reason to do this would be to prevent integer overflows (for example).

# Answer
> 0 votes
I think your best bet is boost::serialization because is easy to propagate down in your hierarchy. You only need to call the top object's save/load function and all your classes are easily created.

See: http://www.boost.org/doc/libs/1\_49\_0/libs/serialization/doc/index.html

# Answer
> 0 votes
For completeness sake I want to mention a c++ serialization library, that I personally use and was not mentioned yet: cereal.
It's easy to use and has a nice, clean syntax for serializing. It also offers multiple types of formats you can save to (XML, Json, Binary (including a portable version with respects endianess)). It supports inheritance and is header-only,

# Answer
> 0 votes
Your game will compromise data structures (hopefully?) that you need to transform into bytes (serialize) so you can store them. In a future, you may load those bytes back and transform them back into your original structure (deserialization). In C++ it is not so tricky since reflection is very limited. But still, some libraries can help you here. I wrote an article about it: https://rubentorresbonet.wordpress.com/2014/08/25/an-overview-of-data-serialization-techniques-in-c/ Basically, I would suggest you to have a look at cereal library if you may target C++ 11 compilers. No need to create intermediate files like with protobuf, so you will save some time there if you want quick results. You may also choose between binary and JSON, so it can quite help debugging here.

On top of that, if security is a concern, you may want to encrypt/decrypt the data you are storing, especially if you are using human-readable formats like JSON. Algorithms like AES are helpful here.

# Answer
> -4 votes
You need to use `fstream` for input / output files. The syntax is simple EX:

```
#include <fstream>
// ...
std::ofstream flux ; // to open a file in ouput mode
flux.open("myfile.whatever") ;

```

Or

```
#include <fstream>
// ...
std::ifstream flux ; // open a file in input mode
flux.open("myfile.whatever") ;

```

Other actions are possible on your file: *append*, *binary*, *trunc*, etc. You would use the same syntax as above instead we put std::ios::(flags), for instance:

* `ios::out` for output operation
* `ios::in` for input operation
* `ios::binary` for binary (raw byte) IO operation, instead of character-based
* `ios::app` for to start to write at the end of the file
* `ios::trunc` for if the file already exist replace delete the old content and replace by new
* `ios::ate` \- position the file pointer "at the end" for input/output

Ex:

```
#include <fstream>
// ...
std::ifstream flux ;
flux.open("myfile.whatever" , ios::binary) ;

```

Here is a more complete but simple example.

```
#include <iostream>
#include <fstream>

using namespace std ;

int input ;
int New_Apple ;
int Apple_Instock ;
int Eat_Apple ;
int Apple ;

int  main()
{
  bool shouldQuit = false;
  New_Apple = 0 ;
  Apple_Instock = 0 ;
  Eat_Apple = 0 ;

  while( !shouldQuit )
  {
    cout << "------------------------------------- /n";
    cout << "1) add some apple " << endl ;
    cout << "2) check apple in stock " << endl ;
    cout << "3) eat some apple " << endl ;
    cout << "4) quit " << endl ;
    cout << "------------------------------------- /n";
    cin >> input ;

    switch (input)
    {
      case 1 :
      {
        system("cls") ;

        cout << "------------------------------------ /n";
        cout << " how much apple do you want to add /n";
        cout << "------------------------------------ /n";
        cin >> New_Apple ;

        ifstream apple_checker ;
        apple_checker.open("apple.apl") ;
        apple_checker >> Apple_Instock ;
        apple_checker.close() ;

        Apple = New_Apple + Apple_Instock ;

        ofstream apple_adder ;
        apple_adder.open("apple.apl") ;
        apple_adder << Apple ;
        apple_adder.close() ;

        cout << "------------------------------------ /n";
        cout << New_Apple << " Apple has been added ! /n";
        cout << "------------------------------------ /n";
        break;
      }

      case 2 :
      {
        system("cls") ;

        ifstream apple_checker ;
        apple_checker.open("apple.apl") ;
        apple_checker >> Apple_Instock ;
        apple_checker.close() ;

        cout << "------------------------------------ /n";
        cout << " there is " << Apple_Instock ;
        cout << "apple in stock /n" ;
        cout << "------------------------------------ /n";
        break;
      }

      case 3 :
      {
        system("cls") ;

        cout << "------------------------------------ /n";
        cout << "How many apple do you want to eat /n" ;
        cout << "------------------------------------ /n";
        cin >> Eat_Apple ;

        ifstream apple_checker ;
        apple_checker.open("apple.apl") ;
        apple_checker >> Apple_Instock ;
        apple_checker.close() ;

        Apple = Apple_Instock - Eat_Apple ;

        ofstream apple_eater ;
        apple_eater.open("apple.apl") ;
        apple_eater << Apple ;
        apple_eater.close() ;

        cout << "----------------------------------- /n";
        cout << Eat_Apple ;
        cout << " Apple has been eated! /n";
        cout << "----------------------------------- /n";
        cout << Apple << " Apple left in stock /n";
        cout << "----------------------------------- /n";
        break;
      }

      case 4 :
      {
        shouldQuit = true;
        break;
      }

      default :
      {
        system("cls") ;

        cout << "------------------------------------ /n";
        cout << " invalide choice ! /n";
        cout << "------------------------------------ /n";
        break;
      }
    }
  }
  return 0;
}

```

---
Tags: c++, savegame, serialization
---


# Question
Title: Any reason not to combine an AO Map and Cavity Map into one texture?
If an Ambient Occlusion Map is for mapping shadows based on closeness of neighboring geometry, and a Cavity Map is for mapping smaller shadows based on angle or distance, then is there any reason not to mix these into one unified shadow map? It seems desirable to do so for saving a game from having to load extra textures, but I ask in case I'm overlooking something.

This article gives an overview of the differences between the two types of maps, but it never mentions combining them. This made me wonder if there was some reason to keep them as separate images.

Thanks in advance for any insight.

# Answer
I cannot speak to any hidden technical limitations that prevent you from sharing the texture (if that was your intended question). That being said, I doubt anyone here is going to recommend that you make your code/algorithm more complex than it has to be without a specific and measurable reason.

Here are two *good* reasons to combine them:

1. Reduce memory usage
    * A 2048x2048x32 texture is about 16MB, less than 1% of a 2GB video card's memory.
    * If you are not memory-capped, don't combine them for this reason.
2. Reduce the overhead required to use them (binding and such)
    * If you are not framerate-capped (under RELEASE and not DEBUG), don't combine them for this reason.

Even though you technically cut resource usage in half, either way, the benefit of doing so for a single pair of textures is probably negligible (60FPS vs. 59FPS). If your question was about a potentially large array of separated textures, I'd recommend combining them, instead, because half of "a lot" equates to a significant improvement to performance (60FPS vs. 1FPS).
> 0 votes

---
Tags: textures, optimization, ambient-occlusion
---


# Question
Title: How to use a KeyListener and an input handler together?
The following class implements a `KeyListener`, and `handleInput()` method gets called in an endless loop.

```
public final class PlayerInput implements KeyboardInputHandler{

  public static final int INVERTED_AXIS = 0;
  public static final int NORMAL_AXIS = 1;

  private Sprite sprite;

  private int axisMode_x=NORMAL_AXIS;
  private int axisMode_y=NORMAL_AXIS;

  private boolean left;
  private boolean right;
  private boolean down;
  private boolean jumping;
  private boolean doubleJump;

  private int jumpCounter=0;
  private boolean stopLeft;
  private boolean stopRight;
  private boolean stopJumping;
  private boolean stopDoubleJump;

  public PlayerInput(Sprite sprite){

    this.sprite=sprite;
  }

  public void setAxisMode_x(int axisMode_x) {

    this.axisMode_x = axisMode_x;
  }

  public void setAxisMode_y(int axisMode_y) {

    this.axisMode_y = axisMode_y;
  }

  public void handleInput(){

    if (left){

      if (axisMode_x==INVERTED_AXIS) sprite.setPos_x(sprite.getPos_x()+sprite.getSpeed_x());
      else sprite.setPos_x(sprite.getPos_x()-sprite.getSpeed_x());
    }
    else if (right){

      if (axisMode_x==INVERTED_AXIS) sprite.setPos_x(sprite.getPos_x()-sprite.getSpeed_x());
      else sprite.setPos_x(sprite.getPos_x()+sprite.getSpeed_x());
    }
    else{

      sprite.goingLeft(false);
      sprite.goingRight(false);
    }

    if (jumping && sprite.collidedDown){

      sprite.addAction(new JumpingAction());
    }
    else sprite.goingUp(false);
  }

  public void keyTyped(KeyEvent e) {}

  public void keyPressed(KeyEvent e) {

    switch (e.getKeyCode()){

    case KeyEvent.VK_LEFT:

      right=false;
      left=true;
      e.consume();
    break;

    case KeyEvent.VK_RIGHT:

      left=false;
      right=true;
      e.consume();
    break;

    case KeyEvent.VK_SPACE:
      jumping=true;
      e.consume();
    break;
    }
  }

  public void keyReleased(KeyEvent e) {

    switch (e.getKeyCode()){

    case KeyEvent.VK_LEFT:

      left=false;
      e.consume();
    break;

    case KeyEvent.VK_RIGHT:

      right=false;
      e.consume();
    break;

    case KeyEvent.VK_SPACE:
      jumping=false;
    break;
    }
  }
}

```

If I want the player to jump, I need to press `Space` and then release it... But what if my "jumping" variable checking comes right after my `keyReleased` method?

Is there a way to synchronize these two pieces of code?

Thank you for your answer.

# Answer
With this current piece of code, only way I can think about is checking `Press`, then `jumping` and finally `Release`, but this is so weird and makes code so coupled that I think it's not even bad as a solution, it's even worse.

First of all, It's nearly unlikely for a human to press and release a key in 1 frame (talking about a normal fps rate), so it shouldn't be a problem, although it's true it's still a possibility. That said, I would make a **list of events** in each frame, and then I'd check that list from the function **handleInput** or, even more flexible code, (if your architecture allows you to) make a function like:

```
void ManageEvents() {
    foreach (Event ev in eventsList) {
        entity.HandleEvent(ev);
    }
}

```

This way, you would get both **`Press`** and **`Release`** in the same frame, so each element (I mean, the character and the logic which sets `jumping`) would get them for their logic, although you of course loose performance.

I don't know if it's clear enough, if it isn't please add a comment and I'll expand it.

---

EDIT: To help figuring out how to code this list, I'll give a brief example. Please note that I'm currently C++ developer and I haven't used Java for too much time now.

Let's imagine (I can't get your architecture from this piece of code, but I think this example will be self explanatory) you have something similar to the following, ignoring how you fill the list.

---

**InputManager.h**

```
class CInputManager {
    public:
        ...
        void ManageEvents();
    private:
        std::vector<Event *> m_events;
        std::vector<IObserver *> m_observers;
        ...
}

```

---

**InputManager.cpp**

```
void CInputManager::ManageEvents() {
    for (std::vector<Event *>::iterator itrEv = m_events.begin();
            itrEv != m_events.end(); ++itrEv) {
        //we iterate over the list of events
        for (std::vector<IObserver *>::iterator itrOb = m_observers.begin();
                itrOb != m_observers.end(); ++itrOb) {
            (*itrOb)->ManageEvent((*itrEv)); //we send each event to every observer
        }
    }

```

This way, what we do is:

1. Fill events list for each frame.
2. Iterate over the whole list of events.
3. Send every event to all observers.
4. Each observer decides if this event matters or not for itself.

NOTE: Remember you should clean events list after sending events to all observers (each frame).

Here, observers would be any class implementing the interface `IObserver`, entities, controls, buttons... whatever you want.

Note that there are too many optimizations and application-dependent things to have in mind.

I leave here links to a project I'm currently developing, consisting on an InputManager with functionality similar to what you're currently trying. Important files are InputManager.cpp and InputManager.h. Actually, the code I posted is a simplified version of it, so you could take a look at it if you want a complete version.

Hope your problem is solved now.
> 1 votes

---
Tags: java, input
---


# Question
Title: What is the easiest way to move towards and along the edge on a hex grid?
I have a hexagonal grid with variable radius. My entity can move exactly two hexes per turn.

How should I calculate next step towards border and afterwards travelling clockwise around map?

**Preferred movement at the boundary**

Character should stay at the border while moving counter-clockwise every turn.

**Example movement at the middle**

Character should move 1 or 2 hexes towards edge every turn.

I can't figure out simple math to do this.

*Edit:*

This is how I did movement at the boundary:

```
  var x = pos.x;
  var y = pos.y;
  var z = -pos.x-pos.y;
  var dx =  0;
  var dy =  0;

  if      (x == -radius && z >   1) {          dy =  2; }
  else if (x == -radius && z ==  1) { dx =  1; dy =  1; }
  else if (y ==  radius && x <  -1) { dx =  2           }
  else if (y ==  radius && x == -1) { dx =  2; dy = -1; }
  else if (z == -radius && y >   1) { dx =  2; dy = -2; }
  else if (z == -radius && y ==  1) { dx =  1; dy = -2; }
  else if (x ==  radius && z <  -1) {          dy = -2; }
  else if (x ==  radius && z == -1) { dx = -1; dy = -1; }
  else if (y == -radius && x >   1) { dx = -2;          }
  else if (y == -radius && x ==  1) { dx = -2; dy =  1; }
  else if (z ==  radius && y <  -1) { dx = -2; dy =  2; }
  else if (z ==  radius && y == -1) { dx = -1; dy =  2; }

```

Any ideas how should I clean this up?

Shortest path to boundary is probably easiest to calculate from x, y and z.

# Answer
I think it'll be easier to solve this if you move one step at a time instead of one-or-two. For each location on the map there's a single direction to move in. Let's calculate that direction.

First observation: if you're using the 3-valued “cube” coordinates, the *largest coordinate* tells you which of the six “wedges” you're in. Here's a diagram showing the colors:

Code like this should do it:

```
var axes = [cube.x, -cube.z, cube.y,
           -cube.x, cube.z, -cube.y];
var direction = 0;
for (var i = 0; i < 6; i++) {
    if (axes[i] >= axes[direction]) {
        direction = i;
    }
}
if (direction == 5 && axes[0] == axes[5]) {
    direction = 0; // special case :(
}

```

Second observation: once you know which wedge you're in, you can decide how to move relative to that wedge direction:

1. If you're *not* at the edge of the map, you want to move towards the edge, and the wedge tells you which way to go. To be fancier, you can alternate left and right steps.
2. If you *are* at the edge of the map, you can take the direction you were moving towards the edge and rotate it left. This will then take you along the edge.

You can use code like this:

```
var length = Cube_length(cube);
var isBorder = (length == N);
var next = Cube_neighbor(cube, (direction + (isBorder? 2 : length % 2))%6);

```

Following these two rules you'll get something like this:

I've also written this up here.
> 4 votes

# Answer
I would do it in two 1-cell steps instead of a single 2-cell step, it’s a lot easier to implement.

Using your coding style, here would be my first try:

```
var dx = 0, dy = 0;

for (var i = 0, x = pos.x, y = pos.y; i < 2; ++i, x += dx, y += dy)
{
    var z = x + y;

    // If point is on the edge, move along the edge
    if (x != 0
          && y == -radius) { --dx; }
    else if (x ==  radius) {       --dy; }
    else if (z ==  radius) { ++dx; --dy; }
    else if (y ==  radius) { ++dx; }
    else if (x == -radius) {       ++dy; }
    else if (z == -radius) { --dx; ++dy; }
    // Otherwise move towards the edge
    else if (x > 0 && z <= 0) {       --dy; }
    else if (z > 0 && y <= 0) { ++dx; --dy; }
    else if (y > 0 && x >= 0) { ++dx; }
    else if (x < 0 && z >= 0) {       ++dy; }
    else if (z < 0 && y >= 0) { --dx; ++dy; }
    else if (y < 0 && x <= 0) { --dx; }
    // Exactly at the centre — just choose a random direction
    else { ++dx; }
}

```
> 1 votes

# Answer
not a mathematician here but you could divide this problem in 4 distinct sections, like the quarters of a circle. Then, by checking which direction is closer to the edge, move along that path. ex: (2,-1) the (+,-) sing informs us that it\`s located in the top right quadrant. then, we know that the edgemost closest hex is 3,-1 but you can deduce by using the max x value at y=0 or the max y value at x=0 and then substract your current position to see where the closest edge lies. then, we can see that there's some very easy rules to follow the edge counter clockwise if taken into quarter cases.

for example: Case 1(top right) if you're on the edge (x cannot go higher) move up along the y axis. if y cannot get higher, lower x until you reach (0, max y) which would be the top most coordinate and from there, move into quadrant 4 (-,-).

just my 2 cents, as i said, not a mathematician.
> 0 votes

---
Tags: movement, hexagonal-grid
---


title: Loading font in Monogame

text:
# Question
Title: Loading font in Monogame
This question is probably a duplicate but I'm still asking it since it's all yesterday that I'm trying to get this done without any success. I followed many solutions and tried even more libraries which were either outdated or they simply didn't work. Right now the most reasonable method I found is

* Open the Content Pipeline;
* Create a new Content if there isn't any;
* Right click on Content -\> Add -\> New item -\> SpriteFont Description -\> Give it a name;
* Click Build;
* Go to the output directory, grab the XNB file that was created and put it in some folder of the project, under Content;
* Change the properties to Content and Copy if newer;

And I use it like this:

```
private SpriteFont font;

font = Content.Load<SpriteFont>("NameOfXNBFile");

spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, Global.Camera.TranslationMatrix);

spriteBatch.DrawString(font, "Some Text", new Vector2(100, 100), Color.White);

spriteBatch.End();

```

I don't have any errors, the text is simply not shown. I think I could be close to a solution since one and only one single time the text appeared, but as the fool I am I happily closed the tabs of countless tutorials and made some changes which led the text to never show again.

# Answer
> What I wanted was instead something HUD-like.

To make it always appear on top, simply draw it last.

```
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
spriteBatch.Draw(someTexture,...);
spriteBatch.DrawString(...); //Will overwrite someTexture
spriteBatch.End();

```

Alternatively, there are overloads for `Draw(...)`, `DrawString(...)`, etc. that allow you to specify the layer depth used by spritebatch to sort sprites.

```
spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
spriteBatch.DrawString(,,,,,,,,,0); //Will overwrite someTexture
spriteBatch.Draw(someTexture,,,,,,,,100);
spriteBatch.End();

```

But you can also use multiple batches:

```
spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
spriteBatch.DrawString(,,,,,,,,0);
spriteBatch.End();
spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
spriteBatch.Draw(someTexture,,,,,,,,100); //Different batch; will overwrite text
spriteBatch.End();

```

> if you know how to change fontsize and other properties like the font itself (I don't like Arial this much) I would be extremely happy.

* Right click on Content -\> Add -\> New item -\> SpriteFont Description -\> Give it a name;

This creates a `.spritefont` file which contains very simple XML pointing to a particular \[font\]-\[size\] which is then used to build the XNB spritesheet. You can edit the `.spritefont` file with Notepad.
> -1 votes

---
Tags: c#, monogame, fonts, spritefont
---


# Question
Title: How solve 400 Bad Request error in unity?
400 Bad Request UnityEngine.Debug:Log(Object) FBScript:DisplayUserName(IResult) (at Assets/Script/FBScript.cs:63) Facebook.Unity.c\__Iterator1:MoveNext() (at Assets/FacebookSDK/SDK/Scripts/Utils/AsyncRequestString.cs:133)

```
void DisplayUserName(IResult result){
    Text UserName = DialogUserName.GetComponent<Text>();
    if (result.Error==null  ) {
        UserName.text = "Hi there," + result.ResultDictionary ["first_name"];
    } else {
        Debug.Log (result.Error);

    }
}

```

# Answer
> 1 votes
As SamedTarıkÇETİN said,

> 400 Bad Request means "request is not valid", you can't get a valid response with an invalid request.

Thanks man.

Well, I hope you are following the general way to Login Facebook as described in this answer.

If you want to get User Name from Facebook then you can use Graph API in this way.

After login successfully, call Graph API for name as,

```
FB.API ("me?fields=name", HttpMethod.GET, GraphCallbackForName);

```

Then in `GraphCallbackForName` callback, retrieve name as,

```
void GraphCallbackForName (IGraphResult result)
{
    IDictionary<string,object> dict = result.ResultDictionary;
    string fbname = dict ["name"].ToString ();
    Debug.Log ("FB Name: " + fbname);
}

```

# Answer
> 0 votes
From w3c.org:

> 400 Bad Request
>
> The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

I assume you fetch the dictionary every frame, or so often. For fetching static information from websites, you shouldn't request so frequently.

And for a "username", it is enough to fetch at the Start method and store the info on a field.

So you don't have to fetch information again and again, you can just use the value of field.

---
Tags: unity
---


# Question
Title: How to clamp a direction vector within a direction pyramid?
In 2D you can specific an angle range such as \[-45 to +45\] and clamp a 2D direction vector within that angle range. I want to have something similar for 3D. I want to specify the allowed directional range as a center directional axis with a local y-axis range and a local x-axis range and clamp an arbitrary 3D directional vector within that range. How do I do that?

For example, I want to specify a angle range as axis (1,0,0) with \[-30 to 30\] as the local y-axis angle angle and \[-10 to 10\] as the local x-axis range. So that something like (0.95,0.1,0.1).normalized() would not be changed but (-1,0,0) would be clamped to an appropriate vector.

# Answer
Assuming your pyramid is defined by a direction vector, an up vector (for the general case, that the pyramid is rotated, it probably defaults to (0, 1, 0)) and two angles maxPitch and maxYaw, I came up with the following solution (in c++, but easily translateable to other languages):

```
class ViewingPyramid {
    private:
        Vector3 direction, up, right;
        float maxYaw, maxPitch;

    public:
        ViewingPyramid(Vector3 dir, Vector3 up, float yawmax, float pitchmax) :
            direction(Vector3::Normalize(dir)),
            up(Vector3::Cross(direction, Vector3::Normalize(Vector3::Cross(up, direction)))),//Getting a rectangular, orthogonal up vector
            right(Vector3::Cross(direction, this->up))
        {}

        Vector3 Clamp(Vector3 dir) {
            Vector3 abc = getSolutions(right, up, direction);

            Vector3 xz = Vector3::Normalize(dir - abc.Y*up);
            float yaw = Math::Clamp(Vector3::Angle(direction, xz), -maxYaw, maxYaw);

            Vector3 yz = Vector3::Normalize(dir - abc.X*right);
            float pitch = Math::Clamp(Vector3::Angle(direction, yz), - maxPitch, maxPitch);

            Vector3 res = direction;
            Quaternion qYaw = Quaternion::CreateFromAngleAxis(up, yaw);
            Quaternion qPitch = Quaternion::CreateFromAngleAxis(right, pitch);
            res *= qYaw;
            res *= qPitch;

            return res;
        }
    };

```

As you can see, it relies on some prebuilt math functions, which should mostly be easy to implement. I did not test it, because I don't have `getSolutions` implemented in my simple math library, but I'm pretty confident this works as intended. You can use whatever library you want (For example Eigen in C++) for math functions, or implement your own. The most complicated part is the `getSolutions` function, which gets the solutions for the equation `dir = a*right + b*up + c*direction`.

I hope this helps.
> 1 votes

---
Tags: mathematics, animation, rotation, vector
---


# Question
Title: What is the difference between "stealth" and "social stealth?"
I was recently researching the stealth mechanics of several games and I stumbled across the distinction of "stealth" (eg. Splinter Cell series) vs "social stealth" (eg. Assassin's Creed series).

What exactly is the difference between these two terms?

# Answer
Classic stealth is typically when you're using occlusion, camouflage, darkness, silence, disabling of detectors, and inanimate distractions (like throwing a rock to make someone look the other way) to hide your *presence*.

Social stealth is when you're using a crowd or disguise to hide your *identity as a threat*.

Basically, if it entails a person other than you and the observer you want to hide from (like an authorized person you're impersonating, or townsfolk you've riled up by throwing money to distract guards in an Assassin's Creed game), it's typically deemed "social."

Both can overlap and achieve the goal that an opponent doesn't know where the threat is. The trick with social stealth is they might be aware of your presence, but just don't identify you as a threat, because you pass for someone who's supposed to be there.
> 6 votes

# Answer
Going to quote Wikipedia on this, but it looks like social stealth is subtype of stealth.

From Wikipedia's article on Stealth Game:

> In 2007, Assassin's Creed employed a social element to the stealth game, where the player is able to hide among crowds of civilians by taking care to blend in.

Poking around in a few other places, the distinction vs. other subtypes of stealth (evading via silence, evading via locomotion, evading via visually hidden, evading via distraction, etc.) seems to be that social stealth involves blending in to social environments via conforming to certain social norms to escape detection.
> 3 votes

# Answer
**Stealth** can be thought of as trying to avoid attracting attention by making it seem like you're not there.

**Social stealth** can be thought of as trying to avoid attracting attention by making it look like you *belong* there.
> 3 votes

---
Tags: game-design, game-mechanics, terminology
---


# Question
Title: How to convert a java made game for pc to android without any external framework?
How to convert a java made game for pc to android manually ie without any external framework like libgdx?
For example games like minecraft and limbo were originally made for pc only but later they got released for other platforms also, how do they do it?
Where can i learn more about porting games across multi platforms?

# Answer
> 0 votes
Porting games can be a painful process. You essentially need to rewrite large parts of the game, mainly the rendering and the input part, as they completely depend on the platform. Depending on the platforms you may be able to keep some of your code, but it's not guaranteed. You may end up deleting the complete rendering part of your code and start from scratch.

The actual game-logic code can be reused, as it should be platform independend. To simplify porting to other platforms I would encourage you to cleanly separate logic code from rendering code to make porting easier.

If you are using a pre-made game engine you may be lucky and it already supports multiple platforms, reducing the needed effort to port your game significantly.

There is no other way than rewriting the incompatible parts.

Also take a look at this: Cross-platform independent development

---
Tags: cross-platform
---


# Question
Title: Why does invoking glm::refract function return NaN?
At the present time, I make a simple raytracing project and I encounter an issue : When I invoking the glm::refract function, it returns me a vec3 with "NaN" values. However, my input data seems to be correct (2 normalized vec3 and my refractive-index is 1.0). Have you got an idea of the problem ? This function is not so well documented.

**EDIT :**

Very strange, if my refractive index is 1.0f it's working well actually :

```
glm::vec3 view = glm::vec3(0.191318035, -0.0721754059, 0.978870869);
glm::vec3 normal = glm::vec3(-0.151046738, -0.988510013, -0.00574064208);
float refractIndex = 1.0f;
glm::vec3 output = glm::refract(view, normal, refractIndex);

```

However, if I invoke the function and passing a refractive index of 1.10000002f for example (my program seems to approximate values and I don't know why...), it doesn't work =\> returns vec3 with "NaN" values. Like below :

```
glm::vec3 view = glm::vec3(0.191318035, -0.0721754059, 0.978870869);
glm::vec3 normal = glm::vec3(-0.151046738, -0.988510013, -0.00574064208);
float refractIndex = 1.10000002f;
glm::vec3 output = glm::refract(view, normal, refractIndex);

```

**EDIT 2 :**

More weird : If I try with a refractive-index of 1.1f it doesn't work. Same error.

# Answer
The refrative index must be within the range \[-1.0f, 1.0f\] inclusively.
> 0 votes

---
Tags: c++, 3d, glm
---


title: Game Server Mechanic

text:
# Question
Title: Game Server Mechanic
Hey guys :) Im currently developing a little rpg duengon crawler. I really want to implement a local and an online multiplayer function, i know how servers are working and how to make them using sockets or kryonet.

But heres my question, i want that when someone, starts a local server in my game, that it starts an runnable jar file which includes the server, is that recommend or just stupid ? Should the server be included in the game or outside in an extra file ? What should i obverse ? :)

# Answer
You might be interested in how games such as Quake 3 were built.

The game is made in such a way that the single player game is in fact a server that starts locally, with a client that connect to it.

This has the advantage that the multiplayer comes for free.

So if you intend to have your game available as 'public' *and* 'local' multi-player, I suggest you make the server part of the game, without having another thing to download for your players.
> 0 votes

---
Tags: java, libgdx, server, client-server
---


title: How do you freeze your cursor in Unity?

text:
# Question
Title: How do you freeze your cursor in Unity?
In a typical MMORPG, when I hold down the right click button and drag, the cursor disappears and stays in the same position.

How does one do that?

# Answer
You can easily do this, if you hide the cursor and draw your own cursor at Input.mousePosition.

http://docs.unity3d.com/ScriptReference/Screen-showCursor.html

Doing so, will allow you to lock the position of your custom cursor, by simply not updating updating to the latest Input.mousePosition.
> 2 votes

# Answer
On a mouse down event (or, if you're feeling fancy, on the first mouse move *after* a mouse down), hide the cursor. On a mouse up event, show the cursor again.
> 0 votes

---
Tags: unity
---


title: Keyboard and Mouse callbacks in GLUT

text:
# Question
Title: Keyboard and Mouse callbacks in GLUT
I'm using OpenGL via GLUT in Ubuntu.

```
While writing text in a text editor, the first keystroke is printed immediately.
But if we keep pressing the key, it waits for a moment and then prints a trail of that character.

```

This is to reduce the sensitivity while typing.

With GLUT, function callbacks for keyboard behave like that.

```
glutKeyboardFunc( keyboard );
glutKeyboardUpFunc( keyboard_up );

```

Now if we keep pressing a key, there is a considerable delay between the first and the second call of `keyboard` ( and `keyboard_up`) function. But in real gaming, this not should be the case.

**Question 1:** How to solve the problem?

**Question 2:** `keyboard_up` gets called even if I press and hold a key. Why so? I think it is supposed to get called only when I release it. Moreover, this also suffers from the above jerk problem.

**Question 3:** For `glutMouseFunc( mouse )`, the `mouse` function gets called whenever we press or release a mouse button. I want this too to get called repeatedly if I press and hold my mouse button, and that too without jerk. How to do so?

# Answer
> 2 votes
`glutIgnoreKeyRepeat` to ignore auto-repeated keystrokes. (that resolves Questions 1 & 2.)

There, unfortunately, isn't an option to make the mouse button's get called repeatedly. You can, however, **create variables recording the mouse button states**. And then read those when you need to know if a button is down. Just as good, or better. (Question 3)

Further Description: Recording key-states in variables for repeated use over many frames

Typically in games when you walk forward using a key, they don't rely on the OS's key-repeat. That can be adjusted so the repeat will likely be much slower then your game-loop cycle. That will create jerky movement that could be smoothed out if it was calculated on a per-frame basis.

One of the simplest ways to cut out that jerky movement, is to check that keys state on a per-frame basis. You can do that with function call's, that however will add a bit of unneeded overhead. So instead, you can record the key-state locally in the program. Since GLUT defines a key with `char`, there are only 255 different key's that you might get. So you only need an array 255 bytes long to store each key's state.

But then there are the 3 mouse buttons. 3 bytes, 1 for each mouse button. The ending result of all this is:

```
#define BUTTON_UP   0
#define BUTTON_DOWN 1

#define MOUSE_LEFT   0
#define MOUSE_MIDDLE 1
#define MOUSE_RIGHT  2

unsigned char keyState[255];
unsigned char mouseState[3];

void keyboard(unsigned char key, int x, int y)
{
    keyState[key] = BUTTON_DOWN;
}

void keyboard_up(unsigned char key, int x, int y)
{
    keyState[key] = BUTTON_UP;
}

void mouse(int button, int button_state, int x, int y)
{
    #define state ( (button_state == GLUT_DOWN) ? BUTTON_DOWN : BUTTON_UP ) // shortens later code

    switch (button)
    {
        case GLUT_MOUSE_LEFT:
            mouseState[MOUSE_LEFT] = state;
            break;
        case GLUT_MOUSE_MIDDLE:
            mouseState[MOUSE_MIDDLE] = state;
            break;
        case GLUT_MOUSE_RIGHT:
            mouseState[MOUSE_RIGHT] = state;
            break;
    }

    #undef state // make sure the defined "state" code above is only used in this function
}

void main()
{
    // some fancy code

    if (keyState[(unsigned char)'W'] == BUTTON_DOWN) // Walk forward
    {
        // W is being pressed! Time to walk.
    }

    if (keyState[(unsigned char)'1'] == BUTTON_DOWN) // render in Wire-Frame
    {
        // toggle wire-frame rendering

        // this key toggles wire-frame mode. We dont want it changing every frame,
        // Or it would keep changing to fast for the user to keep track of.
        // so we'll just say the key is up. Then it wont switch back before the user
        // is ready.
        keyState['1'] = BUTTON_UP;
    }

    // some more fancy code
}

```

# Answer
> 0 votes
`glutSetKeyRepeat` is faster than `glutIgnoreKeyRepeat`, so says this man page

> **glutIgnoreKeyRepeat** can prevent these auto repeated keystrokes from being reported as keyboard or special callbacks, but there is still some minimal overhead by the X server to continually stream KeyPress events to the GLUT application. The **glutSetKeyRepeat** routine can be used to actually disable the global sending of auto repeated KeyPress events.

Put this in your init/main

```
glutSetKeyRepeat(GLUT_KEY_REPEAT_OFF);

```

---
Tags: events, glut
---


# Question
Title: How can I achieve a flickering torch/candle effect in 2D?
I'm currently working on a 2D lighting system that has point lights effectively rendered as a quad in a top-down 2D view, something like this for each light:

I'd like to achieve a somewhat realistic "flickering" effect by changing the position and attenuation of the light over time, simulating the light emitted from a torch or candle. What would be a good way to adjust these attributes of the light, and how quickly / over how much time?

# Answer
Randomly.

But not *entirely* randomly, as pure noise isn't very pleasing and isn't really even realistic in this case. Instead, generate some kind of one dimension smooth, repeatable noise (based on Perlin noise, although that alone might be too smooth, so perhaps some FBM noise).

Use that to adjust the light's attenuation over time, and perhaps to jitter the light's effective position within a very small radius over time, and you should get a reasonable approximation of the candle effect.

As for exactly *how much* or *how often* to do this... that's mostly up to you and your art style and what "looks good" in practice. You'll likely need to tweak both the frequency of updates and the parameters to the noise functions to get an effect you really like.
> 5 votes

---
Tags: lighting, graphic-effects
---


# Question
Title: How to get the position in an actor inside a table with LIBGDX?
Well the title says it all, I want to get the position of an actor inside a table

```
Button button = new Button(bs);
table.add(button).width(50).height(50);
table.top().center();

```

By using

```
button.localToStageCoordinates(new Vector2(button.getX(), button.getY()));

```

I get a near position but not exact, here is an screenshot, red squares are the positions I'm getting, while the transparent squares are the buttons.

# Answer
> 2 votes
Okay I manage to do it like this:

> button.localToParentCoordinates(new Vector2(table.getX(), table.getY()));

---
Tags: java, libgdx
---


# Question
Title: How can I communicate user information from a website to a hosted Unity game?
I have a Ruby on Rails website running which provides a log-in system and dashboard for users. I am building a small game in Unity which is much like an inventory management system. But, the inventory is specific to a user and the user can make changes to it. The user sees the game as a part of *his* dashboard.

What I'd like is for the moment the user lands on his dashboard, the Unity game should load with the inventory of the signed-in user. How can I get this user information from the Ruby dashboard over to Unity?

# Answer
I think your question is asking how to know which user has loaded the webplayer. (If not, please provide more details.)

Unity can communicate arbitrarily with the browser and vice versa via JavaScript (details and examples here in the manual).

On app startup you can request this data from within Unity with `Application.ExternalCall()`, by calling to a function in the browser that will in turn run (javascript) `UnityObject2.getUnity().SendMessage(...)` to transfer the information back to Unity. These messages can be used to tell Unity which user is logged in and, if you choose, the needed authentication information.

With this, you should have all the information you need to request that user's inventory from your server. Displaying/updating it after that should be straightforward.
> 2 votes

---
Tags: unity
---


# Question
Title: Exception whilst doing a full screen negative colors effect
I'm trying to solve a bug I have in my XNA game.

I have an Effect that I want to apply on the screen when I activate an Item.

Currently, I have this weird bug where it throws an exception in the Main method, highlights"

```
using (Game1 game = new Game1(args))
{
    game.Run(); // Throws exception here
}

```

> An unhandled exception of type 'System.InvalidOperationException' occurred in Microsoft.Xna.Framework.Graphics.dll
> Additional information: Cannot call Present when a render target is active.

I've come to understand that it has something to do with RenderTarget2D and setting the render target.

Currently, that's the code that draws (Sorry, 2 months of working on a game with 3 other guys, and our code is hardly readable):

```
    /// <summary>
    /// This is called when the game should draw itself.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.Crimson);

        try
        {
            if (effWholeScreenEffect != null)
                ///////////////////////////////////////////////////////////////////////////////
                DrawWithFullScreenEffect(); // That's when it's supposed to negate whole screen
            else
                PerformDraw();
        }
        catch { }
        finally
        {
            base.Draw(gameTime);
        }
    }

    private void DrawWithFullScreenEffect()
    {
        var rtbSaver = GraphicsDevice.GetRenderTargets();

        using (RenderTarget2D rtScreen = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height))
        {
            GraphicsDevice.SetRenderTarget(rtScreen);

            PerformDraw();

            if (effWholeScreenEffect != null)
            {
                spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, effRingOfGodsFury);
            }
            else
            {
                spriteBatch.Begin();
            }

            GraphicsDevice.SetRenderTarget(null);

            // Draw whole screen
            spriteBatch.Draw(rtScreen, new Rectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height), Color.White);

            spriteBatch.End();
        }
    }

    private void PerformDraw()
    {
        #region Game World Section
        // Draw game map
        gameMap.Draw(spriteBatch, GraphicsDevice.Viewport);

        // Draw connection players
        cntConnection.DrawPlayers(spriteBatch);

        try
        {
            projectileHandler.Draw(spriteBatch);
        }
        catch
        {

        }

        #endregion

        #region Hud Section

        #region Inventory Draw

        int nCurrItem = 0;

        // Run over player's inventory dictionary
        for (byte bCurrIndex = 0; bCurrIndex < Inventory.INVENTORY_SIZE; bCurrIndex++)
        {
            // If the player got the item
            if (localPlayer.Inventory[bCurrIndex] != null)
            {
                // Set fill amount parameter
                effItemIcons.Parameters["fFillAmount"].SetValue(localPlayer.Inventory[bCurrIndex].FillAmount);

                spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, null);

                // If player has an item selected and its the current item
                if ((localPlayer.SelectedItem != -1) &&
                    (localPlayer.SelectedItem == bCurrIndex))
                {
                    // Draw the icon
                    spriteBatch.Draw(tSelectedBorder,
                                     new Rectangle(8 + (50 * nCurrItem),
                                                   GraphicsDevice.Viewport.Height - 72,
                                                   52,
                                                   52),
                                     Color.White);
                }
                else
                {
                    effItemIcons.CurrentTechnique.Passes["CoolDown"].Apply();
                }

                // If mana cost is bigger than current mana
                if (localPlayer.Inventory[bCurrIndex].ManaCost > localPlayer.MP)
                {
                    effItemIcons.CurrentTechnique.Passes["NotEnoughMana"].Apply();
                }

                // Draw the icon
                spriteBatch.Draw(localPlayer.Inventory[bCurrIndex].Icon,
                                 new Rectangle(10 + (50 * nCurrItem),
                                               GraphicsDevice.Viewport.Height - 70,
                                               48,
                                               48),
                                 Color.White);

                spriteBatch.End();

                spriteBatch.Begin();

                // Write the key
                spriteBatch.DrawString(sfPlayerNameFont,
                                       bCurrIndex.ToString(),
                                       new Vector2(25 + (50 * nCurrItem),
                                                   GraphicsDevice.Viewport.Height - 20),
                                       Color.White);

                spriteBatch.End();

                nCurrItem++;
            }
        }

        #endregion

        spriteBatch.Begin();

        #region Team Score

        spriteBatch.Draw(tScoreBoardTexture,
                         new Rectangle(GraphicsDevice.Viewport.Width / 2 - tScoreBoardTexture.Width / 2,
                                       5,
                                       tScoreBoardTexture.Width, tScoreBoardTexture.Height),
                         Color.White);

        spriteBatch.DrawString(sfScoreBoardFont,
                               cntConnection.GoatScore.ToString(),
                               new Vector2(GraphicsDevice.Viewport.Width / 2 + 20, 30),
                               Color.Azure);

        spriteBatch.DrawString(sfScoreBoardFont,
                               cntConnection.HolyCowsScore.ToString(),
                               new Vector2(GraphicsDevice.Viewport.Width / 2 - 40, 30),
                               Color.Azure);

        spriteBatch.DrawString(sfScoreBoardFont,
                                ((double)(cntConnection.RoundTimeRemaining / 100) / 10).ToString(),
                                new Vector2(GraphicsDevice.Viewport.Width / 2 - 50, 60), Color.Azure);

        #endregion

        #region Mini Score Tab

        #region Layout

        spriteBatch.Draw(tMiniScoreTab,
                         new Rectangle(GraphicsDevice.Viewport.Width - tMiniScoreTab.Width,
                                       0, tMiniScoreTab.Width, tMiniScoreTab.Height),
                         Color.White);

        #endregion

        #region Information

        spriteBatch.DrawString(sfMiniScoresTabFont,
                               "Ping : " + cntConnection.Ping +
                               "\nGold : " + localPlayer.Gold,
                               new Vector2(GraphicsDevice.Viewport.Width - 350, 5),
                               Color.Azure);

        spriteBatch.DrawString(sfMiniScoresTabFont,
                               "Kill      : " + localPlayer.Kills +
                               "\nDeath : " + localPlayer.Deaths,
                               new Vector2(GraphicsDevice.Viewport.Width - 255, 5),
                               Color.Azure);

        spriteBatch.DrawString(sfMiniScoresTabFont,
                               "Health : " + localPlayer.HP +
                               " / " + localPlayer.MaxHP + "\n" +
                               "Mana   : " + localPlayer.MP +
                               " / " + localPlayer.MaxMP,
                               new Vector2(GraphicsDevice.Viewport.Width - 160, 5),
                               Color.Azure);

        #endregion

        #endregion

        #region Scores Tab

        // If bIsScoreTab is true
        if (bIsScoreTabShown)
        {
            // Draw the ping shiiiiiiit
            ScoresTab.Draw(spriteBatch,
                           cntConnection.Players,
                           ScoresTab.nPing,
                           GraphicsDevice.Viewport.Width - ScoresTab.FRAME_WIDTH + 30,
                           65);

            #region DEBUG

            if (DEBUG_MODE)
            {
                // Draw the velocity shiiiiiiit
                spriteBatch.DrawString(sfPlayerNameFont,
                                       "VelX : " + Math.Round(localPlayer.VelX, 3) +
                                       "\nVelY : " + Math.Round(localPlayer.VelY, 3),
                                       new Vector2(GraphicsDevice.Viewport.Width / 100, 20), Color.White);
                // Draw the velocity shiiiiiiit
                spriteBatch.DrawString(sfPlayerNameFont,
                                       "| PosX : " + localPlayer.PosX +
                                       "\n| PosY : " + localPlayer.PosY,
                                       new Vector2(GraphicsDevice.Viewport.Width / 100 + 120, 20), Color.White);

                // Show the camera position
                spriteBatch.DrawString(sfPlayerNameFont,
                                       "| ViewportX : " + Camera.CameraVector.X +
                                       "\n| ViewportY : " + Camera.CameraVector.Y,
                                       new Vector2(GraphicsDevice.Viewport.Width / 100 + 250, 20), Color.White);
            }

            #endregion
        }

        #endregion

        #region Shop

        if (bIsShopOpen)
        {
            ItemShop.Draw(spriteBatch, GraphicsDevice.Viewport);
        }

        #endregion

        #region Messages

        // Go over messages
        for (int nCurrMessage = 0;
             nCurrMessage < cntConnection.Messages.Length;
             nCurrMessage++)
        {
            if (cntConnection.Messages[nCurrMessage].MessageType != ActionType.Empty)
            {
                spriteBatch.DrawString(sfMiniScoresTabFont,
                                       cntConnection.Players[cntConnection.Messages[nCurrMessage].ActionPerformerID].Name +
                                       cntConnection.Messages[nCurrMessage].Mess +
                                       cntConnection.Players[cntConnection.Messages[nCurrMessage].ActionRecieverID].Name,
                                       new Vector2(5, 5 + (15 * nCurrMessage)), Color.White);
            }
        }

        #endregion

        spriteBatch.End();

        #endregion
    }

```

I haven't found any valuable information regarding that exception, so I hoped you guys would know more than me...

Thanks for reading and I hope the code hasn't given you some kind of cancer.

# Answer
> 1 votes
The root cause isn't obvious to me, but:

```
try //Try to do some drawing
{
   ...
}
catch
{
   //If there are any errors (NullReference, DeviceLost, etc.), just ignore them
}
finally
{
   //And Present() anyway (evidently with a RenderTarget set)
   base.Draw(gameTime);
}

```

Instead:

```
try
{
   ... //Try to do some drawing
   base.Draw(gameTime); //then Present()
}
catch (DeviceLostException ex) //Most-specific first
{
   //Recover or gracefully abort
}
catch (Exception ex) //Least-specific catch-all
{
   int a = 1; //When this breakpoint is hit, inspect ex and figure out what should happen
   //  ^-- Add breakpoint
   throw ex; //Something unknown is definitely wrong; do not continue
}

```

Possible null reference:
(using the clue that something is happening before `GraphicsDevice.SetRenderTarget(null)`):

```
if (effWholeScreenEffect != null)
{
   //spriteBatch.Begin(..., effRingOfGodsFury);
   spriteBatch.Begin(..., effWholeScreenEffect); //Did you mean...
}

```

or:

```
//if (effWholeScreenEffect != null)
if (effRingOfGodsFury != null) //Did you mean...
{
   spriteBatch.Begin(..., effRingOfGodsFury);
}

```

**WARNING:**

```
using (RenderTarget2D rtScreen = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height))

```

Create and initialize the rendertarget **once**, any time the backbuffer dimensions (Viewport?) change. You may need to use the `RendertargetUsage.PreserveContents` flag during creation.

---
Tags: xna-4.0
---


# Question
Title: How can I prevent 2D teleportation from teleporting through solid objects?
In my 2D game, the player is able to teleport to any place on the screen with the click of the mouse button. What I am trying to *prevent* is the ability to teleport across solid objects. If the point from the player and the mouse click position is across an object then I want the player to teleport *next* to that object instead of across it.

I am currently trying to achieve this with raycasting. The code I wrote somewhat works but only if the mouse click is on an object, if the mouse click is across another object, it still teleports me accross the object without it registering that there is an object between the player and the mouse position.

My code:

```
Vector3 player_position = Camera.main.WorldToScreenPoint(transform.position);
Vector3 to_object_vector = transform.position - Camera.main.transform.position;
Vector3 linear_distance_vector = Vector3.Project(to_object_vector, Camera.main.transform.forward);

float distance_to_camera = linear_distance_vector.magnitude;
Vector3 mouse_position = Input.mousePosition;
float dist = Vector2.Distance(player_position, mouse_position);
Vector3 dir = (mouse_position - player_position).normalized;
mouse_position.z = distance_to_camera;

RaycastHit2D hit = Physics2D.Raycast(new Vector2(player_position.x, player_position.y), new Vector2(dir.x, dir.y), dist, 0);
if (hit.collider != null) {
     Debug.Log(hit.point);
     mouse_position = new Vector3(hit.point.x, hit.point.y, mouse_position.z);
}

```

Is there a better approach to this problem?

# Answer
> 0 votes
One thing you should do, and this is useful for all of your Unity projects, is using `Debug.DrawLine` (if you have `origin` and `destination`) or `Debug.DrawRay` if you only have the `direction` vector.

I haven't used 2D mode in Unity, but I guess you can still use 3D in Scene inspector, right? If so, then use the functions above to throw rays from player to the `hit.point` position. You should do it into Update function, since it could draw a ray just for 1 frame if you don't and you wouldn't see it.

Things to check if working properly:

1. Check if the ray is drawing always trough the object when you click behind it, if it does, then you're not setting the nearest position properly.
2. Check that those objects you don't want to go through are not in a `Ignore raycast` layer.

Now, talking about how to move your character, I would try to use Physics AddForce. Even though it is 3D, you can just use 0 into x/z axis and use Physics to move character. If you multiply the vector for a high thrust, I think you could get a teleport simulation (deactivating `MeshRenderer` before doing it, for example). Remember you need a Rigidbody to use that physics, and probably need to mark it as `Kinetic` in order to avoid it bouncing.

Hope this helps you.

# Answer
> 0 votes
Well since raycasting cannot solve my specific issue which is unfortunate, since it should return the end point of any solid objects that interrupts that line I was forced to expand my colliders far enough to where the player can't click over the object like so:

Since my if statement is checking if the player is clicking on a collider I will always teleport to the hit.point preventing the player from going outside the map indefinitely!

---
Tags: 2d, unity, raycasting
---


title: Unity 2D Diablo style movement

text:
# Question
Title: Unity 2D Diablo style movement
I've made a totally new scene for a 2D mobile game. I placed a sprite on the center of the screen and attached the following script onto it (this is basically a diablo-style click-to-move control script, the sprite follows the pointer when it is clicked):

```
using UnityEngine;

public class Movement : MonoBehaviour
{
private float _moveSpeed = 5;
private Vector3 _targetPosition;
private float _targetDistance;

void Update()
{
    _targetDistance = Vector3.Distance(_targetPosition, transform.position);

    if (_targetDistance < 1)
    {
        _moveSpeed = 0;
    }
    else if (_targetDistance > 1)
    {
        _moveSpeed = 5;
    }

    if (Input.GetMouseButton(0))
    {
        Plane playerPlane = new Plane(Vector3.up, transform.position);
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        float hitdist = 0.0f;

        if (playerPlane.Raycast(ray, out hitdist))
        {
            _targetPosition = ray.GetPoint(hitdist);
        }
    }

    if (_targetDistance > 1)
    {
        transform.position += (_targetPosition - transform.position).normalized * _moveSpeed * Time.deltaTime;
    }
}
}

```

Normally this script doesn't work unless I rotate the main camera by 90 degrees (axis: X) and rotate the sprite also by 90 degrees (axis: X).

How should I modify the script to make it work without rotating the camera and all the sprites I place on the scene?

Thank you in advance!

# Answer
> 1 votes
When working spatially, especially with hidden geometry (such as the Plane you generate for receiving raycasts from the screen's mouse pos to the scene), you want to be absolutely sure you're getting what you expected.

**Here's what your plane looks like:**

**Here's how it should be:**

In the line `Plane playerPlane = new Plane(Vector3.up, transform.position);`

Change `Vector3.up` to `Vector3.forward`, **as your camera is (assumed) facing foward you need to set the orientation of the plane to the same** in order to use it as a flat surface!

*Remember that you can visually debug geometric problems with Unity's wonderful Gizmos and Handles classes!*

---
Tags: unity, 2d, camera, movement
---


# Question
Title: Is it safe to set Lua Table data from multiple C++ threads?
As the title states. I'm curious if it's safe to set data in different Lua tables that exist in the same lua state. From multiple C++ threads.

I'm asking this because my current system actually has a separating between Lua's data, and C++'s data, with Lua driving the majority of the game's update and loop - and C++ handling lower level details such as math, rendering, resources, and physics.

After the physics update, I have to waste time in having an entire phase for Lua to update it's own internals for Serialization and grabbing references.

# Answer
> 5 votes
No, Lua's state is not really thread-safe by default, so you can't access the same state from many threads without work on your part.

Lua will call `lua_lock` and `lua_unlock` at appropriate points, but by default these methods do nothing and you must `#define` them to implementations that actually take the appropriate platform-specific critical section.

However, that implements the most bare-bones approach to thread synchronization which just makes sure only one thread is running Lua at a time. You can see here for more information.

A better approach might be trying to reorganize your update loop so something else can happen *concurrently* with the Lua state sync, which only itself happens on one thread. Perhaps after physics is done processing, you can both synchronize Lua and prepare your graphics calls at the same time? Or something similar; it's admittedly hard to say without knowing more about your architecture.

---
Tags: c++, multithreading, lua
---


title: Ways to improve endless racing traffic

text:
# Question
Title: Ways to improve endless racing traffic
I am looking for ways to improve my traffic AI for endless racing game.

Currently, I have hard coded situations where randomly cars will be spawned ahead of user bike depending on position of player.

The thing most bothering me is how to provide user challenging situations where he will feel fun to play. Good example of such AI can be found here, https://www.youtube.com/watch?v=CJozc6PA9lI

What are the ways you guys would go on implementing Traffic AI for endless racing? What's your suggestion on same.

# Answer
I've never really thought about it since these type of games don't amuse me much. This is, essentially, "Frogger", except that you are travelling parallel to the enemies instead of perpendicular to them. With that in mind and having watched the YouTube you linked, here's what appears to be happening:

1. Every X seconds, spawn a *group* of Y cars
2. Y appears to begin at 2 and increment by 1 or 2 each "level"
3. Speed increases each "level"
4. X slightly decreases with each "level"
5. After a few groups of 5, it appears to change to more frequent groups of 3
6. The composition of each group is psuedo-random

A minimal set of behaviors:

1. Each type/color of car has a specific behavior.
Examples include:
    * Right/Center/Left lane only
    * Start left, move and stay right
    * Start left, move right, move center
    * Random lane change either way
2. Cars may not drive through other cars

Combined with a bit of randomness, these deceptively simple rules should make a good game.

Optional behavior examples:

1. Some vehicle types speed up or slow down when near player
2. Some vehicle types prefer to change lanes abruptly when near player
3. Cars moving faster than player, passing them from behind

For spawning (psuedo-code):

```
ArrayList enemies;
ArrayList expiredEnemies;
int groupSizes[maxLevel] = { 2, 3, 5 };
void Update(float deltaTime) //Game
{
   if (enemies.Count == 0)
      SpawnAGroup(groupSizes[currentLevel]);
   expiredEnemies.Clear();
   foreach (enemy in enemies)
     enemy.Update(deltaTime);

   //Can't delete enemies from enemies while iterating it so we cleanup afterwards
   foreach (enemy in expiredEnemies)
     enemies.remove(enemy);
}

float velocity;
void Update(float deltaTime) //Enemy
{
   bool laneChangeEnabled = true;
   if ((player.lane == this.lane) //Same lane as player
   {
      if (this.y > player.y) //player is behind this enemy
        if (this.y - player.y < carLength) //closer than carLength
          velocity = 1.1; //Speed up a little
   }
   else //Different lane than player
   {
      if (this.y > player.y) //player is behind this enemy
        if (this.y - player.y < carLength) //closer than carLength
        {
           laneChangeEnabled = false;
           velocity = 0.9; //Slow down
        }
   }

   if (laneChangeEnabled)
   {
     int random = GenerateRandomIntInclusive(1, 100);
     if (random > 95) //"5%" chance to change lanes
     {
        int direction = GenerateRandomIntInclusive(0, 1); //0 or 1
        direction = (direction * 2) - 1; //Scale to (0 or 2) then move to (-1 or 1)
        if (player.lane != this.lane + direction) //If player isn't in target lane
           position.x += direction;
        else //Player IS in target lane
           if (player.y < this.y - carlength) //Is player more than one car length behind?
              position.x += direction;

        //Off-roading not allowed
        position.x = Math.Clamp(position.x, leftMostX, rightMostX);
     }
   }

   position.y += velocity * deltaTime; //Always go forward

   if (position.y < 0) //Off-screen
   {
      expiredEnemies.add(this);
   }
}

```

If this is your road:

This code tries to spawn `numCars` enemies, giving up if it takes too long

```
ArrayList<int2> newCars;
void SpawnAGroup(int numCars)
{
   newCars.Clear();
   int tryCount;
   int2 testPosition;
   for (i = 0, i < numCars; i++)
   {
     tryCount = 0;
     testPosition.x = GenerateRandomIntInclusive(1, 3);
     testPosition.y = 6 + GenerateRandomIntInclusive(1, 3);
     while (!isValid(testPosition))
     {
        if (tryCount++ == 10) //Don't try forever
          break;
        testPosition.x = GenerateRandomIntInclusive(1, 3);
        testPosition.y = 6 + GenerateRandomIntInclusive(1, 3);
     }
     if (tryCount < 11) //If giving up, tryCount == 10++
     {
        //Spawn new car i
        enemies.Add(new Enemy(RandomEnemyType(), testPosition));
        newCars.Add(testPosition); //For isValid()
     }
   }
}

bool isValid(int2 position)
{
   if (newCars.Contains(position)) return false;
   ... //Now all the "rules" go here
   //if (currentLevel == 1) //Can also apply certain rules to specific levels
   return true;
}

```

Verify the system is working before adding a bunch of rules. The only rule I've included is that we will only spawn one car per square. The rules should be very simple (a pile of `if`'s is fine) but it shouldn't take an *enormous* amount of them. Once it's working, another very important rule is to not spawn more than 2 enemies for any given Y (road block).

I ran a few "simulations" (tic-tac-toe):

It seems:

* We need to spread cars evenly on the X (top "too easy")
* We can't fill an entire row (top "too hard")
* At least one stationary car is preferred (bottom "too easy")
* All lane-changers should not lane-change in the same direction (bottom "too easy")

And, for every X cars spawned (3-ish):

* At least one lane-changer is preferred (bottom "ok" fixes bottom "too hard")
* At least one bi-directional lane-changer is preferred (top "ok")
* Absolute maximum of 2 bi-directional lane-changers (top "unreliable")
* Too many bi-directional lane-changers becomes dependent on "pushing" cars out of the way via the enemy speed-up/slow-down mechanism (bottom "unreliable")

**Important note:**

All of this relies on "random" numbers which aren't actually random. If you do not change the "seed", the game will appear to be random the first time you run it, but every time after will be an exact re-play of the same "map", so to speak. You should definitely generate a new seed at game start and then, again, every X seconds, or each level; not too often.
> 5 votes

---
Tags: unity
---


title: Pausing the game

text:
# Question
Title: Pausing the game
I've had a look around and kept finding about using Time.TimeScale = 0 to pause the game, although this is the normal way to do it, it is not exactly what im looking for.

When my menu button is pressed I have a texture which is instantiated and slides onto screen from the left side and therefore does not work with Time.TimeScale because the menu just stays hidden off scren.

Is there a way to have the game pause but still allow for this menu to slide onto screen?

Edit -

How I spawn in the Menu prefab (Within GameController Script):

```
public void MenuPressed ()
{
    Vector3 newPosition = new Vector3 (-13, -0.06f, -2);
    Quaternion newRotation = Quaternion.Euler (0, 0, 0);
    Instantiate (menu, newPosition, newRotation);

    menuButton.SetActive (false);

    textFrame.SetActive (true);
}

```

How I move the Menu (Within MenuMover Script):

```
void Start()
{
    rb = GetComponent<Rigidbody> ();

    rb.velocity = transform.right * speed;
}

void OnTriggerEnter (Collider other)
{
    if (other.tag == "MenuBoundary")
    {
        rb.velocity = Vector3.zero;
    }
}

```

}

# Answer
You can use `Coroutines` for that. With `WaitForEndOfFrame` as it does not depend on `Time.timeScale`. What you have to do is to get rid of `Rigidbody` and `Colliders`.

So let say your menu Max X value (where it would stop actually) is `15`. Then you can do with some code like,

```
// Script attached to your prefab

float _xLimit = 15;
float _speed = 0.1f;

void Start ()
{
    StartCoroutine ("MoveMenu");
}

IEnumerator MoveMenu ()
{
    while (true) {
        transform.position += Vector3.right * _speed;
        if (transform.position.x > _xLimit)
            yield break;
        yield return new WaitForEndOfFrame ();
    }
}

```
> 1 votes

# Answer
Looks like you're attemnpting to use the physics engine in order to slide the text from left to right. The physics engine is paused effectively when you set the time scale to zero, so you'll need to slide your menu in without the aid of physics.

There are a couple of solutions you could try here:

The first is to use an animation on the object you want to slide across and set the animator controller's update to 'Unscaled Time' (http://docs.unity3d.com/ScriptReference/AnimatorUpdateMode.html)

The second is to move the menu transition to the Update loop (which is always called, even when the time scale is zero) and use Time.unscaledDeltaTime to keep the transition consistent (in this case you can change the transform position on each update)

As the physics engine is disabled you'll also need a new way to determine the boundary (as your trigger won't register). You could use something like the screen width or a game object position to determine when to stop in this instance... or if it's always a fixed width, just use that.
> 0 votes

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


# Question
Title: How do I interpret the differences between the "Time" and "Self" columns in Unity's profiler?
I'm not quite understanding how to read the results of the profiler:

A method `Pathfinding_NodeAdjuster.CheckSpecificArea()` method is using up 94.7% of the `BehaviorUpdate` overall time, while taking 73.4% of that time on itself (taking ~74ms of actual time) excluding other function calls. What I don't understand is where this 74ms time is coming from.

Now I realize that if I averaged the time for all 1221 calls of this method, I would probably end up with ~74ms of time spent. But what is that time being spent on? I would have suspected `GetComponent()` / adding and clearing the `List` / something like that. But those are listed separately and only combine to get a few ms of time between them. So, where is all the time being spent coming from?

I've included the method in question, if you want more info just let me know. Any ideas are appreciated.

UPDATE:

A:

What I still not sure on (and could have asked better) is:

-CheckSpecificArea() which takes 74ms, if time spent in other methods is not counted all that is left in the method is really 4 \<= / =\> comparisons, 2 assignments, and 1 assignment with an explicit cast which are repeated. Granted that some of those sections are run a lot of times, but are those operations really that 'expensive'? I guess so.

B:

Something else I probably should have realized sooner is that the times listed by the Profiler 'don't reflect regular operation', or in other words that the times listed also include the time needed to 'profile those scripts'. I made my own small bit of code to profile the script during normal gameplay and Deep Profile Recording using Time.realTimeSinceStartup and realized that after isolating the 3 main sections of the script that profiling them was adding increase in processing time from ~7.7x to ~9.3x. And the Self ms times in the Profiler are even 10x longer than what my profiling code shows during Deep Profiling. All this is still logged as time needed to complete the frame (so in my case a 100ms frame is really more like 13-15ms \[and probably much less\] ).

```
    private bool CheckSpecificArea(List<GraphUpdateScene> gusAreaToCheck, GraphNode gn)
{
    for (int areaCounter = 0; areaCounter < gusAreaToCheck.Count; areaCounter++) //check node location against each area of a certain type
    {
        if(nodeXZValues.x >= gusAreaToCheck[areaCounter].transform.GetComponent<Renderer>().bounds.min.x && nodeXZValues.x <= gusAreaToCheck[areaCounter].transform.GetComponent<Renderer>().bounds.max.x &&
           nodeXZValues.y >= gusAreaToCheck[areaCounter].transform.GetComponent<Renderer>().bounds.min.z && nodeXZValues.y <= gusAreaToCheck[areaCounter].transform.GetComponent<Renderer>().bounds.max.z)
            //basic bounds test to see if point could possibly be contained within the area before doing more advanced test (remember XY is really XZ).
        {
            gusPointList.Clear(); //prevent stacking.

            for (int i = 0; i < gusAreaToCheck[areaCounter].points.Length; i++) //for each polygon shape's nodes
            {
                gusNodeXZValues.x = gusAreaToCheck[areaCounter].points[i].x;
                gusNodeXZValues.y = gusAreaToCheck[areaCounter].points[i].z;

                gusPointList.Add(gusNodeXZValues);
            }

            if (PolyContainsPoint.ContainsPoint(gusPointList, nodeXZValues)) //needs GUS objects to use WORLD SPACE!!
            {
                gn.Tag = (uint)gusAreaToCheck[areaCounter].areaType; //set node tag value to the value of the GUS containing said point.

                return true;
            }
            else
            {
                #if DebugMaster
                Debug.Log("!PolyContainsPoint.ContainsPoint(gusPointList, nodeXZValues), NO match found");
                #endif
            }
        }
        else
        {
            #if DebugMaster
            Debug.Log("nodeXZValues NOT contained within renderer bounderies of: gusAreaToCheck[" + areaCounter + "], test concluded");
            #endif
        }
    }

    return false;
}

```

# Answer
> 3 votes
"Total" represents the overall cost of the function (in milliseconds or percentage, depending on the column). "Self" represents the cost of that function minus the cost of all child functions.

In other words, the answer to...

> where is all the time being spent coming from?

...is "all the code that *isn't* a function call."

In this case the "culprit" is probably the loop itself. This doesn't mean the loop is *slow*, it means a large part of the cost of that function is the loop it contains, which contains a (gated) inner loop and a bunch of non-function call computations. That inner loop is also where you call *another* high-cost function (`PolyContainsPoint.ContainsPoint`)

You should probably focus your optimization efforts on: \- reducing the number of times the outer loop has to iterate \- reducing the number of times the inner loop has to iterate or increasing the number of times the inner loop can be skipped entirely \- reducing calls to or or optimizing `PolyContainsPoint.ContainsPoint`.

---
Tags: unity, c#, performance, profiling, profiler
---