# Question
Title: How to move an object uniformly from one point to another at a fixed angle?
In my 2d java game, I need to move Point objects (as projectiles) from Enemy object to Player object in a straight line. I did some research and found out that I can use atan2(x, y) method of Math class to get the angle, but then how am i supposed to move the projectile in that particular angle(direction)? I checked this question: How do I calculate how an object will move from one point to another? , but did not quite understand. Also there is no vector math in java. Any ideas would be very helpful.

# Answer
\[**EDIT**: as I don't know what lib you're using, and as this question is not specific to Java, my answer is in pseudo-code.\]

If I understand your question correctly, atan2 is not what you're looking for.

What you want to achieve is moving something (which has coordinates) from one point to another according to time. You just need to compute the vector between the player entity and the target.

What you need here is:

* the position (x,y) of the player (player\_position).
* the position (x,y) of the target (target\_position).
* the speed at which you want your bullet to travel (in unit per seconds) (bullet\_speed).
* the time passed between two game updates (two frames) (deltaTime).

As you seem to have all of that, you seem ready to make that bullet move.

The vector from your player to the target, in pseudo code, is :

```
Vector2 diff_vector = player_position - target_position;

```

Then put your bullet at player\_position and move it each frame alongside this vector you just computed using the deltaTime between frames. Something like:

```
new_bullet_position = bullet_position + diff_vector * deltaTime * bullet_speed;

```

Changing bullet position each frame accordingly to the diff\_vector and the bullet\_speed will make it move uniformly from player to target.

I hope it helps.
> 0 votes

# Answer
Suppose the projectiles curret position is $(x,z)$. Then, in each step, you let $x\_{new} = x\_{old} + t \cos(\theta)$ and $y\_{new} = y\_{old} + t \sin(\theta)$ where $\theta$ is the angle you found, and $t$ is some small number (depending on the number of milliseconds since last update, for example).
> 0 votes

---
Tags: java, 2d, physics
---


title: How to save a Unity prefab on file?

text:
# Question
Title: How to save a Unity prefab on file?
I'm working on a Unity project, and what I'm doing is creating a new scene. In my new scene, I want add some prefabs that there aren't in the project folders, but I can see them in another scene.

So in my new scene I have only few prefabs, and I don't know how to add the prefabs that are present in the other scenes. Is there a way to do it?

# Answer
It seems that you mix up **GameObjects** and **Prefabs**.

When you say *"Prefabs in another scenes"* I think you are talking about Game Objects.

Game Objects are objects, prefabs or not, who are in a scene. Prefabs are Game Objects that can be "saved" in your game folder. You can find more about Prefabs here.

That said, and if I understand your question correctly, you want to instantiate Prefabs in your scene.

First of all you need to make the GameObject you want to instantiate a Prefab. Go to the scene where the GameObject you want is, and simply drag and drop it in the Unity Project View (where your game folder is). It should now be blue in the scene hierarchy, and visible as a prefab in the folder you dropped it in.

Now go back to the scene where you want to instantiate it. You have 2 options. One via the Editor and one programmatically (in fact you have another option using the Resources.Load but I won't explain it here).

**1. Via the editor**

To put a prefab in your scene, just click on it in the game folder (in the Project View) and drag it to the Hierarchy view. That's it. Your prefab is now a Game Object of your scene.

**2. Via script**

In a script of yours (a Monobehaviour) you can declare a prefab entry such as:

```
public Transform my_prefab;

```

Now, if you link your script to a GameObject you will see an empty entry called my\_prefab. Just drag your Prefab to that entry to fill it with the Prefab you want to instantiate. Later in your code you can instantiate it, in the Start method of your script for example, using:

```
private void Start()
{
    if ( my_prefab != null ) // check that the prefab is set.
    {
       Instantiate(my_prefab);
    }
}

```

Now, at Start, the prefab you have chosen will be instantiated in your scene.

I hope it helps.
> 3 votes

---
Tags: unity
---


# Question
Title: Fastest way to assign sprites to components in Unity
I'm using a sprite atlas and Unity's built-in sprite editor to tease out the individual images. Specifically, I have a single texture containing lots and lots of icons for armor, and I am assigning those to a `Sprite[]` field of a Component.

However, the process of manually assigning sprites to the component -- via drag and drop -- is tedious. Is there a faster way to do this? Perhaps a way I can bulk assign sprites to a component?

---

Update: This is the code of the final solution. In short, the easiest thing to do is to put the texture atlas in the `/Resources` folder and then programmatically access the sprites by name.

```
private void MergeTextureAtlas(string atlasName, Dictionary<ItemSubType, List<Sprite>> spriteLookup) {
    Sprite[] atlasSprites = Resources.LoadAll<Sprite>(atlasName);
    Assert.IsNotNull(atlasSprites, atlasName);
    Assert.IsTrue(atlasSprites.Length > 0, atlasName);

    int spritesLoaded = 0;
    foreach (ItemSubType itemSubType in Enum.GetValues(typeof(ItemSubType))) {
        string subTypeFriendlyName = ItemSubTypeHelper.GetSubTypeName(itemSubType);
        foreach (Sprite atlasSprite in atlasSprites) {
            if (atlasSprite.name.Contains(subTypeFriendlyName)) {
                if (!spriteLookup.ContainsKey(itemSubType)) {
                    spriteLookup.Add(itemSubType, new List<Sprite>());
                }
                spriteLookup[itemSubType].Add(atlasSprite);
                spritesLoaded++;
            }
        }
    }

    if (spritesLoaded == 0) {
        Debug.LogWarning(String.Format(
            "Found 0 new sprites in texture atlas '{0}'.",
            atlasName));
    }
}

```

# Answer
> 1 votes
The fastest / easiest way is to do it programmatically.

What you seem to do with weapon sprites is usually something that can be achieved via data driven programming. For that kind of stuff I usually load / set everything using JSON files. For such job JSON files content could look like :

```
{
   name: "axe",
   sprite_resource: "weapon_common_axe",
   damage: 5,
   speed: 12,
}

```

During loading times, using data driven programming, it's possible to easily set resources. Changing a sprite is as easy as opening a text file and set the correct name.

I hope it helps.

\[EDIT: fyi you can load text resources using Resources.Load as TextAsset\]

# Answer
> 2 votes
1. **Do it once for one component, then copy**. Once completed for one component right click the component and choose "Copy component". Then you can right click the target component and select "Paste component values" and only change the array elements that differ between the two.
2. **Do it in code**. Assign the sprites as defined in a text file programmatically. You can create a custom format for this, or use something like XML. This gives the added benefit of being modifiable outside Unity, like as a user mod. Or, you can assign them based on the name of the parent object (i.e. The component is looking for weapons and so you assign all the sprites with the word "weapon" in them to that array). Do this in the `Start()` method.
3. **Extend the editor with a script to do this**. Either with a bulk copy or the same type of script you'd use in option number two.

---
Tags: unity
---


title: Can I use sounds from UT2004?

text:
# Question
Title: Can I use sounds from UT2004?
What if I use some sounds from the game Unreal Tournament 2004? I can export them from `.uax` archives via **UnrealED** tool into `.wav` files. I could (and very would like to) import them into my game I am developing and use them there.

But is that right thing to do accoring to the copyright laws? Could Epic Games, I don't know, sue me for that? Or they can't unless I make the game shareware?

# Answer
All assets, including, but not limited to, sounds in Unreal Tournament 2004 are the property of Epic Games. Unless you obtain explicit permission you cannot use any asset from UT2004 in other games. I do believe you are allowed to use the assets to build maps and mods for UT2004, as long as the mods is not sold for money. You should consult a lawyer to be sure!

A partial solution is to get a commercial license for the Unreal Development Kit after which you can use all asset bundled with it. However, I do not know if the UDK includes all assets from UT2004.
> 4 votes

---
Tags: copyright, sound-effects
---


# Question
Title: Vertical Camera Movement in a 2D Platformer
I would like to ask about how vertical camera movement should be handled in a platformer in which the player changes his Y position frequently. For the past two days I've tried to adjust the camera movement and I haven't made any satisfying progress.

In principle, the camera's height should change as infrequently as possible, to avoid causing nausea. It also has to react quickly enough to the player's change in direction so he could see where he's going. An example of vertical camera movement done very, very well is in *Rayman: Origins* or *Rayman: Legends*.

How did you think vertical camera movement should be done in a platformer?

# Answer
Some games define rectangular area of the screen that the player can move about in without causing camera movement. Any movement outside of this area will cause the camera to move to compensate. This allows the player to make small movements (e.g. adjusting position on a block or jumping on an enemy) without shifting the camera. Shaun Inman has posted a great demonstration of this technique at mimeoverse.com.

Some other games have several camera states that can be invoked as needed. As an example Super Mario World has at least the following vertical camera movement modes:

* Follow along the bottom of the level (typical)
* Follow along the top of the level (invoked in some cave levels)
* Follow mario (flying, swimming, climbing)
* Snap to platform when landing (used in vertically oriented jumping levels)

A great explanation of this technique as a demonstrated by SMW is has been posted (also by Shaun) on youtube.

The transitions between these modes can add additional complexity. Of course when done right the player will be unaware that anything special is happening behind the scenes. However this complexity can cause problems as demonstrated at about 3:35 in the second video.
> 2 votes

# Answer
I call the way I do it the rule of the two thirds.

Basically the screen height is split in three, and level design is done accordingly to these part sizes. Player avatar is always in the middle part. When she jumps to a higher platform contained in the top third of the screen, the camera moves to center the player. When player reaches the lowest part the camera moves down to center on the avatar. The only exception is when the player has reached the bottom of the level. It's the only moment when the camera is not moved to put the avatar in the middle part.

As the levels have been thought and designed with this method in mind camera shakes are not numerous enough to disturb players.

Note that the method used is very relative to the kind of gameplay you propose as well as the design of your game. That said this method may not be the most interesting one for your game.

The other technique that can be combined twith this one is working on camera zoom to perform even more subtle transitions.

I hope it helps.

EDIT: also, as this method is based on third size of your screen, the camera movement can be smooth enough to be discrete.
> 0 votes

---
Tags: camera, movement, platformer
---


# Question
Title: What's the best way to build a game with kids?
I work at a *not-for-profit* organization and we've been thinking about building a game with the kids we help everyday.

We'd use their art, voice and ideas to power a simple enough PC game they can play and enjoy. The kids are *6-14 years old* and one of them knows simple programming (C, Pascal).

Can you guys recommend me something?

# Answer
Long story short you have several free options to let kids make games. My favorites are:

* Scratch: Everything is made using logic blocks. Perfect your young kids. They can do simple things easily.
* Algoid: Perfect for kids wanting to really "code". Easier than usual engine / langage. Adapted for teenagers.

---

First of all that's a great initiative.

I was invited, earlier this year, to do that kind of event with kids (groups of 10+ kids of 10 to 15 years old) by a museum. It was a very good experience and as a game developer I enjoyed it a lot.

We had a very short amount of time to do that event (3 sessions of 3 hours) I spent the half explaining them what is video game development and how it works behind the scene. It was very important to me to let them know the different jobs implied in video game making. Kids play video games everyday so it's good for them to know what's behind.

After that, we made a "game". They decided what kind of game it would be (it's important to guide them on that). They decided the rules. They produced the art assets (drawings on paper). They registered the music (done with their voices and recorded with a simple microphone). And I was in charge of the programming.

I did the programming part on Unity3D. It's an engine I know well so it was easy to me. However, on the way to making those games I discovered a lot of different way to let kids do the programming on their own.

The first software is scratch. It's based on logic blocks so it's pretty easy to understand even for young kids. They can import their sounds or images and do "limited" games.

Scratch is very impressive but it's "limited" for older kids. 15yrs old kids I worked with found it boring. So, if they really want to start programming there are some other "software" like Algoid. It's pretty nice, well documented, and allowed kids to do really nice things.

You can find more about my experience with kids (and one of the games) on this page.

I hope it helps.
> 1 votes

# Answer
One c++-based approach is a gaming library at:

It is designed for kids to write mini-games, with support for sprites and 3d objects.
> 0 votes

# Answer
One good suggestion is multi-user dungeons (MUD). They are text-based games that are open source (free), developed in multiple languages including C, C++, java, python and more. They are also online multiplayer games that pretty much gave birth to the whole massively multiplayer online games such as Ultima Online, Everquest, Dark Age of Camelot and of course, World of Warcraft.

> A MUD (/ˈmʌd/; originally Multi-User Dungeon, with later variants Multi-User Dimension and Multi-User Domain), is a multiplayer real-time virtual world, usually text-based. MUDs combine elements of role-playing games, hack and slash, player versus player, interactive fiction, and online chat. Players can read or view descriptions of rooms, objects, other players, non-player characters, and actions performed in the virtual world. Players typically interact with each other and the world by typing commands that resemble a natural language.

I've personally used MUD's to learn how to program, game design, manage an online game, manage an online community and test. This allowed me to transition into a video game job, where I worked in the video game industry for 8+ years working on specifically online games.

Although I ended up more on the marketing/publishing side of the industry, MUD's prepared me enough to both understand the core fundamentals behind a game, as well other aspects of that allowed me to hit the ground running and opened up a lot of doorways to other game engines at a very young age (15 to be exact).

You can install MUD's on pretty much any operating system these days, but it's recommended for Linux/Unix based stacks. You can download a free source of any type of MUD engine from the MUDBytes website. I highly recommend a Diku/ROM based MUD to start with that is programmed in C.

Remember, MUD's can be just as complex and robust as any high-quality AAA MMORPG in terms of game design. They just lack high-end graphics and sound. So, you can split your kids up into separate teams to represent separate departments on a game including game design, system design, QA and then start working on a game they can grow and play.
> 0 votes

---
Tags: game-design, html5
---


# Question
Title: Milkshape3D Animation on Windows 7 64-bit
when I run Milkshape 3D on my 64-bit Windows 7 machine, certain joints expand when I try to rotate them.

For example, my model's leg has hip, knee, foot and toe joints. So to do a walking animation I would rotate the hip joint, then rotate the knee joint. Then as soon as I start rotating the foot, the foot joint moves away from the knee rather than just rotating around the axis.

These images show what I'm talking about:

I've tried to run Milkshape in comaptibility mode and with the Mesa software OpenGL renderer, but it doesn't work. At the moment my workaround is to run Milkshape in a 32-bit Windows XP virtual machine.

Does anyone know what causes it and how to solve it?

# Answer
> 1 votes
From the images it looks like you're actually extending your shin bone by moving the ankle joint (the shin is abnormally long in the second image). Makes sure the joints are parented to each other and that when rotating, the joints rotate around their base, and not around a center much farther away (which would cause translation too). For example, ensure the Rotate command is rotating around the Center of Mass, and not the origin or a user specified point.

Work through whatever tutorial you're using again, to make sure you didn't miss a step. Or follow another tutorial.

---
Tags: animation, tools
---


# Question
Title: Real hardware acceleration of vector images?
Basically vector graphics have many advantages, especially that they scale very nicely. So there are many reasons to use them in 3D and 2D games. Is there any support for hardware accelerated vector graphics?

I know it's possible to parse SVGs and generate filled vertex buffers, but that has many disadvantages over e.g. parsing SVG into a small binary format and let the GPU handle it. Of course the GPU would need to support most non-trivial SVG objects like paths, gradients and patterns to be actually usable.

# Answer
> 3 votes
There is actually an NVidia extension to their cards that adds methods to the OpenGL API to deal directly with *Path Rendering*, AKA vector graphics: NV Path Rendering.

I don't know how usable that driver is or if it is still being shipped with the newest cards. The OpenGL extension is dated of 2011.

Another option that provides hardware support is OpenVG, which was supposed to be the go-to of vector graphics. But this framework also doesn't seem to be moving forward very fast.

---
Tags: graphics-programming, svg, hardware-acceleration
---


# Question
Title: What AI algorithm to use to find hidden shapes in a Battleships-like game
I'm developing a game similar to Battleships, only using different shapes. A single type of shape will be used within a game session, by both the human player and AI. There will be several objects spread out on the map (10x10 grid).

I want to find a way to guess the location and position of the human player's "ships" after I have one or more hits.

I'm aware that there will be a lot of randomness involved, but I want the AI to be smart enough to pose a challenge to the human player.

I'm thinking about having the AI "sweep" the map and evaluate each possible shape, somehow assign a probability to a certain position and maybe refine the guess by additional sweeps (thus a higher difficulty). But I need some ideas on what logic to use, I don't want to check every possible combination.

Thank you.

# Answer
This sounds similar to polyomino puzzle solving, which I've played with...

With a 10 x 10 grid, you can reasonably do an exhaustive search for each shape.

Starting from the top left, and going to the lower right, try to set the shape onto the grid. If it contradicts one of the known misses, discard it. If it overlaps some of the known hits, rank it as more likely.

Do this for each shape at each orientation.

Some cells might be members of several possible shapes, so that square could be considered even more likely.

By the end, you could have a ranking on each of the 10 x 10 cells.
> 1 votes

---
Tags: ai
---


# Question
Title: Weird GLM perspective problems with my 2D Game
I am trying to create the graphics system of a 2D game using OpenGL 3.3. To help me in this task I am using the GLM math libraries.

However I am having some trouble. When my objects (for now they are just squares) have a different scale, they "slide" through each other. I am posting some examples below.

In this picture both objects are at the center and camera is centered at the center

In this other picture the code has only moved the camera, but for some reason the big square moved down faster than the smaller one

Here are the matrices I am using to transform my camera

```
  // Projection matrix : 120° Field of View, display range : 0.1 unit <-> 10000000 units
  glm::mat4 Projection = glm::perspective(3.141516f/1.5f, (float)_WindowWidth / (float)_WindowHeight, 0.1f, 10000.0f);

  //glm::mat4 Projection = glm::ortho(0.0f, 16.0f, 12.0f, 0.0f,  0.1f, 100000000.0f);
  // Camera matrix
  glm::mat4 View       = glm::lookAt(
    glm::vec3(CameraPos.x, CameraPos.y ,2.0f), // Camera Position
    glm::vec3(CameraPos.x, CameraPos.y ,1.0f), // Where the camera looks
    glm::vec3(0,1,0)  // This is another way to say camera is not rotated
  );

```

And here are my matrices for my model transform

```
  glm::mat4 ViewProj = View * Projection;

  // Object to world matrix
  glm::mat4 Model      = glm::translate(glm::mat4(), glm::vec3(ElementToDraw.Position.x, ElementToDraw.Position.y, 1.0f)) *
      glm::rotate(glm::mat4(), ElementToDraw.Rotation, glm::vec3(0.0f, 0.0f, 1.0f)) *
      glm::scale(glm::mat4(), glm::vec3(ElementToDraw.Scale.x, ElementToDraw.Scale.y, 1.0f));

  glm::mat4 MVP = Model * ViewProj;

```

I really don't know why this happens. Am I using some matrix wrong?

Another thing, this only happens on the axis of the different scale. If both objects have the same scale they don't "slide"

Thank you in advance :)

**EDIT:**

I tried using glm::ortho with the following parameters:

```
 glm::mat4 Projection = glm::ortho(0.0f, 4.0f, 3.0f, 0.0f,  0.1f, 1000.0f);

```

**EDIT 2:**

I am passing the MVP using shaders

But the sliding continued and the objects werent centered at the center of the window

# Answer
I found the solution, I had to change this line:

```
glm::mat4 MVP = Model * ViewProj;

```

To this line

```
 glm::mat4 MVP =  ViewProj * Model;

```

I made some research and it seems that in DirectX its the other way around.
> 0 votes

# Answer
The problem is your World matrix multiplication order.

What you do is

**W** = **T** * **R** * **S**; where **W** is the world transform, **T** is translation, **R** is rotation, and **S** is scaling.

You should instead use:

**W** = **S** * **R** * **T**.

THis is because matrix multiplication **is not commutative**.

Hope that helps.
> 0 votes

---
Tags: opengl, 2d, graphics-programming, glm, pc
---


# Question
Title: Getting neighbors of hex tiles in 3D space
I have a hex tiled model like attached below. Each of the hex tiles are separate objects meaning I can access each of the hex tiles individually inside Unity

Now in my program I want to be able to get the 6 neighboring tiles of the selected tile. At first I thought I would get the 6 edges of the current tile and then check to see if any of the remaining tiles have those edges in common but that would be very expensive if I want to compute neighbors of all the tiles.

Any ideas??

# Answer
> 1 votes
As I can see the hex game objects have a mesh collider. So you can use SphereCastAll using your hex center position as origin and hex radius * 2 as radius to grab every neighbors colliders.

It's surely not the most elegant way to do it but it sure avoid headaches :)

# Answer
> 0 votes
you could keep references to them in a kind of an array like this so you'd get the neighbours just with indexing, like in a 2d grid: https://stackoverflow.com/questions/6661169/finding-adjacent-neighbors-on-a-hexagonal-grid and https://stackoverflow.com/questions/4585135/hexagonal-tiles-and-finding-their-adjacent-neighbourghs/15524441#15524441

---
Tags: unity, mathematics, hexagonal-grid
---


title: Saving Game Data In Windows Store App

text:
# Question
Title: Saving Game Data In Windows Store App
I am creating a windows store game using unity . I want to save the current high score data . I most probably use StreamReader / StreamWriter for saving data but when i build the executable for windows store app , the compiler is giving me a error that StreamReader class is not supported . Is there any alternate way for solving this problem ?

# Answer
> 3 votes
PlayerPrefs provides a key-value store implemented in a platform appropriate manner.

---
Tags: unity, windows, filesystem
---


# Question
Title: Unity3D: Change Background Image on a GUI Skin
So I'm testing with GUI Skins and trying to make something cool, and I want to change the background image of the application background. This is what I mean

In the screenshot above, the background is just blue, i'd like to change that to an image so it looks a lot better. Anyone know how to do this?

# Answer
> 1 votes
Are you using the new GUI system?

If so remember that this is within your scene view or is actually in the 3D rendering view. This means that whatever you put behind the canvas object (Z-Transform) is going to be rendered as the background (even 3D Objects).

You could easily also just pick a plane and rotate it 90 degrees to show a simple background with a texture/material.

If you want to learn more about how to utilise the menu system and its capabilities I would recommend you look into these tutorials by 3DBuzz

---
Tags: unity
---


# Question
Title: Can I use icons, which I am not allowed to use in commercial applications, in a free game
I wonder if I can use commercially-not-allowed icons in a mobile game which will be free for download. My game will include ads. Will ads make my game a commercial product?

# Answer
Disclaimer: IANAL! (I am not a laywer!)

A very strict definition of a commercial application is "an application made with the intent to earn money". Clearly adds are inserted into game to make money, so if the license on the icons disallows commercial use you cannot use them.
> 2 votes

---
Tags: legal
---


# Question
Title: Libgdx : point that scrolls on the edge of a circle
I'm not very familiar with libgdx vectors. I want to create my own joystick-controller and I want to know how can I find the coordinates of B by using Vectors. I can calculate the radius and I have the center.

Thank you.

# Answer
Imagine the radius is one. That means every point around the circle is exactly one unit away from the center. Now what kind of vectors always have a length of one? Unit vectors of course. You can get a unit vector by normalizing a non-unit vector.

Take the vector CA (center to A). Next, normalize CA to make it a unit vector, then scale it by the radius of your circle, to get vector CB. Finally, add CB to your center coordinates to get the coordinates of B.

```
B = Normalize(APos - CenterPos) * Radius
BPos = CenterPos + B

```
> 2 votes

---
Tags: java, mathematics, libgdx, vector
---


# Question
Title: How do I edit a Texture2D at run-time to visually indicate connected tiles?
I'm making a 2D sandbox game in C# and MonoGame, and I have a couple of tile sprites. These tile are loaded in-game as `Texture2D`s. I want to have blocks visually connect to adjacent blocks.

An example:

This is how a tile would look if it was connected to another tile to its *right side*:

Here's if *all of its sides* were connected:

If *none of its sides* were connected at all:

I think you see the idea. Starbound and Terraria do a similar thing.

I don't want to have like 10 different textures for each block for every combination of every side, as that needlessly takes up space.

What can I do in the code to edit my existing sprites to look like this? Am I just better off going with 10 different textures? Or maybe there's something better I've missed?

# Answer
> 2 votes
Depending on the texture, if you're changing the texture based on orthogonal connections, you'll only need 5 (if the texture can be rotated) or as many as 15.

The simplest solution is to create these textures manually. You'll have a much easier time getting the visuals right.

As for deciding which to use, see this question and answer: Choose tile based on adjacent tiles

---
Tags: c#, directx, sprites, monogame
---


# Question
Title: How do I use elapsed time as the player's score in Unity?
I'm making a "survival" game, where the goal is to stay on a rotating board as long as possible. I want to add a score system based on how many seconds passed. For example, if you stay on the board for 5 seconds, your score should be 5.

How can I do this in Unity using JavaScript?

# Answer
What you're looking for is the Time object. And `Time.time` in particular. `Time.time` contains the time in seconds since the game has started (or the level has been loaded).

So you want to know how many seconds elapsed since the player is on the board. Just save the `Time.time` value when you want to start counting and then, in the Update method, you can easily know how many seconds have elapsed.

```
function Start() {
  // for the example we start counting at Start
  _start_time = Time.time;
}

function Update() {
  // elapsed time is equal to the current Time.time
  // minus its value when we started to count
  var elapsed = Time.time - _start_time;
  Debug.Log( elapsed + "s have elapsed.");
}

```

I hope it helps.
> 2 votes

---
Tags: unity, javascript, scoring
---


# Question
Title: How do I maintain game balance while promoting interaction between dead and alive players?
How do you motivate players to be content with randomly selected roles that are often complex to play and differ drastically in playstyle (AND to stick around till the end of game)?

Some background: *Town of Salem* is a more diversified and polished version of the popular "party games" such as Mafia and Werewolf. There are about 30 roles with offensive/defensive/supportive/investigative specializations, assigned to players at random. Most of all, many roles have unconventional abilities that provide incentives for any player to stay engaged during each stage of a game session (i.e. early-game/initiative, mid-game, and end-game)

For example: **Medium** can chat with dead players. The catch is that the names of such dead players (*"out of play"*) are anonymous to Medium. In this sense, it provides a greater flexibility in player contribution overall with a strong emphasis on **mid and late-game** . Players are motivated to keep deducing and cooperating until the game is declared over (as opposed to sitting back once they are out of play) knowing that their intel can affect the outcome via Medium regardless of how early they were killed off.

I am also interested to see examples from multiplayer games in the same genre.

# Answer
Answering by just focusing on the question and not the other information.

**Identification**

I think the key to solving any problem is identifying what's causing the problem. If you're trying to find out how to motivate players more, then it may be critical to gather player feedback on what motivates and what doesn't motivate.

Unfortunately, I don't think anyone here can really identify those problems for you because we are not your players and likely not your target audience.

**Motivation**

Just speaking on motivation for anything regardless of your game specifically, there are a number of tactics you could take. One of my favorites is simply showing players firsthand how fun the game could be played in someone elses hands. Game publishers have been doing this for years through live demos, videos and more.

I think this may even be especially important in your case because players are playing randomly select roles that is foreign to them. Being foreign is bad in some game design (IMHO), then making it familiar could be a huge boost in motivation. Show them what they can do and they will likely start doing it more.

**Complex Systems**

Complex systems are really hard to make work and sell to the end user. This is because they are complex, which could lead to frustration, which could lead to players quitting the game. I know you are specifically not asking a question on complex systems, but this is likely a good reason on why players are not sticking around either.

However, that's a question that only your players could answer too. If true, ways to resolve complexity is similar to motivation. You have to bridge the gap between not knowing and knowing through various tactics such as video tutorials, in-game tutorials, web based resources such as game guides and the infamous game wiki.

**Sticky Players**

At the end of the day, there is no magic formula for making players sticky. If there was, we all have it and all be rich I think. Improving player retention is very much like everything else I've mentioned, only the players can help make it better. That's because they are the ones leaving the game and not sticking around. Finding out why is critical to improving that stickiness and there is no way for us to really answer that without actually experiencing the game as they did.

Hope that helps.
> 3 votes

# Answer
The main problem is see is the fact that only 2 roles have any method of influencing your death characters. I think you should strive to more interesting death character roles. Why not assign various roles to various ghosts to give them options? You could have a type of ghost with the power to see what other characters roles are, another that is able to discover the (living) identity of another ghost. A third one(poltergeist) might be able to prevent a living character from acting one every day. Having a number of these special roles means that the death characters can still interact with the game beyond just the medium.
> 2 votes

---
Tags: multiplayer, game-mechanics, balance, turn-based-strategy
---


# Question
Title: How do I serialise a mesh to a text file?
I'm building a game engine in OpenTK (OpenGL for C#). Is it ossible to take a terrain mesh (in any format) and convert it into a text file (or a really small character-filled file, no more than a few bytes). Then, afterwards, I'd take that file and generate the terrain from it.

The only reason I'm doing this is to save some memory on the computer. I think it would be more efficient if we had to quickly generate a crude terrain, and then smooth it instead of loading in a large mesh file.

Is this possible, and if so, how could I do it?

# Answer
I think the obj file format is what you need. OBJ is pretty commonly used in 3D graphics, and it's a text file. You will need to walk through your mesh properties and write your own file. Then you'll be able to load and display it.
> 5 votes

---
Tags: terrain, mesh, file, serialization, content-generation
---


# Question
Title: Converting time of day into a smooth day/night variable?
I'm trying to make a smooth day/night cycle for a game project that I've been working on. I've already set up a clock that adds deltaTime to seconds, wraps seconds to gameMinutes, etc. The issue that I'm having is that I want a signed normalized float to represent day (+1) and night (-1), and I'm not exactly sure what the most effective way of doing that is.

Here's my time class in pseudocode:

```
class GameTime {

    float snDayNight; //signed normalized

    float seconds;
    int gameMinutes;
    int gameHours;
    int gameDays;
    int gameMonths;

    //Omitted consts used for wrapping (SEC_PER_MIN, HR_PER_DAY, etc.)..

    //Per-frame update..
    public void Update(){
        seconds += Timer.GetDeltaTime();
        WrapTimeValues (); //Wraps sec to min, min to hr, etc.
        UpdateDayNightCycle ();
    }

    private void UpdateDayNightCycle(){
        //?????
    }

    //...//
}

```

So, my GameTime has been tested and seems to be working fine; when the value in seconds is \>= the value of SEC\_PER\_MIN it adds another minute and stores the leftover fraction of a second. It then goes on to check minutes, hours, days, etc.

**I've been a little bit stuck at UpdateDayNightCycle() though.** I want to be able to convert my time into a smooth decimal value where -1 represents absolute night and 1 represents absolute day. I've normalized values between 0~1 and -1~1 before, but I've never tried to use a normalized value to represent a repeating/periodic value like night~day before..

I tried drawing a simple graph where time of day is on the x-axis and daynight value is on the y-axis. What I get is essentially a *graph of a triangle wave*. Sadly my math skills are a little bit underdeveloped and even after looking into formulas for triangle waves, I've been having trouble implementing it in my code..

So, am I even on the right track? How can I smoothly convert my game world's time into a single decimal value between -1 and 1?

# Answer
> 10 votes
tl;dr

Func 1 on Wolfram Alpha:

`1 - 2 * |(x mod 2) - 1|`

Or in your specific case:

```
1 - 2 * |((time % entireDay) - halfDay) / halfDay|

```

---

You can even use a sinus wave instead (much more pretty).

`sin(x - pi/2)`

Sin Wave on Wolfram Alpha

Or in your specific case:

```
sin (- pi / 2 + 2 * pi * time / entireDay);

```

---

Long tedious explaination in fine detail:

If in military time: 00:00 (midnight) is -1, 12:00 (noon) is 1 and 23:59 is again ~-1 then we are measuring distance from noon (how long ago was noon or how long until it's noon again?). Then negating the value and subtracting one.

To measure distance in 1d we use the abs operator: `|7 - 5| = |3 - 5| = 2`(because seven and three are the save distance from 5.

```
float hours = gameHours + gameMinutes / 60.0 + seconds / 3600.0;//<time in hours with fracation>

distanceFromNoon = |hours - 12.0|; // Equals 12 at most (so we"ll divide by 6)

""normalized distance"" = distanceFromNoon / 6.0;

result = 1 - ""normalized distance"";

or

""normalized time"" = -2 * |hours - 12| + 1;

```

where `| |` means the absolute value of... This is normally accomplished with `Math.abs();`

So you get:

```
result = -2 * Math.abs(gameHours * 3600 + gameMinutes * 60 + seconds - 12 * 3600) / (3600) + 1;

```

---
Tags: mathematics, animation, lighting, timer
---


title: Lidgren peer to peer

text:
# Question
Title: Lidgren peer to peer
I am currently integrating Lidgren into my Unity game. I need to move away from the built in networking capability in Unity because of the style of game I am making, basically MMO, I will have far too much information routing through the server just to get from one peer to another.

With Lidgren I am hoping that the peers that need to send information to each other can connect and send messages while maintaining the server connection.

My question is that if I have say 2 people already connected to each other with NetPeer and a third connects to one of them, will all three automatically be connected to each other as peers, or do i have to connect the third to both other players manually?

# Answer
A `NetPeer` in Lidgren is like a "node" in the network (like a vertex). You only need one per machine (or per instance of your application).

A `NetConnection` is what you use to connect `NetPeer`s together over the network (like an edge).

Each `NetPeer` can have multiple `NetConnection`s.

You must form all of the connections between peers yourself. One peer must make make the connection and another must accept it. Creating a connection between one pair of peers does not create any other connections.

Lidgren has no built-in functionality for managing P2P *networks* (even though it can make P2P *connections*). You must write this functionality yourself.
> 0 votes

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


title: View Rigidbody 2D Wire Frame

text:
# Question
Title: View Rigidbody 2D Wire Frame
Simple question. When I prototype game ideas I like to create objects without having to attach sprites. Is it possible to create a Rigidbody 2D in unity, set its size and render its wire frame? I am using a unity in 2D mode.

Thanks!

# Answer
> 1 votes
To answer your question directly, it is possible to set the scene/game windows to enable gismos for your colliders but they will only be displayed when that gameobject (or a parent) is selected in the hierarchy.

This can be improved by attaching a script that implements `OnDrawGizmos()`, as an example here is an implementation that would visualize a BoxCollider2D:

```
using UnityEngine;

public class DisplayBoxCollider : MonoBehaviour {
    public Color LineColor = Color.green;
    private BoxCollider2D _boxCollider;
    private Transform _transform;

    public void Start () {
        _transform = GetComponent<Transform>();
        _boxCollider = GetComponent<BoxCollider2D>();
    }

    public void OnDrawGizmos() {
        if (_boxCollider) {
            DrawBox(_transform.position, _boxCollider.size, LineColor);
        }
    }

    private void DrawBox(Vector3 origin, Vector3 size, Color color) {
        Vector2 halfSize = size/2;

        float top = origin.y + halfSize.y;
        float bottom = origin.y - halfSize.y;
        float left = origin.x - halfSize.x;
        float right = origin.x + halfSize.x;

        Gizmos.color = color;
        Gizmos.DrawLine(new Vector3(left, top), new Vector3(right, top));
        Gizmos.DrawLine(new Vector3(right, top), new Vector3(right, bottom));
        Gizmos.DrawLine(new Vector3(right, bottom), new Vector3(left, bottom));
        Gizmos.DrawLine(new Vector3(left, bottom), new Vector3(left, top));
    }
}

```

However this approach leads to a fair bit of work if you require support for all of the collider types.

Instead I take the following approach:

* Use an image editor to create a set of small white png files. (e.g. 8x8, 8x16, 16x8 to cover a few basic senarios)
* Import these images into the unity project (Texture Type: Sprite, Sprite Mode: Single, Pixels to Units: 8)
* Attach a sprite to a GameObject, then customize the SpriteRenderer's Color to disambiguate between different types.

Using these placeholder sprites results in a minimalist representation of each object and the space it occupies, suitable for basic prototyping. By having a couple of sizes I can have sprites 1x1, 1x2, 2x1 units in size without having modify to the scale.

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


# Question
Title: How do I use the DirectX Extension-Library in Windows 8?
I need to use the extended DirectX-Library (D3DX...), but I am programming on Windows 8 (VS), so the DirectX 11-SDK is already included. However, it's included without the extension-library.

Do I have to download the June 2010 SDK? If so, how do I set up VS to work with the extended library?

# Answer
> 2 votes
The D3DX 11 library has been discontinued so if you want to use it you will have to download the 2010 SDK and install it. (If paths are not already set up, you will have to set the library and include paths for your project to the folder where the SDK installs (somewhere in Program Files (x86) IIRC).

However, if you want functionality similar to that of the D3DX library, try the DirectXTK which is designed a bit as a replacement to the D3DX library for D3D11 (with Windows Phone/Windows 8/Xbox One support)

# Answer
> 0 votes
All versions of D3DX are deprecated and not included with the Windows 8.x SDK. This is covered on MSDN and on my blog.

Ideally, you should change your program to not use D3DX. A full list of replacements for D3DX functionality can be found here. In summary: If you are on Direct3D 10, port to Direct3D 11. Then use the wide variety of Direct3D 11 support libraries instead of D3DX:

* DirectX Tool Kit on CodePlex provides replacements for the majority of runtime elements of D3DX such as loading textures, sprite, font, mesh, etc.
* DirectXTex on CodePlex replaces the texture content processing functionality in D3DX.
* DirectXMesh on CodePlex replaces the mesh content processing functionality in D3DX.
* If you are still using the DXUT library, you can use the latest version on CodePlex.
* If you are still using the Effects 11 library, the latest version is also on CodePlex.
* There are a number of samples from the legacy DirectX SDK on MSDN Code Gallery.

If given all that advice, you still need to use the legacy D3DX library, or if you are using XAudio 2.7 or XInput1.3 to support Windows 7 or earlier, then you can mix the use of the Windows 8.x SDK and the legacy DirectX SDK. However, the path order for doing this is reversed from previous recommendations for VS 2012 and VS 2013:

`(IncludePath);$(DXSDK_DIR)Include`

`$(LibraryPath);$(DXSDK_DIR)Lib\x86` or `$(LibraryPath);$(DXSDK_DIR)Lib\x64`

This is covered in detail on MSDN.

---
Tags: directx, directx11
---


# Question
Title: GLSL- How to change a certain color of a sprite, to another color passed into the shader?
There are sprites, with certain pixels being bright pink, and a shader dyes these pink or grayscale pixels to a custom color determined by the player. For example, a character looks normal except for his karate belt, which is dyed based on the level of the player (a variable outside the shader which changes the belt's color throughout the game).

I am looking to not have to use another texture as a mask, because that is a lot of extra work for all the animation frames of every character.

Something like this:

originalFaceColor --\> newFaceColor

originalShirtColor --\> newShirtColor

originalHairColor --\> newHairColor

I know how to do this in code to edit the texture and create a new one:

getPixel(); if(color) setPixel(newColor);

but would prefer to use a shader instead because all characters will share the exact same image, but I'd like each character to have unique colors.

# Answer
> 0 votes
You can use a simple shader for this, but I wouldn't do so, simply due to the fact that you're doing simple tinting with one color (or shades of one color) only. The Unity script above would work with some modifications, but you'll have to keep in mind that there's additional overhead/metadata in there that doesn't belong to the actual GLSL code.

What I'd do is split the texture based on tintable/non-tintable areas and then draw in two passes:

* One pass you'll render the un-tinted part of the texture.
* In another pass you'll render the tinted part of the texture utilizing `sf::Sprite::setColor()` to set the actual color.

While this might be less efficient than using a shader, you'll get far better compatibility out of this (e.g. SFML's mobile ports don't support shaders so far). In addition to that, you won't have to hardcode multiple color checks/values/swaps (which you actually won't anyway, since it's better done programmatically).

Personally, I've used this strategy in the past with the following texture:

It's a simple sprite sheet of a guy running to the right (four frames of animation).

While the first row includes the full sprites that will be tinted, the second row contains the non-tinted areas.

To draw one of those characters, I'm using two sprites. Sprite one uses the first row of the texture and `sf::Sprite::setColor()` to draw colored clothes. The second sprite is drawn on top without tinting to draw the hands and face using their original colors.

---

If you really want to do this in a shader, I'd avoid the branching `if ()` since that can slow down your code. Also it's quite tedious to update the code or work with multiple shades (which is a lot easier to be done with the tinting approach). So instead you could use a 1D texture 256 pixels wide. You'd just have to check a screen pixel's color and in case all three components are identical (or just red and cyan and green is 0), you'd use that value as the index in the 1D texture to get the replacement color.

---
Tags: c++, 2d, glsl, sfml, color
---


title: Quaternion Rotation Help

text:
# Question
Title: Quaternion Rotation Help
So I'm making a little engine with DirectX 11 and C++. (Some other help from other API's as well) DirectX has this function XMMatrixRotationQuaternion(XMVECTOR quaternion). I know nothing about this so excuse my cluelessness. I have a few questions about them that maybe someone could help me with.

* Do I use XMMatrixRotationQuaternion(XMVECTOR quaternion) and multiply the resultant Matrix with my scaling matrix and translation matrix to get my transformation matrix?
* How can I convert an angle (let's say in radians) to a quaternion. I've tried to look at this and what I got was something like this(I have a feeling this isn't anywhere close to correct)...
* Lastly, do I need to normalize that XMFLOAT3 axis?

```
static XMVECTOR XMConvertToQuaternion(XMFLOAT3 axis, float radian)
{
   return XMVectorSet(cos(radian/2), sin(radian/2)*cos(axis.x), sin(radian/2)*cos(axis.y), sin(radian/2)*cos(axis.z));
}

```

# Answer
> 1 votes
> Do I use XMMatrixRotationQuaternion(XMVECTOR quaternion) and multiply the resultant Matrix with my scaling matrix and translation matrix to get my transformation matrix?

I believe so. At least that's what I do with D3D9. (D3DXMatrixRotationQuaternion) You might already know but multiplication order should be : scalingMatrix * rotationMatrix * translationMatrix

For converting an angle to a quaternion, you can use:

XMQuaternionRotationAxis XMQuaternionRotationNormal (which, as its name suggests, requires the axis vector to be normalized.)

http://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx\_sdk.quaternion.xmquaternionrotationaxis(v=vs.85).aspx http://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx\_sdk.quaternion.xmquaternionrotationnormal(v=vs.85).aspx

# Answer
> 3 votes
I'd expect the conversion to be more like:

```
static XMVECTOR XMConvertToQuaternion(XMFLOAT3 axis, float radian)
{
   return XMVectorSet(sin(radian/2)*axis.x, sin(radian/2)*axis.y, sin(radian/2)*axis.z, cos(radian/2));
}

```

in particular there is no need to push the coordinates through a `cos` and the `w` should be the last coordinate, there is a micro optimization that stores the `sin(radian/2)` in a temporary variable but I expect an optimizer to be able to deal with it.

---
Tags: c++, 3d, directx, rotation, quaternion
---


# Question
Title: Algorithm to verify if a shape is inside another
I have a rectangular canvas and I need to verify whether a shape is totally inside that canvas or not. The shape can be lines, ellipses, arcs, rectangles and arbitrary polygons.

**Does anyone know a lib with this kind of algorithm, preferably in java?**

I searched and found just Slick2D, but it has a bug exactly on the method that verify if shape contains another shape.

Just to exemplifly, in the figure only shapes 2, 4, 5, and 7 are inside the canvas.

# Answer
I have good news and bad news for you:

The Bad News: I don't know or remember any Java library that does what you want

The Good News: It's really easy to implement this type of algorithm yourself! Here's a couple, you can mix them to optimize your collision detection depending on the type of shape.

---

## BB Collision Detection

You can imagine a box around your canvas. This algorithm is perfect if the two colliding shapes are rectangles. Now your two boxes have a x-pos, y-pos, width and a height, right? Let's say the x and y positions are the bottom-left point of your bounding box (BB). In pseudocode,

```
let x1, y1, w1, h1
let x2, y2, w2, h2

if (x1 + w1) - x2 >= 0 and (x2 + w2) - x1 >= 0
    shapesCollide()

```

---

## Bounding Sphere Collision Detection

This one's easy. If your two shapes are circles, you have two radii, r1 and r2. To detect the collision, you must calculate the distance between the shapes and substract to it the two radii. If this gives you a negative result, then your two shapes are colliding.

---

## SAT (Separating Axis Theorem)

This one is good if you have any shape that is convex. It works very well, albeit a little bit more complex to implement than the two others. Here's a very good tutorial about this algorithm: here

---

## Going Further

If you have concave shapes or want a more optimized algorithm (let's say you have more shapes than a thousand), well there's nothing a quick google search will not fix ;) You can also try to implement these on your own:

* Separate your concave shape into sub-shapes that are convex
* Make non-collision zones where you are sure that there won't be any collisions so you don't need to test for it
* etc.

Good luck!

**EDIT**: Just saw that I'm not answering your question directly... For your problem you could implement the SAT algorithm and detect if the shapes are not colliding with the inverse of your global canevas... anyways, sorry!
> 12 votes

# Answer
As already pointed out in the comments and answer: This can be arbitrarily complex.

Particularly, depending on the exact use case and performance requirements, you can employ some rather sophisticated data structures in order to make these tests fast. The bounding box test is the simplest one that should be done in any case (and in fact, could already be sufficient for many application cases). But beyond that, you could more tight-fitting bounding volumes like oriented bounding boxes, possibly in a hierarchy to accelerate the tests for complex shapes (see quad tree, KD Tree and related structures), or employ some sort of spatial hashing.

The "best" choice here also heavily depends on whether the objects are *animated* or *static*, or whether objects may be added or removed at runtime.

However, there is a very simple solution with plain Java. **Note** that this is comparatively inefficient, but it does an exact test for any possible `Shape`: You can define an `Area` that defines the region "outside of the screen" (assuming that the coordinates of the actual shapes are not unreasonably (infinitely) large). Then you can intersect the "outside" area with the area of the shape, and see whether the result is empty.

The code could roughly look like this:

```
Rectangle screenRectangle = ... // The screen/canvas rectangle
int s = Short.MAX_VALUE;
Area a = new Area(new Rectangle(-s, -s, s+s, s+s));
a.subtract(screenRectangle);

Shape toCheck = ... // The shape to check
Area b = new Area(toCheck);
b.intersect(a);
if (b.isEmpty()) {
    // The shape toCheck was completely contained in the screenRectangle
}

```

Again, this will not be very efficient when you have to check many (complex) shapes, but may still be an option here.

Additionally: A `Line2D` object would have to be treated differently, because it has no area at all. But fortunately, for a line, you can simply check whether both endpoints of the line are contained in the screen rectangle by calling `screenRectangle.contains(lineEndpoint);`.
> 4 votes

# Answer
If you know the canvas is a rectangle then this simplifies to the case of checking if the bounding rectangle of the shape being drawn is contained within the canvas' rectangle.

That's a fairly efficient check to run, and (generally) finding the bounding rectangle for your shape should be fairly easy (just finding the minimum and maximum x and y coordinates)

The test for an object being contained in the canvas is then:

```
(canvas.top > objectBounds.top && canvas.bottom < objectBounds.bottom &&
       canvas.left < objectBounds.left && canvas.right > objectBounds.right)

```
> 2 votes

# Answer
yeah, all solutions have already been made... i'll just add some more code (i'm rather from stackoverflow ^^)

* assuming you're using bounding box
* assuming you use plain java (java.awt)

.

```
List<Shape> shapeList = ...; //you know where you get them
Shape exampleShape = shapeList.get(0);
Rectangle2D boundingBox = exampleShape.getBounds2D();

```

see http://docs.oracle.com/javase/7/docs/api/java/awt/Shape.html#getBounds2D%28%29
and http://docs.oracle.com/javase/7/docs/api/java/awt/Rectangle.html

```
Rectangle yourRedRectangle = ... ;//you know where you get it

```

now you can simply check for two methods:

```
boolean isInside = yourRedRectangle.contains(boundingBox); //100% inside
boolean isIntersecting = yourRedRectangle.intersects(boundingBox); //partly inside

```

this can be applied for any `Shape`(http://docs.oracle.com/javase/7/docs/api/java/awt/Shape.html)

another more sophisticated approach would be to...

## ...use path iterator...

```
AffineTransform normalTrans = AffineTransform.getTranslateInstance(0,0);
PathIterator iter = shape.getPathIterator(normalTrans );

double[] point = new double[]{0,0};

do{
    //pick x/y from iterator
    iter.current(point);
    double x = point[0];
    double y = point[1];

    //checkif one point of iter is Inside
    boolean isInside = yourRedRectangle.contains(x,y);

    //step to the next point
    iter.next();

}(while( !iter.isDone() );

```
> 1 votes

---
Tags: java, 2d
---


# Question
Title: How do I save variables and load them in Unity with JavaScript?
I made a game and i want to save the high score and load it back. I need to save 3 variables and load them when the game starts. How do i do it?

# Answer
> 2 votes
Look at PlayerPrefs class. It's a key/value system that allows you to save, or read, a value.

---
Tags: unity, javascript, savegame
---


title: Save player data in Unity 3D

text:
# Question
Title: Save player data in Unity 3D
I've started to design a commercial Client/Server game in Unity and I need server-side saves players data for later analysis and web consultation (like battle.net). Is there a best practice to achieve this? Can I use MongoDb for a commercial game?

# Answer
> 1 votes
I will only answer to your first question (as I don't have a clue about MongoDB + commercial game).

Unity3D has a set of classes to communicate through HTTP. They are not perfect but they exists and (usually) work.

Have a look at WWW class, to set up a connection, and also at WWWForm to send requests and data to your server using HTTP.

Once your game will be able to read and write data via HTTP you will have to write the server side logic to save this data into your database.

Note that it's also possible to communicate through C# classes such as System.Net.WebClient, if you need to use commands not allowed by Unity `WWW`, such as `PUT`.

I hope it helps.

---
Tags: unity
---


# Question
Title: How can I combine chasing and obstacle-avoidance in a steering-based AI?
I'm developing a top-down game in XNA with enemies that wander until they are within range of a player, at which point they begin chasing the player. This works, but I also want them to avoid obstacles around the map while chasing.

I can find tutorials on programming the avoidance behavior, but I'm unsure as how to integrate that into my current AI so that the enemy both chases the players while also avoiding obstacles. I cannot use a pathfinding algorithm like A\* because my current AI is steering-based.

How should I go about integrating this?

# Answer
Since your AI is steering based it's pretty simple. You need to weigh your forces based on how important they are. The closer you get to obstacles the more important they should be, otherwise chasing should be the most important. There are a couple different ways to implement it, but I always found having some "max force" worked best where you iterate over your steering behaviors, calculate the force (which is scaled by a weight based on importance), and add the force to a total vector. Don't let the magnitude of the total vector exceed "max force". Ordering of behaviors & momentary importance decides how your AI behaves.
> 4 votes

# Answer
If you've been looking at steering behaviours you've probably seen this page which is by the guy who first came up with steering behaviours. If you want to know about the general background of how steering behaviours work that's the best place to start.

The steering behaviours were implemented by the same chap in a library called OpenSteer which was ported to C# and then fixed for XNA4 and finally I have forked the library for my own game.

**tl;dr**: You can find my XNA4 compatible library implementing all the Steering behaviours. I suggest you download the library and check out the Demo Application to see how to use behaviours. If you decide you want to use it, there's a nuget package available.
> 0 votes

---
Tags: xna, c#, ai, steering-behaviors, collision-avoidance
---


title: Position GUI Text in 2D game

text:
# Question
Title: Position GUI Text in 2D game
I am working on a 2D game, and my camera is a orthographic with a size of 320.

I want to display some text, but not with `OnGUI()`. Rather, with a `GUI Text` game object.

I couldn't help but notice that positioning my GUI Text object is a real pain: apparently, the onscreen coordinates where the text appears range from 0 to 1. That is, 0.5 is the center of the screen.

If I wanted to put my label at exactly `(100,50)` regardless of the screen size, I would have to calculate something like

```
(100f / Screen.width, 50f / Screen.height)

```

---

Is there a way to tell the GUI Text to appear at the actual transform position as it appears on the scene editor? Currently, if you move the GUI Text game object's transform slightly to the right, the rendered text will be displaced a LOT to the right instead...

# Answer
Camera.WorldToViewportPoint() can be used to map from world to viewpoint coordinates.

For static content the following line could be added to an `Awake()` method.

```
transform.position = Camera.main.WorldToViewportPoint(transform.position);

```

For dynamic content I add the GUIText or GUITexture to a child gameObject. Then on this child I attach a script with code like this:

```
public Vector3 WorldOffset = Vector3.up * 2.0f;
public Vector3 ScreenOffset = Vector3.zero;
new private Transform transform;
new private Camera camera;
private Transform target;

public void Awake() {
    transform = GetComponent<Transform>();
    target = transform.parent;
    camera = Camera.main;
}

public void LateUpdate() {
    transform.position = camera.WorldToViewportPoint(target.position + WorldOffset) + ScreenOffset;
}

```

This allows the parent object to move around in world coordinates as required, while the GUI appears to follow despite moving in viewport coordinates.
> 3 votes

# Answer
```
void OnGUI()
{
  float xScreen = 100f;
  float zScreen = 50f;
  GUI.Label(New Rect(Screen.width / 2 - xScreen / 2, Screen.height / 2 - zScreen / 2, xScreen, zScreen), "[&]");
}

```
> -1 votes

---
Tags: unity
---


# Question
Title: Problem loading level layout from file in Breakout clone
I'm working on a Breakout clone and I decide to use files as method to load level layouts. The file is something like this:

N,N,N,N,N

N,N,N

N,N,N

Only indicates what type of brick I'll instantiate, the initial positions to set this are in the WallBuilder.cs shown next. But I got a problem when I use my script, because the bricks doesn't appear in the rights position, they look moved and translated, and in the start moment, they move, but I don't understand why, I leave you a screenshot of the game when starts:

And the configuration of the prefabs of my brick:

Also, I leave you the WallBuilder.cs, which constructs the level based on the size of the screen and puts each brick next to each other:

```
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO;

public class WallBuilder : MonoBehaviour
{
    public float xOffset = 0.31f;
    public float yOffset = 0.15f;
    public GameObject level;
    private List<List<string>> filedata;
    private Dictionary<string, string> prefabMap;

    // Use this for initialization 24
    void Awake ()
    {
        readFile("./Assets/" + Application.loadedLevelName + ".lyt");
        initPrefabMap();
        placeBricks();
    }

    // Update is called once per frame
    void Update ()
    {

    }

    private void initPrefabMap()
    {
        prefabMap = new Dictionary<string, string>();
        prefabMap.Add("F","FastBallsBrick");
        prefabMap.Add("I", "InverseBrick");
        prefabMap.Add("M", "MultipleBallsBrick");
        prefabMap.Add("U", "NonDestroyableBrick");
        prefabMap.Add("N", "NormalBrickPrefab");
        prefabMap.Add("S", "SlowBallsBrick");
        prefabMap.Add("X", "XResBrickPrefab");
        prefabMap.Add("XX", "XXResBrickPrefab");
    }

    private void readFile(string filename)
    {
        TextAsset sr = Resources.Load("Level2") as TextAsset;
        filedata = sr.text.Split('\n').Select(s=>s.Split(',').ToList()).ToList();
    }

    private void placeBricks()
    {
        Camera mainCamera = tk2dCamera.Instance.ScreenCamera;

        float halfWidth = mainCamera.aspect * (mainCamera.orthographicSize/100);
        float tempYOffset = (mainCamera.orthographicSize/100) - yOffset - 0.5f;
        foreach (var data in filedata)
        {
            float tempXOffset = -halfWidth + xOffset;
            foreach (var item in data)
            {
                if (tempXOffset < halfWidth - xOffset)
                {
                    instantiateBrick(item,tempXOffset, tempYOffset);
                }
                else
                {
                    break;
                }
                tempXOffset += xOffset;
            }
            tempYOffset -= yOffset;
        }
    }

    private void instantiateBrick(string type,float xOffset,float yOffset)
    {
        string item = type.Trim ();
        if (prefabMap.ContainsKey (item)) {
            GameObject.Instantiate (Resources.Load (prefabMap [item]), new Vector3 (xOffset, yOffset, 0), Quaternion.identity);
        }
    }
}

```

Also, I leave you the collision exit method of the brick, just in case:

```
   void OnCollisionExit2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Player") {
            brick.addHits ();
            if (brick.getCurrentHits () == brick.getNeededHits ()) {

                Brick.ObjectBrick objectBrick = brick.getObject();

                if (objectBrick != Brick.ObjectBrick.NONE) {
                    String objectBrickStr = StringUtils.GetStringValue(objectBrick);
                    Instantiate(Resources.Load(objectBrickStr), gameObject.transform.position, gameObject.transform.rotation);
                }

                int totalPoints = brick.getPoints()*brick.getCurrentHits();

                GameObject gameObjectGM = GameObject.Find("GameManager");
                GameManager gameManager = (GameManager) gameObjectGM.GetComponent(typeof(GameManager));
                gameManager.addScore(totalPoints);
                gameManager.minusBrick();

                Destroy(gameObject);
            }
        }
    }

```

I have tried different things:

1. I harcoded the positions for the blocks, but after the Instantiate method in the WallBuilder.cs, they are set in other positions, maybe I'm wrong, but could be something about physics between the objects.
2. After that I removed the rigidbody2D of the prefab bricks, and they start to overlap each other no matter the offset I defined in the WallBuilder.cs. (I'll upload a screenshot of this later).
3. After those tests I notice that this problem doesn't occur when each row of my level has the exact amount of bricks, if I add one in any row, that problem occurs when I start the game.

I hope someone help me out.

Thank you

# Answer
Rigidbodies can be said to operate in two modes:

**Non-Kinematic** has physics driven movement, the physics engine will consider any forces brought to bear on the object to calculate and apply changes to velocity, rotation and position.

**Kinematic** lacks physics driven movement, the physics engine will not cause this object to move and any forces on the object will be disregarded. These objects can be moved through code by directly manipulating the Transform if required.

One important point to be mindful of is that the physics engine is optimized such that it will not detect collisions between two Kinematic Rigidbodies.

If your ball is a Non-Kinematic Rigidbody and you want the bricks to remain stationary then I recommend setting the bricks to Kinematic.
> 3 votes

# Answer
A few things catch my attention off the bat. First:

```
    filedata = sr.text.Split('\n').Select(s=>s.Split(',').ToList()).ToList();

```

Feels highly dubious to me. Are you sure this is doing what you expect it do be doing?
Second:

```
    float halfWidth = mainCamera.aspect * (mainCamera.orthographicSize/100);
    float tempYOffset = (mainCamera.orthographicSize/100) - yOffset - 0.5f;

```

Is just begging for integer division issues. I'd toss an 'f' on each of those 100s, just to be explicitly clear that you are indeed doing float division.
> 3 votes

---
Tags: 2d, unity, loading
---


# Question
Title: How to inplement a save-system for a complex nested list of character classs?
This is the situation I'm in:

I'm developing a game with C# using unity. In the game I have characters which is either locked or unlocked, and they're pretty much the same. For every character, they have their respective rank, level, type and race (provides additional effects), HP and MP as well as some stats, unique abilities with arbitrary effects to the game suited to them.

Then, the complication comes in as there's also a "Inventory" with predefined "Items", which every one of them holds arbitrary effects, can be either passive or active, as well as another set of rank and level for every item.

So, now I have to do planning. I want all the parameters for the characters to be in a single file (for obvious reasons), where the character class should read these file, retrieve the relevant part, and apply it to the character.

The game will be updated with new characters/items, or changed abilities/stats/effects. My saving system has to generate save data that persist from all versions too. (Say, a character is added. Then the old save should still load fine, with the new character initialized at locked and basic stats)

And I'm not sure what should be used to implement it with such a multi-layered nested structure, which still has to persist. My idea is to make the whole character structure a list with each character being the element, but then I can't see how to make a flexible system when there are apparently lists of lists of lists of lists, which is basically a mess to work with. I need some way to store the structure in a abstracted way that allows me to save all the parameters in all the nested stuff of a list of characters in a save file, and then also be able to read them (and fill those missing parts with initialized value).

# Answer
> 2 votes
When you have deeply nested types, you should use a data format which supports unlimited nesting of objects. Two possible alternatives are the simple JSON and the more complex XML. Both formats look different but work surprisingly similar. They are basically key/value maps where values can also be either primitive data types, other key/value maps or lists of values. This is really useful for backward-compatibility: When you come up with a new key and you don't find it in an old document, you can just assume a reasonable default value. As an additional bonus, both formats are easily human-readable and editable with a common text editor, which is really comfortable for testing and debugging.

When you have no problems deciding on one, you could have each class implement a `toJson` or `toXml` method which creates a node for that data format. This method not only serializes the object itself, it also calls the appropriate method of any sub-objects and embeds these as a sub-node in the node it returns.

Deserialization works by having each class also implement a constructor which builds the object from a JSON/XML node. This constructor would also call the constructors of its sub-objects passing the sub-nodes to it.

When you are not sure which data format you are going to use and want to keep your options open, you could alternatively use the Visitor pattern. In this pattern the serialization is done by a Visitor object. Each serializable object has a `visit(Visitor)` method. This method passes all information about the object to the visitor and then passes the visitor on to the visit-method of all its sub-objects. The visitor itself decides what to do with the information. So you can have different visitor classes which serialize the information in different formats.

A very simple example of a character with an inventory and an item in JSON:

```
{
     name:"Bob",
     level:10,
     class:"Fighter",
     inventory: {
          capacity: 1000,
          content: [
               {
                    name: "Axe",
                    type: "weapon",
                    attack: 10
               },
               {
                    name: "Healing Potion",
                    type: "potion",
                    amount: 5
               }
          ]
     }
}

```

This is how the same character could look in XML:

```
<character>
     <name>Bob</name>
     <level>10</level>
     <class>Fighter</class>
     <inventory capacity=1000>
         <item>
             <name>Axe</name>
             <type>weapon</type>
             <attack>10</attack>
         </item>
         <item>
             <name>Healing Potion</name>
             <type>potion</type>
             <amount>10</amount>
         </item>
     </inventory>
</character>

```

Which one you choose is subjective. Personally I prefer JSON over XML because I consider XML to be quite over-engineered for most use-cases (my examples show almost everything JSON has to offer but only scratch the surface of the features of XML), but that's just my opinion.

There are mature libraries available for either for most programming languages, so there is no need to fiddle around with string operations. The .NET framework has both an XML library and a JSON library.

# Answer
> 0 votes
Why not split it in lists by type? An item in inventory can be \[some data\] just as well as index(or handle) in array of all items. This index can be always generated from a pointer(and back) when saving, same applies to other non numeric attributes. When you got an array of POD(that is the goal) it is really easy to save it as binary.

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


# Question
Title: How can I create a character design that maintains a fixed rotation body, while allowing the body's "arm" to rotate 180 degrees?
I am attempting to create a 2d shooter in Farseer Physics on the Xbox360.

I have a player body which has a fixed rotation, as I do not want the body to rotate at all during gameplay. I am now looking to add an arm/weapon to the player's body, which should be able to rotate when the player moves the thumbstick on the controller.

This arm should have the following features:

* Does not react to gravity
* The position does not change by itself
* The only time the angle should change is when the player tells it to do so, and I should be able keep it at a fixed angle when the player decides to stop moving it.

Originally, I thought I could get this done using a fixture. Unfortunately, I don't see a way to rotate a fixture on a body after it has been added.

I assume the correct approach is to create a seperate body for the arm of the player, and attach them using a joint. I cannot for the life of me figure out which joint to use, and which characteristics to apply it. I feel like I have tried all of them, but I'm sure there are just a few variables that I am unfamiliar with that are giving me unwanted results.

# Answer
> 1 votes
conceptually, you would split off the main body sprite, and the rotating arm sprite. then you use the same transformations on the arm as you do on the main body. when you want the arm to rotate you set the arm sprite's origin point to the shoulder of the body sprite and rotate around that.

once your characters arm reaches an unrealistic angle, simply flip the character and have it run backwards.

---
Tags: box2d, farseer-physics-engine
---


title: Slick2d - state change problem

text:
# Question
Title: Slick2d - state change problem
In my slick-based game, I have 4 states - introState, gameState, pauseState and menuState.

From the gameState, I want player to go to **either menuState or pauseState**. To do that, I did this in gameState:-

```
public void changeState(GameContainer gc, StateBasedGame sbg)
{
    Input input = gc.getInput();
    if(input.isKeyPressed(Keyboard.KEY_ESCAPE))
    {
        sbg.enterState(2);
    }
    else if(input.isKeyPressed(Keyboard.KEY_SPACE))
    {
        sbg.enterState(3);
    }
}

```

To return from pauseState to gameState, I did this in pauseState:-

```
public void changeState(GameContainer gc, StateBasedGame sbg)
{
    Input input = gc.getInput();
    if(input.isKeyPressed(Keyboard.KEY_ESCAPE))
    {
        sbg.enterState(1);
    }
}

```

To return from menuState to gameState, I did this in menuState:-

```
public void changeState(GameContainer gc, StateBasedGame sbg)
{
    Input input = gc.getInput();
    if(input.isKeyPressed(Keyboard.KEY_SPACE))
    {
        sbg.enterState(1);
    }
}

```

As you can see, I want player to go to **either pauseState or menuState from the gameState** and not from pauseState to menuState or vice-versa.

Unfortunately, due to some unknown reason, when i press escape, it enters pauseState correctly but then if i press spacebar and then press enter, instead of going to gameState it goes to menuState. Any idea why is that happening?

# Answer
I found the solution myself:- *Before going to a different state, use the **input.clearKeyPressedRecord()** to clear all previously recorded key-Presses, or else even after changing a state, previously stored keyPress event will cause problems.*

So instead of doing this,

```
public void changeState(GameContainer gc, StateBasedGame sbg)
{
    Input input = gc.getInput();
    if(input.isKeyPressed(Keyboard.KEY_ESCAPE))
    {
        sbg.enterState(1);
    }
}

```

Do this:

```
public void changeState(GameContainer gc, StateBasedGame sbg)
{
    Input input = gc.getInput();
    if(input.isKeyPressed(Keyboard.KEY_ESCAPE))
    {
        input.clearKeyPressedRecord();
        sbg.enterState(1);
    }
}

```
> 3 votes

---
Tags: 2d, slick, game-state
---


# Question
Title: How do I pause a single bone with spine?
I'm using spine along with SFML. I have a character that is always animated. When he shots, I set an animation that affects only his arm. The arm goes up, but I need to stop this animation in the last frame while he keeps shooting.

I use this to make him walk

```
AnimationState_setAnimationByName(drawable->state, 0, "walk", true);

```

And this to make him shot

```
AnimationState_setAnimationByName(drawable->state, 1, "rshot", false);

```

I can't find a way in Spine c runtime to make this.

I could resolve this if I find a way to update manually tracks 0 and 1, instead of the full animation.

# Answer
> 1 votes
Finally I resolved this easily by editing the spine c runtime.

AnimationState.h

```
struct spTrackEntry {
    spAnimationState* const state;
    spTrackEntry() { stopAtEnd = false; };
    int/*bool*/ stopAtEnd;
    spTrackEntry* next;
    spTrackEntry* previous;
    spAnimation* animation;
    int/*bool*/loop;
    float delay, time, lastTime, endTime, timeScale;
    spAnimationStateListener listener;
    float mixTime, mixDuration, mix;

    void* rendererObject;
};

```

AnimationState.c

```
    /* End non-looping animation when it reaches its end time and there is no next entry. */
    if (!current->loop && current->lastTime >= current->endTime)
    {
        if (!current->stopAtEnd)
            spAnimationState_clearTrack(self, i);
    }

```

...

```
spTrackEntry* _spTrackEntry_create (spAnimationState* state) {
    spTrackEntry* self = NEW(spTrackEntry);
    CONST_CAST(spAnimationState*, self->state) = state;
    self->timeScale = 1;
    self->lastTime = -1;
    self->mix = 1;
    self->stopAtEnd = 0;
    return self;
}

```

---
Tags: sfml, spine
---


# Question
Title: What are the most common ways of closing an open world?
In many open world games, there are several ways to limit them. From original ones such as Desynchronisation(Assasins' Creed) to invisible walls.

What are the most common ways to close open worlds?

# Answer
### Infinite Water or Land

Of all the techniques I have encountered I find this the most appealing. It doesn't kill you, it gives sense of continuity and doesn't pull you away from the open world sense. Examples Far Cry 3. GTA V.

Others include:

* Killing the player using killer robots, monsters etc.
* Artificial Boundaries. You hit a boundary, used in older games.
* Natural Boundaries Mountains or valleys.
* Journey also used Wind, which throws the player down the mountain.
> 3 votes

---
Tags: maps, world-design
---


# Question
Title: What's the 'proper' way to get unit vectors?
My apologies if I've misunderstood the term 'unit vector' or misapplied it in concept, but I *think* that is the term for an object's heading when expressed as `[x, y]` when `x` and `y` are a value between -1 and 1; so if an object were moving 'south' on a computer screen, it would have a unit vector of

```
[0, 1]

```

...right?

Anyway, I've been using this concept to move my objects and rotate their images (when needed), but I think the math I'm using to determine the unit vector is... suboptimal.

```
def set_heading(self, goal):
    """Uses a 'goal' (x, y) to set the object's heading.
    Returns list of 0s and 1s for 'straight' headings.
    Diagonal headings are + and/or - math.sqrt(2)/2.
    """
    vals = [a - b for a, b in zip(goal, self.pos)]
    self.heading = [i / abs(i) if i != 0 else 0 for i in vals]
    if 0 not in self.heading:
        self.heading = [i * (sqrt(2)/2) for i in self.heading]

```

*(If you're not familiar with Python ternary syntax, the second line contains `i / abs(i) if i != 0 else 0` which is Python's way of saying `x if Condition else y` as opposed to the usual `Condition? x : else y` syntax in other languages. Basically I'm just trying to avoid dividing by zero!)*

So as you can see, this method of doing this sort of 'locks' the object into eight directions; if a 0 is not present in the heading, the method assumes that we're traveling diagonally and so multiplies the values by `sqrt(2) / 2` to ensure that the object doesn't travel faster than it should when moving diagonally. In this way I can move the object by simply adding the result of the unit vector times its speed to its current x and y coordinates.

```
def move(self):
    """Moves the object by changing self.pos."""
    self.pos = [a + (b * self.speed) for a, b in zip(self.pos, self.heading)]

```

I can't help but feel like the method for getting the unit vector (if that's what it's correctly called) is sophomoric. Especially since it is locked into eight directions - it's fine for the little project I'm working with currently, but I'm not sure of the right method for getting a more precise unit vector. What is the correct method for doing so - and is it more or less performant than the weirdness I have come up with independently?

# Answer
> 13 votes
A Unit Vector is of length 1.

A given vector can be converted to a unit vector by dividing it by it's magnitude. (With the exception of course that a zero length vector can not be converted).

Note that magnitude can be calculated using the Pythagorean theorem

For example if a vector has components: (`x, y, z`)

`magnitude = sqrt( x`<sup>`2`</sup>`+ y`<sup>`2`</sup>`+ z`<sup>`2`</sup>`)`

`unit vector = ( x / magnitude , y / magnitude, z / magnitude )`

---

Annan raises an interesting point that for vectors with a magnitude larger than `math.sqrt(sys.float_info.max)` (approximately 1.3e+154 on my machine) this will fail when using floats in the normal manner. In this case a workaround using longs to hold the working values and then finding the square root manually will be functional but relatively slow.

```
def isqrt(n):
    x = n
    y = (x + 1) // 2
    while y < x:
        x = y
        y = (x + n // x) // 2
    return x

def large_magnitude(x, y, z):
    long_magnitude_squared = pow(long(x), 2) + pow(long(y), 2) + pow(long(z), 2)
    return float(isqrt(long_magnitude_squared))

```

Credit for this implementation of Newton's Method goes to user448810.

---
Tags: vector, python
---


# Question
Title: Prefab disables its script when a clone is instantiated
A clone of a cube is spawned when it is destroyed, however the clones disable the script in the editor (example: http://gfycat.com/SnarlingScornfulEgg). Used the exact same script for a different kind of 'enemy' and it worked as intended.

Relevant part of script:

```
function Start () {
    health = 100;
}

function Update () {
    if(health <= 0){
        Dead();
    }
}

function OnCollisionEnter (col : Collision) {
    if(col.gameObject.tag == "Bullet"){
        health-=25;
    }
}

function Dead () {
    Destroy(gameObject);
    var posx = Random.Range(-50, 50);
    var posz = Random.Range(-50, 50);
    Instantiate(enemyl, Vector3(posx, 0.5, posz), transform.rotation);
}

```

Is there something I'm missing?

EDIT: The clone takes damage but doesn't die like the original when its health is \<= 0.

# Answer
> 1 votes
Looking at your video it appears that the cloned `EnemyL` object has an `EnemyL(Clone)` as the value for the variable `enemyl`.

I suggest ensuring that the `EnemyL` prefab has the `EnemyL` prefab as the value for its variable `enemyl`.

---

Thanks for posting image below. It appears that you have the prefab "linked to itself" and when cloned at runtime these clones are also "linked to themselves". As such any changes to state will propagate from one generation to the next.

In your case when you call `Destroy(gameObject)` and then `Instantiate(enemyl, ...)` both are referring to the same object. As you are cloning a partially destroyed GameObject the resulting clone has unexpected behavior.

Here is a discussion of this (self referential prefab) issue on the Unity forums. There are a couple of solutions and workarounds discussed.

Two of these options are:

1. Move the prefab into the resources folder, change the variable declaration and Awake() to something like this:

```
private var enemyl : Transform =  null;

function Awake() {
    if(enemyl == null) {
        enemyl = Resources.Load("EnemyL");
    }
}

```

This will create a link from the object in the scene to the prefab in the project. Now that it is not a self referential link, state will not propagate to later generations.
2. Alternatively the cloning functionality can be moved to a separate, stable, helper object and called upon when required.

---
Tags: unity, javascript
---


# Question
Title: How do I properly check if a particular OpenGL version is available?
I can't find any information on glCreateContextAttribsARB returning errors if a version is unsuported by the driver. So how do i check if it is? I don't want the program to hard crash because glCreateContextAttribsARB failed and i had no chance to check why it did.

Here's my code, i try to keep it minimalistic, the OpenGLVersion uses the glGetIntegerv to get the major and minor didgits and creates a number out of it. It checks if the version is 'least 3.3, though i've no idea if this actually does anything unless i set up glCreateContextAttribsARB with the wrong numbers.

So when does OpenGL "get a version", so that the glGetIntegerv returns a valid information? Is it something built in or does it return something valid only after i set up the context? How do i check if the OpenGL version i want to use is supported?

```
void CreateOpenGLContext(HWND hWnd){

    //Set the pixel format

    PIXELFORMATDESCRIPTOR pfd =
    {
        sizeof(PIXELFORMATDESCRIPTOR),
        1,
        PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
        PFD_TYPE_RGBA,
        32,
        0, 0, 0, 0, 0, 0,
        0,
        0,
        0,
        0, 0, 0, 0,
        24,
        8,
        0,
        PFD_MAIN_PLANE,
        0,
        0, 0, 0
    };

    hDC = GetDC( hWnd );
    GLuint PixelFormat = ChoosePixelFormat( hDC, &pfd );
    SetPixelFormat( hDC, PixelFormat, &pfd );

    //Create an OpenGL context to get access to the WGL extensions

    hRC = wglCreateContext( hDC );
    wglMakeCurrent( hDC, hRC );

    //Load functions

    if(glload::LoadFunctions() == glload::LS_LOAD_FAILED){
        MessageBox( NULL, TEXT("Failed to load OpenGL extensions."), TEXT("Error"), MB_OK | MB_ICONEXCLAMATION );
        PostQuitMessage(0);
    }

    //Load WGL extensions

    if(glload::LoadWinFunctions(hDC) == glload::LS_LOAD_FAILED){
        MessageBox( NULL, TEXT("Failed to load WGL extensions."), TEXT("Error"), MB_OK | MB_ICONEXCLAMATION );
        PostQuitMessage(0);
    }

    //Use WGL extensions to create an OpenGL 3.3 context

    const int contextAttributes[] =
    {
        WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
        WGL_CONTEXT_MINOR_VERSION_ARB, 3,
        WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
        0
    };

    HGLRC hRC3 = wglCreateContextAttribsARB( hDC, hRC, contextAttributes);

    wglMakeCurrent( hDC, hRC3 );
    wglDeleteContext( hRC );
    hRC = hRC3;

    //Check if the system supports OpenGL version 3.3

    if(OpenGLVersion() < 33){
        MessageBox( NULL, TEXT("Your system doesn't support OpenGL version 3.3"), TEXT("Error"), MB_OK | MB_ICONEXCLAMATION );
        PostQuitMessage(0);
    }
}

```

# Answer
> I'd like to know if the way i'm checking if the OpenGL version of choice (3.3) is availible.

Allow me to state this more clearly:

The *only way* to know if your OpenGL implementation supports a particular version is to attempt to create a context with that version and see if you get a valid context as a result. `wglCreateContextAttribsARB` will either return the version you requested (or a backwards-compatible higher version), or it will *fail*. And failure is the only way to know what is and is not supported.

---

> I can't find any information on glCreateContextAttribsARB returning errors if a version is unsuported by the driver.

Ahem:

> On failure wglCreateContextAttribsARB returns NULL. Extended error information can be obtained with GetLastError. Conditions that cause failure include:
>
> ...
>
> If the pixel format associated with does not support OpenGL contexts providing the requested API major and minor version, forward-compatible flag, and/or debug context flag, then `ERROR_INVALID_PIXEL_FORMAT` is generated.

So just check to see if you got an actual context. If you didn't, then it failed.

But really, there's not much point to having a check/fail/retry cycle. You wrote your code expecting some minimum version of OpenGL. That version is what you should ask for. If you happen to get a version higher than this version, great. But no matter what, you will get a version of OpenGL that is backwards compatible with what you asked for.
> 8 votes

# Answer
I like simple. If GLEW loaded correctly, this extension will be valid function pointer. Otherwise it will be null.

```
if(wglCreateContextAttribsARB)
    wglCreateContextAttribsARB(hDC, hRC, &attribs)

```
> 0 votes

---
Tags: c++, opengl, winapi, win32
---


# Question
Title: How to read a color of a pixel from texture (cocos2d-js)?
How to read a color of a pixel at \[x,y\] from a texture (in cocos2d-js)?

# Answer
I'm not finding any way to do this within the cocos2d framework, so if someone can do that it would probably be a better answer.

However, cc.Texture2D does have a getHtmlElementObj() function. Now, this function can return either an image element or a canvas element. If it returns an image, you need to make a canvas from it as shown in this answer:

```
var canvas = $('<canvas/>')[0];
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);

```

Once you have a canvas element, you should be able to get a pixel's color as described in this answer:

```
var data = canvas.getContext('2d').getImageData(x, y, 1, 1).data;
var color = new Color([data[0], data[1], data[2]]);

```

And just for good measure, here is how to test if `getHtmlElementObj()` returns an image:

```
function isImage(i) {
    return i instanceof HTMLImageElement;
}

```
> 3 votes

---
Tags: textures, sprites, cocos2d, ccsprite, cocos2d-x-js
---


title: Night cycle on a globe

text:
# Question
Title: Night cycle on a globe
I am working on a tile based game on a globe. I am trying to implement a simple day night cycle on my hex globe something similar to the image below

Here is the picture of my globe inside Unity

I am just using a few point lights but it doesn't look perfect. Would it be possible to do better with the current lighting system in Unity or do I have to just play around with different lights, intensity and their positions to make it look close to what I want. Also is there any way through a script that I can get information on if my gameobjects in the scene are being lit by a source of light. I would want this to get information on the tiles that are in the dark and the ones that are in the light

# Answer
Unity has three kinds of lights that work in real-time: Directional, point, and spot.

Point lights just sit somewhere and emit light in all directions, which sounds a lot like the sun, but you would have to put the light so far away from everything and make it so strong that it may be unreasonable.

Spot lights are the same, except they emit light in a cone instead of in all directions.

Directional lights, however, don't have a position. Well technically in Unity they probably do, but the position isn't used in the light calculations. The only factors are the direction and the strength of the light. This means the light effectively has a distance of infinity, but the brightness does not fall off.

**Of these three, the directional light is the most reasonable to simulate sunlight, even if it doesn't exactly sound right.**

For some pictures to further clarify things, here's Unity's page on the matter: http://docs.unity3d.com/Manual/class-Light.html
> 2 votes

---
Tags: unity, lighting
---


title: Stop animation playing automatically

text:
# Question
Title: Stop animation playing automatically
I've created an animation to animate a swinging mace.

To do this I select the mace object in the scene pane, open the animation pane, and key it at a certain position at 0:00.

I'm prompted to save this animation in my assets folder, which I do, as `maceswing`

I then rotate the mace, move the slider through time and key it in a different position. I move the slider through time again, move the object to the original position and key it.

There are now three things in my assets folder:

maceswing appears to be my animation, but I have no idea what Mace Mace 1 and Mace 2 are. (I've been mucking around trying to get this working so it's possible Mace 1 and Mace 2 are just duplicates of Mace. I still want to know what they are though)

When I play my game, the mace is constantly swinging, even though I didn't apply maceswing to it. I can't stop it. People say there's some kind of tick box to stop it constantly animating but I can't find it.

My mace object only has an `Animator` component:

Unticking this component doesn't stop the animation playing so I have no idea where the animation is coming from. Or what the `Animator` component actually does.

I don't want this animation constantly playing. I only want it to play once when someone clicks a certain button:

```
var Mace : Transform;
if(Input.GetButtonDown('Fire1')){
    Mace.animation.Play('maceswing');
};

```

Upon clicking the 'Fire1' button, I get this error:

> ```
> MissingComponentException: There is no 'Animation' attached to the "Mace" game object, but a script is trying to access it.
> You probably need to add a Animation to the game object "Mace". Or your script needs to check if the component is attached before using it.
>
> ```

There is no 'Animation' attached to the "Mace" game object, and yet I can see it swinging away constantly. Infact I can't stop it! So what's causing the animation if the game object doesn't have an 'Animation' attached to it?

**My maceswing animation object:**

# Answer
When you select a `maceswing` object you should see an Animation Import Settings in your Inspector. There should be an option called `Wrap Mode`, which selects a default animation mode:

* Default - I think it doesn't start the animation, until you do. It's probably what you need now.
* Once - Runs the animation once and sets it back to start.
* Loop - runs your animation as looped.
* Ping Pong - runs your animation as ping-ponged (start-\>end, then end-\>start).
* Clamp Forever - Runs your animation once, but it stays at the end.
> 1 votes

# Answer
To stop the mace from looping (and only swing once when the animation is played), in your last picture there's a checkbox called "Loop Time" (first checkbox). Unclick that.
> 0 votes

---
Tags: unity
---