# Question
Title: What's the technology that allows programming inside a game?
There are some games which allow the player to write/create scripts in-game, for example: Space engineers or Psi.

I want to use something similar to either one, but I've had a hard time finding information so my question is:

**Is there a branch of programming that covers the ability of a software once compiled to run new code created by the user?**

By branch of programming I mean something like PTG (Procedural Terrain Generation).

To avoid the *too broad of a question* or *opinion based*, let me clearly state that I'm not looking for guides or places to learn, I want the name or definition (if one exists) of the technology involved.

# Answer
Scripts written in **scripting / embedded / interpreted languages** such as "Lua", "Lisp" or "AngelScript" (more here) can be updated during the game **\[\*\]** and then are interpreted (= executed) on the fly.

You can bind elements from those scripts to your native compiled coding (C++, etc.) so that the scripts can then execute logic from your application. E. g. a specific command that the user can put in the script, as a result moves the in-game character by a given distance in the game world.

Some relevant linked questions:

---

**\[\*\]** *either by the user as part of the game play or also by devs for fast iteration/testing without restarting the application*
> 42 votes

# Answer
**Embedded language** is the proper technical term. In practice, languages which are used inside other applications (such as games) are often referred to as *scripting* or even *interpreted* languages, although they should not necessarily be interpreted or used for automating routine tasks. Googling "scripting languages for games" would probably yield more useful results than searching for "embedded languages".
> 12 votes

# Answer
You are looking for a way to change the code into some actions. This is precisely what **interpreters** are doing.

Take a look at Python. You run it, and bam! You land in **REPL**(**R**ead **E**val **P**rint **L**oop).

You define a function "hello" which prints "Hello, world". And there you have it!

Notice that you didn't compile anything; interpreter did some magic to create function on the fly (during the runtime) and now you are able to call it.

The same applies to games. Instead of having a REPL, you have a game with REPL module. The game probably starts the REPL and then runs everything else in this REPL, so you have access to the data and can actively modify it.

If you are working with huge languages like C++, they tend to be less dynamic and probably compiled. You want some easier. You either create your own language, or use some existing(like CoffeScript, Squirrel, Lua, Scheme, ...)

These are often called **scripting languages**, since you use them to write **scripts** that are built upon the game engine developed in some other language(e.g. C++).
> 10 votes

# Answer
There are two examples that I can think of off the top of my head. Both seem to do exactly what your asking for.

The first is screeps. https://screeps.com/ You can read alot about how it accomplishes this goal at http://support.screeps.com/hc/en-us/articles/205960931-Server-side-architecture-overview

The second is ComputerCraft http://www.computercraft.info/ They don't go into as much detail as to how it works but a little can be seen at their wiki http://www.computercraft.info/wiki/Main\_Page

In essence, the main game runs an interpreter in a separate thread, then allows that thread to manipulate the game world through API calls.

In both examples, while the language is nearly unlimited (only some calls blocked for security reasons) manipulations are limited by API calls that can be made.

Usually very little work is required to get something like this started. You need

* a thread manager that protects your game's loop (doesn't let a thread lock up the loop or consume to many resources). Both examples use a time based limiter.
* a interpreter to run a language. LUA is pretty common these days.
* a set of API calls that modify the game world. What fun is a programming language if you can't do anything with it.
* a resource management implementation. In other words a way to store code files and reference them in game.

There is no single branch of programming that handles all these concerns. But you will need a strong foundation in multi-threading, and a general knowledge of how an interpreter works.
> 2 votes

# Answer
If the in-game programming language was only designed for the purpose of the game, then it is a **domain specific language**.

The advantage (and disadvantage) of domain specific languages is that the language itself can limit what the user can do (i.e. you can disallow connecting to the internet). You could design a language that makes typical game tasks more easy than in a general purpose language. The disadvantage is that the user has to learn a new language.

Just running unsanitized user code in a **general purpose language** (like python or perl) from within your game, could allow the user to mess with things he shouldn't mess with. But it depends on your game. If you don't mind users doing stuff like opening new windows from within your game or whatever they like, you can use a general purpose language and expose bindings to certain features of your game world.
> 1 votes

# Answer
The compiled executable must contain a **parser** that is able to read external **program code**. The program code need not look like C or Python or xyz - it can be any kind of descriptive data that is suitable for the purpose in question. For example swedish, or morse.

The external program code needs to have a **syntax**, so that the parser understands it as it reads it character by character. The syntax may describe (and code may contain) **identifiers, numeric values, operators etc**.

The parser is **fixed** (compiled) but it works on flexible, external code.

The compiled executable must have an **internal API** to it's relevant functionality. so that the parser can perform actions. Most likely there must be (bi-directional) access to the executable's internal data as well, or the parser must provide some kind of data storage and housekeeping.

The parser can read the external program code at executable's **startup**, or it can read (parts of) it **ad hoc**, or it can **re-read** it per each frame (would be inefficient), or the code can even be **hand-typed** and posted to the parser as it gets ready (like: "move unit X forward 5 steps"\[enter\]).

Essentially, the external code is **not fixed** \- it can change any year, day or minute, but still the executable need not be re-compiled. Only the resulting behaviour, hosted by the executable, changes.

The text you are reading right now is (kind of, and even more if it was spoken) **interpreted** because you "execute" it in your brains while reading it, without knowing what next sentence says (or even if it possibly, sneakily changes right now). As opposed to Stack Overflow (pre)compiling the entire story into bytecode in your brains, which then executes it - and ofc then it could not change any longer.

The **phenomen ongoing** is interpretion. Scripting is only the act of creating a deSCRIPTion, or **writing**. All computer coding is imo scripting - we describe what we want to happen. The word "scripting" has got a somewhat tilted meaning, but so be fine. We know what we mean.

There is absolutely nothing extraordinary with interpreted languages, and **it is in no way a disputable term**. A multitude of them exist, and some of the very oldest ones are interpreted as opposed to compiled. In an interpreted language one might for example type by hand:

sock = Socket.New(AddressFamily.InterNetwork, SocketType.Stream ProtocolType.Tcp) \[ENTER\]

... and then go for a 30... no, 45 minute coffee break :-). When returning, "sock" exists and is ready for further use by typing more by hand, or letting the interpreter's automation continue with it.
> 0 votes

---
Tags: scripting, terminology
---


# Question
Title: Why doesn't my C#6 code compile in Unity?
Why can't Unity work with C# 6 code? It always gives me compiler errors. Here are some code examples:

```
using static System.Convert;
using static System.Environment;

$"€{punten}{NewLine}€{Money}{NewLine}€{KilledEnemies}{NewLine}€{bonus}{NewLine}€{total}";

```

I use Visual Studio as my code editor and build with no errors. If I press play in Unity it won't build.

# Answer
> 18 votes
Unity uses an old version of Mono runtime which is based on .NET3.5. It uses something between C# 3 and 4 in terms of features.

I found this by googling around. Not sure if it works but might be something worth investigating.

# Answer
> 6 votes
Unity Technologies have announced that Unity is upgrading to 4.6+. It is available through beta testing now.

# Answer
> 4 votes
This video on YouTube demonstrates how someone was able to get C# 6 syntax working on Unity by creating a new project, changing the target .Net Framework back to 3.5, setting the build and release output directories to the Unity project assets folder, and adding a reference to the UnityEngine dll. Debugging seems to function the same.

# Answer
> 2 votes
The compiler in Visual Studio has more features than the compiler in Unity which means that some code (especially newer c# features) will give an error in Unity, but not in Visual Studio.

You can however change your target framework to match the one that is closest to what Unity uses in your editor. I have done this in Xamarin when developing libraries for Unity, but it looks like it is possible in Visual Studio as well.

> In Visual Studio, in the DLL project's properties, set the Target framework property to the Unity framework version you're using. This is the Unity Base Class Library that matches the API compatibility that your project targets, such as the Unity full, micro, or web base class libraries. This prevents your DLL from calling framework methods that exist in other frameworks or compatibility levels, but which might not exist in the Unity framework version you're using.

https://msdn.microsoft.com/en-us/library/dn940020.aspx

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


# Question
Title: Find Initial Velocity for Parabolic Arc with Fixed Angle that Crosses Target Position
In my game I want skeletons to occasionally lob bones at the player. The player can be anywhere in relation to the skeleton (above or below, to the left or right), and I want the skeletons to throw a bone such that it lands on the player (or its parabolic arc intercepts them while rising, if the player is above the skeleton).

Given an arbitrary starting position, an arbitrary target point, and an arbitrary launch angle, how can I calculate the initial velocity of a ballistic projectile (assuming no air resistance) such that its parabolic trajectory intercepts the target point?

I know there are a number of similar questions on this site, but none of them appear to have this particular set of requirements:

Calculating initial velocities given trajectory parabola requires a known/fixed apex height.

Calculating velocity needed to hit target in parabolic arc and Throw object towards predefined place? assume a known/fixed travel time.

I want to have a fixed launch angle, initial position, and final position, and from those determine the initial velocity.

The Wikipedia article Trajectory of a projectile comes close, but I have no idea how to solve that for velocity.

**Reference**

In computer coordinates, the Y axis is inverted from Cartesian coordinates. The accepted formula operates independently of this, but it's unintuitive to deal with. This means that gravity will be a positive number, while being above the projectile will result in a negative displacement.

This also means that the fixed angle you choose will be the negative of what the habitual version would suggest.

As a final note, I adjusted for the absolute value of Vx by performing this manipulation before calculating Vy:

```
if sign(x_velocity) != sign(delta_vector.x):
    x_velocity = -1 * x_velocity
var y_velocity = x_velocity * tan(angle)

```

Full pseudocode reference:

```
static func get_velocity_of_arc_intercept(initial_position, target_position, angle):
    var delta_vector = target_position - initial_position
    var x_velocity = sqrt((gravity * delta_vector.x * delta_vector.x) / (2 * (delta_vector.y - (tan(angle) * delta_vector.x))))
    # Adjust for lost sign.
    if sign(x_velocity) != sign(delta_vector.x):
        x_velocity = -1 * x_velocity
    var y_velocity = x_velocity * tan(angle)
    return Vector2(x_velocity, y_velocity)

```

# Answer
First note that the initial velocity V at angle theta (from the horizontal, without loss of generality) has X and Y components Vx and Vy given by:

```
Vx = V cos(theta)
Vy = V sin(Theta)

```

Then by referencing the equations in my answer here, one readily obtains that at the time t of intersection:

```
Dy = Vy t  + g (t^2) / 2
Dx = Vx t

```

where Dx and Dy are the relative displacement of the target from the thrower.

Eliminating t in the first by substitution of the second gives

```
Dy = Vy (Dx/Vx) + g ( ((Dx/Vx) ^ 2) / 2

```

and then by rearranging

```
(Vx ^ 2) Dy = Vy Vx Dx + g (Dx ^ 2) / 2

```

But Vy == Vx tan(theta) from the problem statement, so

```
(Vx ^ 2) Dy = (Vx ^ 2) tan(theta) Dx + g (Dx ^ 2) / 2

```

or

```
(Vx ^ 2) (Dy - tan(theta) Dx) = g (Dx ^ 2) / 2

```

which finally becomes

```
Vx = sqrt( g (Dx ^ 2) / ( 2 (Dy - tan(theta) Dx) ) )

```

and then |**V**| = |Vx| / cos(theta)
> 1 votes

---
Tags: physics, projectile-physics, trajectory
---


# Question
Title: How to use Monogame Content Pipeline with XML
I have an XML file that I'm trying to import into my MonoGame project using the content pipeline. I'm having trouble getting the MonoGame Pipeline tool to convert the XML file into a .xnb file before I can even run the program.

The XML file is as follows:

```
<?xml version="1.0" encoding="utf-8"?>
<XnaContent>
  <Asset Type="GameObjects.ObjectInstruction">
    <FrameNames>
      <Item>Image_1</Item>
      <Item>Image_2</Item>
    </FrameNames>
    <FrameSpeed>10</FrameSpeed>
    <HorizontalOrigin>0.5</HorizontalOrigin>
    <VerticalOrigin>0.5</VerticalOrigin>
    <HorizontalScaling>1</HorizontalScaling>
    <VerticalScaling>1</VerticalScaling>
    <HorizontalOffset>0</HorizontalOffset>
    <VerticalOffset>0</VerticalOffset>
    <Subset Null="true" />
    <RotationRadians>0</RotationRadians>
    <Tint>
      <B>255</B>
      <G>255</G>
      <R>255</R>
      <A>255</A>
      <PackedValue>4294967295</PackedValue>
    </Tint>
  </Asset>
</XnaContent>

```

The GameObjects namespace is in a Visual Studio project that creates a .dll file, and I have another MonoGame project that references GameObjects and is the one in which I'm trying to do all the content stuff.

Inside the Pipeline tool I've got a reference set to the GameObjects.dll file. This file shows up in several places, and if I pick the wrong one the Pipeline tool fails with the error "Assembly is either corrupt or built using a different target platform than this process. Reference another target architecture (x86, x64, AnyCPU, etc.) of this assembly."

If I change the reference to the .dll file in the GameObjects project folder, the Pipeline tool still fails when trying to process my XML file. The error message looks like "System.Xml.XmlException: 'Element' is an invalid XmlNodeType. Line 19, position 8." This part of the XML file would be the G field of the Tint part of the ObjectInstruction object (Tint is a Color).

I've been knocking my head against this problem and getting nowhere. How do I use the Monogame Pipeline tool with XML files? How do I get it to recognize the definition of ObjectInstruction and process the XML file into a .xnb file? I'm pretty sure the rest of my program will run if I can solve this bit. Thanks for any help.

# Answer
Since `Tint` is a `Color`, you should try replacing the node with just

```
<Tint>FFFFFFFF</Tint>

```

MonoGame XML serializer understands this shorthand form.

There is a way you can use to create correct XML files for reference: see this blog post. Of course, you should reference the matching MonoGame DLL (located at `%ProgramFilesX86%\MSBuild\MonoGame\v3.0\Tools`).

The assembly reference error you mentioned is caused by the Pipeline being 64-bit only, so you need to use the x64 assembly.
> 0 votes

# Answer
Petri Laarne had the fix to the problem, but I thought I'd follow up with some lessons learned in case anyone else has a similar issue.

I generated the above XML file by writing a program to create a dummy version of my object and then export it using `IntermediateSerializer`. For whatever reason, the MonoGame version of this class output the `Color` struct in the form above, with all the fields broken out. (According to what I've read, this is consistent with `XMLSerializer`. I don't have enough insight into this topic to say why the output is what it is.) My problem stemmed from the fact that the XML importer was expecting a different format for the `Color` field than what I had in my test file.

According to this link, the `IntermediateSerializer` can read a `Color` struct with an 8-digit hexadecimal code. That article also had some notes on the `Rectangle` struct that was giving me similar problems in another XML file.

In summary, check that you're using the right XML format and linking the MonoGame Pipeline tool to the correct definition for the class you're trying to serialize.
> 0 votes

---
Tags: xna, monogame
---


title: Dynamic Shader Linkage in DirectX12?

text:
# Question
Title: Dynamic Shader Linkage in DirectX12?
Do the dynamic shader linking concepts introduced in DirectX11 ShaderModel 5.0 still work in DirectX12? In the documentation the reflection API is still available (e.g. `ID3D12LibraryReflection`), claiming it is provided especially for the shader linking technology, but I couldn't find other important interfaces like `ID3D11FunctionLinkingGraph` or `ID3D11ClassLinkage` in DX12.

# Answer
Yes. They are provided in the D3DCompile library: https://msdn.microsoft.com/en-us/library/windows/desktop/dd607342(v=vs.85).aspx
> 2 votes

---
Tags: shaders, directx, directx11, directx12
---


# Question
Title: JavaScript - Updating a canvas real-time... from server-side or client-side
I have this 2D tilemap game 13x13 viewport (169 tiles drawn on canvas at a time) of a 150x150 map. Each tile is 32x32px. Obviously I only update the 13x13 viewport...

I want to update a canvas in real-time as the world-map will be handled server-side. At least the logic... the drawning... should it be server-side or client-side?

Now, I am using Socket.IO for real-time data. Based on that current player's x and y, the canvas is drawn from where that person is on the map.

I can do this two ways:

1. (**Server-side**) Use node-canvas to draw the server-side via NodeJS and transmit back the new canvas. Is it possible? Because it seems I can only do it once via a PNG.
2. (**Client-side**) Transmit the 169 array of the new tileset (when player moves or action happens). Doing the logic server-side and draw it on the client-side from the array received from a callback.

Client-side problem: The problem here is that transmitting that large of an array does take seconds (2-3) so there is some lag.

Server-side problem: There is no continuous streaming of a canvas being drawn from the server that outputs to client... is there? Or am I not looking hard enough at node-canvas npm module.

I am not using any JavaScript game framework.

What are my best options here?

# Answer
> 3 votes
You should keep a copy of the map on both the client and the server. Send updates from the server that propagate to the client. But trying to send a chunk of the map every frame is a recipe for disaster. Drawing should be handled client side and logic handled mostly server side. You could certainly stream in data, but you should not do it once every frame, especially in a language such as javascript with little control over memory management. You could hypothetically stream video in real time (wouldn't be a simple thing to implement) but that is likely to look terrible, require a ton of bandwidth, and not work very smoothly (See OnLive).

---
Tags: 2d, javascript, tilemap, html-canvas, client-server
---


title: Resolution Independence in libGDX

text:
# Question
Title: Resolution Independence in libGDX
How do I make my libGDX game resolution/density independent? Is there a way to specify image sizes as "absolute" regardless of the underlying density?

I'm making a very simple kids game; just a bunch of sprites displayed on-screen, and some text for menus (options menu primarily). What I want to know is: how do I make my sprites/fonts resolution independent? (I have wrapped them in my own classes to make things easier.)

Since it's a simple kids game, I don't need to worry about the "playable area" of the game; I want to use as much of the screen space as possible.

What I'm doing right now, which seems super incorrect, is to simply create images suitable for large resolutions, and then scale down (or rarely, up) to fit the screen size. This seems to work okay (in the desktop version), even with linear mapping on my textures, but the smaller resolutions look ugly.

Also, this seems to fly in the face of Android's "device independent pixels" (DPs). Or maybe I'm missing something and libGDX already takes care of this somehow?

What's the best way to tackle this? I found this link; is this a good way of solving the problem?: http://www.dandeliongamestudio.com/2011/09/12/android-fragmentation-density-independent-pixel-dip/

It mentions how to control the images, but it doesn't mention how to specify font/image sizes regardless of density.

# Answer
Since you can read the device density and render fonts during runtime in libgdx, I use this solution to achieve a density independent font size:

```
float densityIndependentSize = origFontSize * Gdx.graphics.getDensity();
int fontSize = Math.round(densityIndependentSize );
BitmapFont font = generator.generateFont(fontSize );

```
> 12 votes

# Answer
To achieve this in libgdx, you can use the "orthographicCamera" there you asign the size that you wat to use, and in every resolution you may see all your images scaled to that size (i use the 800X480 because its the larger screen in Android) and it works good :)

```
public class GameStage extends Stage
{
     public GameStage(float width, float height, boolean stretch)
     {
          this.camera = new OrthographicCamera(800, 480);
          this.camera.position.set(800/2, 480/2, 0f);
     }
}

```
> 10 votes

# Answer
I believe Android's "device independent pixels" are just a measuring stick for classifying devices, and aren't actually available as renderable pixels. So you're not missing out on any magical DPI-solving infrastructure. As far as I understand the state of the art here, you have discovered all the options. There are two basic approaches for dealing with different devices:

1. Scale pre-existing images to match the actual device DPI.
2. Choose from a variety of pre-scaled images at run-time based on the DPI.

Of course, you can do some mix of the two (picking a roughly accurate image and then scaling it), or use different approaches for different elements of your UI (e.g., pre-existing images for fonts/text, and dynamic scaling for gameplay sprites).

What your specific game is trying to do can really make a difference in which approach makes more sense. For example, if you've got an on-screen menu you'll want to make sure the buttons are some reasonable multiple of a finger-tip size (so the button is always easy to hit, but isn't larger than necessary on big devices like tablets). Alternatively, if you're trying to build a puzzle game where you want to make sure the entire puzzle is visible at once, you'll need to scale the elements to fit on the screen (for example, with a tic-tac-toe game perhaps you'd like each element to use roughly 1/3 of the screen).

I think for things like fonts that have a lot of fine detail you'll want to have a variety of pre-rendered images with text, and then pick the best-matching. So buttons might change their relative shape/size from one device to another, but will generally always look nice.

Check out Mario Zerchner's Beginning Android Games for some discussion of the problems and some solutions. Note that Mario is the author of libGDX, so the book's approach mirrors the libGDX one (note they're not one-to-one, the book covers writing a library similar to libGDX, but not libGDX itself).
> 4 votes

# Answer
One way to do it is to define minimum aspect ratio and a maximum aspect ratio for your game. These will be the ratios that you want to support. Then you need to use a Viewport that is now provided in libGdx. The viewport will scale your world according to the settings you provide.

There are several types of viewports and you need to select the one that is most appropriate for your game.

You can use ExtendViewport for example and fix either your height or width and calculate the other. Then you need to make sure that all graphics can be seen in your minimum aspect ratio. The extend viewport will scale your graphics to the correct aspect ratio without distorting the graphics. However the ExtendViewport works by adding additional space to your world so you should also provide graphics for backgrounds for example that cover your whole extend of covered aspect ratios, when the world is smaller than your maximum aspect ratio the extra part of the graphics won't be shown.
> 1 votes

---
Tags: android, libgdx
---


# Question
Title: Calculating adjacent quads on a quad sphere
I've been experimenting with generating a quad sphere. This sphere subdivides into a quadtree structure. Eventually I'm going to be applying some simplex noise to the vertices of each face to create a terrain like surface.

To solve the issue of cracks I want to be able to apply a geomitmap technique of triangle fanning on the edges of each quad, but in order to know the subdivision level of the adjacent quads I need to identify which quads are adjacent to each other.

Does anyone know any approaches to computing and storing these adjacent quads for quick lookup?

Also It's important that I know which direction they are in so I can easily adjust the correct edge.

# Answer
> 2 votes
It's not a full answer, but it's too long for a comment...

From your question I presume you want to use a LOD system (geomipmap approach) and you're creating your mesh by cube subdivision, so why not to think about a LOD during both stages - mesh creation and rendering?

You start from just a 6 planes, so it's really easy to tell which sides are connected. Then, when you subdivide one of the planes you know which neighbors are at the all 4 edges. You can also store the newly created, internal edges.

This way you can create a hierarchical, tree-like data, where you start from 6 quads and every quad have 4 child quads. Having such data you can easily iterate over all LOD levels. You can even store the mesh data precomputed for all LOD levels, or you can create them on the fly, depending on camera move. There are really many possibilities here, but I can't help you more as I don't know what data are you going to need for your algorithm to work.

# Answer
> 1 votes
In their paper "Navigating through Triangle Meshes Implemented as Linear Quadtrees", Michael Lee and Hanan Samet propose a method of addressing the nodes (triangles) of a spherical quad-tree such that the "addresses" of neighbouring nodes (triangles) of equal size can be found in constant time.

The underlying principle they use is, that by assigning the two-bit sequences 00, 01, 10 and 11 to the upper, left, center and right subdivision of an up-facing triangle and to the lower, left, center and right subdivision of a down-facing triangle, the address of the right, left or vertical neighbour of any node (triangle) in the quad tree can be expressed by binary operations AND, OR, XOR, NOT and bit shift.

It seems the authors made a copy of their work freely available here: http://www.cs.umd.edu/~hjs/pubs/LeeTODS00.pdf

---
Tags: quadtree, sphere
---


# Question
Title: Difference between using Tags and GetComponent
I was implementing a basic "check if the player enter the trigger" behaviour and I get myself wondering about this question:

What the difference between this:

And this:

I guess it is a performance issue for using GetComponent every time? If not, I dont really see the point of using tags in this kind of checks.

# Answer
> 1 votes
There's only a few differences between the two:

* You can have more than one component (even a single type of component) per object but only one tag per object (unless you do special parsing or get an addon for it).
* If you have special functionality for a player, you might already have a need to add a `Player` component to it. Adding the tag might get redundant and and hard to manage.
* Tags provide the useful `GameObject.FindGameObjectsWithTag` and `GameObject.FindWithTag` which seem to be performant enough (as of 2006, lol)
* While there are performance differences, they are very negligible in terms of a game. A generic functional call versus a string comparison won't make much of a difference unless you're hitting it many times a frame.

I've personally never had a need for tags but everyone codes their games different. I can see uses for it but I usually build my own lists of certain objects which tend to better describe the group they belong to and I have better encapsulation over that group too.

# Answer
> 0 votes
I reccon the main difference is that with the latter, you restrict your trigger logic to your player implementation, so it's more of a design issue.

Consider that, one day, you wake up to a realization that your current player codebase can't handle some new issue and a refactor is in place. And then you see, well damn, all my triggers depend on this specific class to exist in this specific gameobject! Tread carefully, lest you break something.

Now, if you used tags, you could rename, remove, refactor to your heart's content, and things will (quite likely) just work.

My personal approach is to remove the object inspection logic away from triggers and whatnot. Triggers simply ask "Do you recognize this object that ran into me just now?", to which a third party inspects the object and says either "Yes" or "No". Depending on the answer, the trigger either ignores the event or proceeds to do whatever the trigger does.

(The third party in my case are ScriptableObject assets that I pass to the objects in the editor. An asset to identify the player, an asset to identify pickable objects, etc. This makes it easy to mish and mash functionality inside the editor, like turning a pick-up into a damaging entity, with no extra code involved)

---
Tags: unity, performance
---


# Question
Title: What is a "tick" in the context of game development?
Ok so this is a very beginner level question but I need to know this, what does the term "tick" refer to in the context of game development? Is it the same thing as FPS? Thanks!

# Answer
A tick is a unit of measure for time, specifically it is refers to a single instance of a repeated action (usually a broad action) in a game, or the period of time that action consumes.

Ticks are repeated and (mostly) regular; the term comes from one of the sounds a clock makes ("tick" and "tock").

Typically a tick is an iteration of some loop, such as the main game logic loop. One can say, for example, that the game logic "ticks" once a frame, or that "during the tick, the character positions are updated."

However it can also refer to more granular periods; one can say that "the AI tick in the game is limited to 5ms of processing time."

FPS is a measure of how many frames (usually render frames) a game processes in a second. Ticks and FPS are not necessarily related, however sometimes people will call a single execution of the game logic loop a "logic frame," in which case the (logic) FPS rate would be the number of ticks processed per second. This is particularly common for games that enforce fixed frame rates for game logic or physics for whatever reason.
> 24 votes

# Answer
Most games are implemented in a loop. Something like

```
def main
 setup(a, bunch, of, stuff)
 load(a, bunch, of, stuff)
 while true do {
   // <- A tick starts here
   read(a, bunch, of, inputs)
   call(a, bunch, of, stuff)
   do(a, bunch, of, stuff)
   update(a, bunch, of, stuff)
   // <- A tick ends here
 }
 clean(a, bunch, of, stuff)
 save(a, bunch, of, stuff)
end

```

It's a pretty standard way of doing things, and while rendering and UI elements may be handled in a separate thread, the actual game logic (press w move your ship forward), happens inside this tick.

This is also called a "frame" and is usually refereed to as a Frame rate (not to be confused with the graphics stuff). Tick has become a popular synonym to help differentiate the two.

As a programmer your goal is to have a constant, stable frame (tick) rate no matter what. This keeps the responses in your game smooth and rational, while at the same time allowing a model (programming not graphics) to process things in a computer friendly fashion. Tick times are not constant across games and there is no magic number. Some games are 100 Frames per second, others are 1 tick every 3 seconds.
> 5 votes

# Answer
A "tick" can refer to two different things. It could refer to a frame tick as you said were all the visible graphics on the screen gets updated. However, the term "tick" may also refer to a game loop tick. That type of tick is where your code get's executed. Usually your ticks is in a context of a loop of the same repeating ticks that will continue until the game stops.
> 1 votes

# Answer
A tick generally refers to one iteration of the game loop in which all the logic is computed, so games generally have multiple ticks per second.
However, many games run both the graphics and game loop on the same thread because the graphics usually don't take so long to display so that logic is interrupted, or vice-versa (although developers put checks in place for situations like that, like taking the difference in time between the last and current frame and adjusting the rate of movement accordingly).
**FPS** stands for **F**rames **P**er **S**econd, so for many games, yes, technically speaking, each frame is one tick.
> 1 votes

---
Tags: terminology
---


# Question
Title: How to prevent clients from stuttering while keeping the game in sync in multiplayer Pong?
I wrote Pong in multiplayer. The clients all run their own game, but I have an authoritative server which enforces its ball position onto the clients.

The game is in sync and playable, however, there is some stuttering on the client side even with a fast connection. I've read that clients could be configured in a way that shows a smooth experience to the player, while in fact the connection may be lagging.

I was thinking about not directly correcting the ball position when a server position update comes in, but to increase or decrease the ball's velocity based on the difference. I didn't manage to get this working properly yet.

Am I thinking in the right direction? How would I make a calculation that shows a smooth experience to the players, while keeping the game in sync?

# Answer
> 1 votes
Yoh have 2 method, a very simple one and a more complex

The first is to make the ball have a velocity, send that to the client, and use it to interpolate between server updates. This is the easier, and foe a pong game, it should be sufficient.

The second is way more complex and is used by multiple big companies, like Valve. You pretty much send an update from the server, wait for the next one and when it arrives, you start to interpolate between the 2 states. When the next update comes in you take the current state of the object and try to interpolate between it and the update from the server.

A very obvious drawback to this is that the client will always be 20-30 or even 10 ms behind the server, so you need to imllement a backward comouting algorithm for collision.

---
Tags: java, networking, multiplayer, synchronization, lag
---


# Question
Title: VS2013: Compiling Shaders with Shader Model 5.0
When I try to compile two HLSL files included in my project, the compilation fails with an error:

> Error error X4502: invalid vs\_2\_0 input semantic 'INSTANCE'

However, I notice it's trying to use shader model 2.0; when I'm trying to use 5.0:

Why is the shader compiler trying to use the 2.0 model when I've told VS to use 5.0? Or have I misunderstood?

# Answer
> 5 votes
Make sure you right click -\> properties on each shader file and set the Shader Type as well. The property right above the shader model in your graphic.

# Answer
> -1 votes
you should set (/fx) in shader type

---
Tags: shaders, hlsl, visual-studio
---


# Question
Title: Computing chance of winning when dealing with fuzzy numbers
Computing chance of winning in a **one player and one enemy battle** when using fixed numbers is quite easy; for example if we have these numbers:

> Player : Attack : 5 - Health : 30 - Attack Interval : 2s
> Enemy : Attack : 10 - Health : 20 - Attack Interval : 5s

When both player and enemy start battling together at the same time you can say for 100% the player will win this battle because it takes the player 8 seconds to kill enemy but enemy needs 15 seconds to win, so it is certain the player would win this battle.

Now considering using not fixed numbers (Attack and Attack Interval are fuzzy), for example for these numbers:

> Player : Attack : (5\>10)10% - Health : 30 - Attack Interval : (2s\>5s)50%
> Enemy : Attack : (10\>15)20% - Health : 20 - Attack Interval : (5s\>7s)10%

**Note:** (5\>10)10% means for 90% of times when a player attacks it would have 5 hit points and for 10% of times it randomly can be from 5 to 10 point.

**Note:** (2s\>5s)50% means for 50% of times player attack interval is 2s and for 50% of times it randomly can be from 2 to 5 second.

Now this changes choosing the winner for some numbers; either the player or the enemy can win the battle. How can we compute the chance of winning? For example, concluding that the player has 34% of winning in this battle, etc.

---

**UPDATE** : I'm creating probability tree for player and enemy for my example with a little change in numbers to get rounded numbers. example is this :

> Player : Attack : (5\>10)10% - Health : 30 - Attack Interval : (2s\>5s)70%
> Enemy : Attack : (10\>15)20% - Health : 20 - Attack Interval : (5s\>7s)10%

now i achieve two `probablity/winTimeNeeded` chart like these :

Now how can i get player overall win probability with these chart and numbers?

---

**Update** : with @realUser404 solution i can say player have exactly `82.0028%` of winning in this example (if player and enemy have exactly the same time we consider this a lost.)
still if some one have better solution I'll be happy hear about it I'll wait til the end of bounty.

# Answer
If you do not wish to compute all the solutions, maybe the following can get you a good approximation :

Choose fixed stats for the Enemy : `Enemy : Attack : 10 - Health : 20 - Attack Interval : 5s` for example. This gives you the time the enemy needs to kill you.

With that information, it is pretty easy to get the probability that you kill him first, with your fuzzy stats.

You can then calculate the same for different values of the enemy's stats, and then ponderate according to the probabilities you defined for your enemy --\> This will give you your **final probability of winning**.

It is only an approximation, but it can be a pretty good one depending on how you do the settings, and can improve the performances by a lot.

**With your Edits :**

Okay, so now with your edit it became pretty simple to calculate the player's winning probability : Just calculate the probability of winning if you do 4 secs, then 6 secs, then 8... up to 20s. Then ponderate by the probability of doing yourself that time, and add everything up.

A few examples : if you kill your opponent in 6 seconds, you have 100% chances of winning. So you can add to your total probability 4.40 * 100% = 4.40%. As your opponent cannot kill you before 10 seconds, you already know you have **at least** a 1.40 + 4.40 + 64.60 +0.60 +0.20 = 71.20% chances of killing him.

For 12 seconds, you have 96.20% chances of killing your opponent (100 - 3.60 - 0.20), so you can add to the total probability 96.20 * 9.80% (percentage of chances to kill the opponent in 12 seconds).

Do This for all the times, add everything, and you should get something around 85% in your example.
> 2 votes

# Answer
Run a batch of randomized simulations (aka Monte Carlo experiments) & collect the desired statistics. This technique is especially useful if you have hard to quantize combat factors, such as freeze effects, to randomized hit modifiers, variable chance to crit, etc. It's also a nice way to capture other info like the quickest victory, least damaging, most damaging, etc. I've seen this approach used in Brogue for instance.

In terms of draw backs, this technique general requires loosely coupled game logic &/or games with easily restored logical state. It is not good for situations where your combat is tightly coupled to your graphics / animations.

I usually automate the process of finding a good # of trials for this sort of thing. This let's me experiment with a potentially wide variety of different combat mechanics & I can easily adjust my estimate finder without doing a bunch of testing by hand.
> 6 votes

# Answer
This is written in `python 2.7.11` if you want to test it out for yourself before you start working it out in the language you're using if you decide to use it. There are no special requirements, just make sure to use python 2.7 and remember to import math.

I started by getting the range of time that each individual has the opportunity defeat the other. The starting value represents the soonest possible time that one person can possibly defeat the other and the end value represents the latest. Each value rounds up, accounting for a user not taking a "non-integer" amount of turns since we don't need to deal the exact damage required to defeat their opponent.

This range is important because we want to figure out how long one person has until the other has a chance of defeating them. We then calculate the odds of that person defeating the other during this time. For the remainder of this post, I will refer this person (the person who has the opportunity to defeat the other first) as `Sub_A` and the other `Sub_B`. Just so I don't have to describe it every time :)

example: there is a 40% chance that the player(Sub\_A) will defeat the enemy(Sub\_B) before the enemy has a chance of defeating the player. That leaves a 60% chance of both users having an opportunity to defeat one another afterward.

The rest of the equation is acquiring the odds of the player defeating the enemy during the remaining time using their approximate damage per second. This is then multiplied by the odds of Sub\_A NOT DEFEATING Sub\_B and added to the odds of Sub\_A DEFEATING Sub\_B.

continued example: There is a 20% chance of the enemy(Sub\_B) defeating the player(Sub\_A) and a 60% chance of the player defeating the enemy. We then divide each percentage by the sum of both ( 20 / (60 + 20) and 60 / (60 + 20) ). This gives us 25% and 75% for a total of 100%. There is a 100% chance that one of them will defeat the other during this time. Those values are then multiplied by the 60% from earlier to get 15% and 45%. We then know that the player has approximately a (40 + 45) = 85% chance of defeating their enemy.

Hopefully this does the job! I tried to put in some helpful comments, but ultimately it just takes a some figuring out. Please let me know if I made any mistakes or if anyone has any improvements/changes. I would love to know!

```
def main():
    import math

def lerp(mn, mx, amt):
    # calculate the value between min and max at a certain percentage
    return mn + (mx - mn) * amt

def average_amt(mn, mx, odds):
    # takes the average random value between (min amount) and the (average of the range between min and max)
    # this takes into account the odds of getting the min amount
    return lerp(mn, lerp(mn, mx, .5), odds)

class Fighter:
    def __init__(self, min_dmg, max_dmg, dmg_chance, hp, min_time, max_time, time_chance):
        self.min_dmg = min_dmg
        self.max_dmg = max_dmg
        self.dmg_chance = dmg_chance
        self.hp = hp
        self.min_time = min_time
        self.max_time = max_time
        self.time_chance = time_chance

    def time_range(self, dmg):
        # returns the range of time needed to deal a certain amount of damage
        # value is based on how many turns it will take
        # example: if it takes 4.2 turns to deal the requires amount of damage, it will round up to 5
        mini = math.ceil(dmg / self.max_dmg) * self.min_time
        maxi = math.ceil(dmg / self.min_dmg) * self.max_time
        return mini, maxi

    def get_dps(self):
        # returns the average amount of damage dealt per second
        ave_dmg = average_amt(self.min_dmg, self.max_dmg, self.dmg_chance)
        ave_time = average_amt(self.min_time, self.max_time, self.time_chance)
        return ave_dmg / ave_time

    def approx_percent(self, time, dmg):
        # returns an approximate percent chance of winning at any given time based on average damage per second
        time_range = self.time_range(dmg)
        if time <= time_range[0]:
            # it is not technically possible to win at this point in time,
            # but would still return a value if not explicitly told not to
            return 0
        else:
            return self.get_dps() * time / dmg

    def odds(self, enemy):
        # returns the odds of winning a battle against an enemy
        my_range = self.time_range(enemy.hp)
        enemy_range = enemy.time_range(self.hp)

        if my_range[0] > enemy_range[1]:

            # enemy will win before the player has a chance to
            return 0

        elif my_range[1] < enemy_range[0]:

            # player will win before the enemy will have a chance to
            return 1

        else:
            overlap_start = max(my_range[0], enemy_range[0])
            overlap_end = min(my_range[1], enemy_range[1])
            if my_range[0] < enemy_range[0]:
                # the player has an earlier possibility of defeating the enemy

                # win_odds are the odds of the player defeating the player before the enemy has a chance
                win_odds = self.approx_percent(overlap_start, enemy.hp) / 2

                # enemy/player odds are the odds of the enemy and player winning while the possibilities overlap
                player_odds = self.approx_percent(overlap_end, enemy.hp) / 2 - win_odds
                enemy_odds = enemy.approx_percent(overlap_end, self.hp) / 2

                # return the total odds in relation to the player
                return win_odds + player_odds / (player_odds + enemy_odds) * (1 - win_odds)
            else:
                # the enemy has an earlier possibility of defeating the player

                # win_odds are the average odds of the enemy defeating the player before the player has a chance
                win_odds = enemy.approx_percent(overlap_start, self.hp) / 2

                # enemy/player odds are the odds of the enemy and player winning while the possibilities overlap
                enemy_odds = (enemy.approx_percent(overlap_end, enemy.hp) - win_odds) / 2
                player_odds = self.approx_percent(overlap_end, enemy.hp) / 2

                # return the total odds in relation to the player
                return player_odds / (enemy_odds + player_odds) * (1 - win_odds)

# Player : Attack : (5>10)10% - Health : 30 - Attack Interval : (2s>5s)50%
#  Enemy : Attack : (10>15)20% - Health : 20 - Attack Interval : (5s>7s)10%

# this is the equivalent to your example in code
PLAYER = Fighter(5.0, 10.0, .10, 30.0, 2.0, 5.0, .50)
ENEMY = Fighter(10.0, 15.0, .20, 20.0, 5.0, 7.0, .10)

odds = PLAYER.odds(ENEMY)
print '{}%'.format(odds * 100)

# 69.1689008043%

PLAYER = Fighter(10.0, 15.0, .2, 20.0, 5.0, 7.0, .1)
ENEMY = Fighter(10.0, 15.0, .2, 20.0, 5.0, 7.0, .1)

odds = PLAYER.odds(ENEMY)
print '{}%'.format(odds * 100)

# 50.0%

main()

```
> 3 votes

# Answer
With discrete random events like your example, the easiest method to understand would be the probability tree. Map out all the possible outcomes in a tree, note the probabilities of each outcome "branch", and sum the probabilities in the end.

Since there could be many attacks before the first player/enemy dies, this tree could have many levels of branches, so you may need to write a short program to perform the calculation.
> 2 votes

# Answer
This problem looks small enough that you could just do a brute force exhaustion over all possible random choices, as described in this answer.

---

The biggest optimization you can probably do here is to study the two actors independently. i.e. for the player, you tabulate the probability distribution on the amount of time it takes to deal 20 damage, and for the enemy you tabulate the probability distribution on the amount of time it takes to do 30 damage.

Then using those tables, you can then compute the probabilities of the player doing 30 damage before, at the same time as, or after the enemy.

You can even do that last calculation in time linear in the table size with the right algorithm.

---

You can also optimize the exhaustion over all random choices.

Rather than iterate through the possible states — e.g. pairs consisting of "the time the actor can attack next" and "damage previously done done" — you can iterate through them in a topological ordering (e.g. increasing time). Using a hash table, you can detect when a game state is duplicated, and merge the probabilities of arriving at that state, so as to avoid duplicating work.

Approaches like this are *surprisingly* effective if you've never seen them before; they can very quickly do exhaustive calculations that you might have thought completely infeasible if you've never seen things like them before.

---

Also, claim that analyzing the two actors separately is actually an optimization an educated guess — depending on the sorts of actual problems you have, it may actually be better to do the exhaust over all of the possible states of actual combat.
> 2 votes

# Answer
**Intro**
I'm going to specifically answer how to use the probability tree to get win/loss ratios.

For starters, your math becomes very ridiculous to hand-design a flowchart. I didn't even finish the first player attack and got this:

**Simplify**
So, let's change your numbers a bit so the drawing gets done today. Now, both player and npc have 15 health, player has a 50% crit chance, npc has a 25% crit chance, both player and npc do 5 damage, and all crits do double damage. Also, they each attack once per turn regardless, and I'll assume the player wins a tie (i.e., both player and enemy would hit 0 health or less on the same round).

This means that each round there are 4 possible outcomes for damage. PHit/EHit, PHit/ECrit, PCrit/ECrit, PCrit/EHit, with probabilities of 50% x 75% = 37.5%, 50% x 25% = 12.5%, 50% x 25% = 12.5%, 50% x 75% = 37.5%.

Now we get this:

In each box, the first number represents the probability of that box occurring if the preceding box happened. Then PxD gives the player's damage, ExD is the enemy's damage, PxH is the player's remaining health, and ExH is the enemy's remaining health. The final percentage is the cumulative chance of getting to that box, calculated by multiplying each conditional chance in the chain (and rounded a bit, so the final totals won't be exactly 100%). Orange text means the player killed the enemy, red text means the enemy killed the player.

**Specific Numbers**
For a specific example, let's take the left-most branch each turn. 37.5% of the time, both player and npc roll normal hits, doing 5 damage each, leaving them at 10 health. After that happens, there's a 37.5% chance they each roll normal hits again, doing another 5 damage each, leaving them at 5 health. Finally, there's another 37.5% chance they each roll normal hits a third time, doing a final 5 damage and killing each other. Since we said the player wins a tie, this counts as a win for the player. The total probability of the fight ending this specific way is 37.5% x 37.5% x 37.5% = 5.2734375% ≈ 5.3%.

**Results**
So the player loses on the second round 11% of the time, wins on the second round 74% of the time, and wins on the third round 14% of the time. Total odds are that the player wins 88% of the time and loses 11% of the time.

**Applying to your Numbers**
Using your example numbers, you'd need to have a lot more branches, including the fact that many branches include no damage when no attack occurs on that particular round. Which means you'd likely want to automate the process instead of doing it by hand.

~~I'm not exactly sure how you got your charts, but I think you can convert it to similar numbers by multiplying each of the player percentages by the percentage of player wins, then the same for the enemy chart. So, for example, if the player wins 80% of the time, the first number on the chart becomes 80% x 1.4% = 1.12%. Then the first number on the enemy chart becomes 20% x 3.6% = 0.72%. Etc.~~

~~My gut feeling is you can't do what your edit says to get 82%. Each chart sums to 100%, which means each number isn't a percentage of the total, so you can't just add the percentages. You can add the percentages say that 71% of all player wins occur in the first 9 seconds. But you don't know how often the player wins, so you can't say there's a 71% chance the player wins by 9 seconds.~~

Your chart says there's a 71% chance the player wins by 9 seconds. Then it gets complicated. There's a 29% chance the player doesn't win by 10 seconds. 0.2% of that remaining 29% chance involves the player killing the enemy on the 10th second. But this is 0.2% / 29% ≈ 6.90% chance assuming that we got to 10 seconds. Then we have to break that into four parts. Because we could have neither player nor enemy wins, both win, player wins, enemy wins. There's a 3.6% / 100% = 3.6% chance the enemy wins on this turn, with final results of:

In about 89.7% of the cases, nobody wins, so we go to the next step. In about 3.4% of cases, the enemy wins (so the player loses). In about 6.7% of cases, the player wins. And in about 0.25% of cases, both win (so it's a tie). But the total odds are the 29% chance we even got this far times the individual odds of any specific branch happening. For example, there's a 29% x 0.25% = 0.0725% chance of getting a tie on round 10.

So we repeat the same stuff for the next round. Nobody kills anyone on round 11 (100% chance of nothing, 0% chance of other stuff), so we skip to round 12. There's a 29% chance we made it to 10, then an 89.7% chance we went from 10 to 12, so there's a total of 29% x 89.7% = 26.013% chance we get to round 12 at all. The player chance remaining is 28.8%, and the enemy chance remaining is 96.4%. So the odds the player wins this round, given we got here, are 9.8% / 28.8% ≈ 34.0%. The odds the enemy wins this round, given we got here, are 0.2% / 96.4% ≈ 0.21%. Again, there are four possibilities, just like above. Each block is calculated as tie = (e x p), player wins = (1-e) x (p), enemy wins = (e) x (1-p), and neither wins = (1-e) x (1-p), where e and p are the odds of the enemy and player winning given above, 0.21% and 34.0%.

Then we repeat that for every step of the way. Each round will have four options: tie, player wins, enemy wins, and nothing happens (which leads to the next round). In some cases, there will be a 100% chance nothing happens, so we just skip ahead. The final case will have a 0% chance nothing happens. Add up all the numbers for tie + player wins + enemy wins, and you should get 100%. Add up all the player wins to get total odds of the player winning, etc. Assign tie wherever you want, or treat it separately, your choice.
> 1 votes

---
Tags: mathematics, algorithm, fuzzy-logic
---


title: Keep 2d GUI shape through rotation

text:
# Question
Title: Keep 2d GUI shape through rotation
I've been working on creating the GUI system for a 3d game I've been working on, and have hit a bit of an obstacle in trying to rotate GUI elements (Google searching did not yield what I was looking for). This is how the screen looks without any rotation. As of now, rotating each element distorts the GUI elements, like this, whereas I want an effect closer to this, without any stretch or skewing.

My code, using glm, looks like this:

```
void GUI::NewGUIBase::rebuildMatrix()
{
    glm::vec3 newModel = glm::vec3(absoluteTopLeft.x, absoluteTopLeft.y, 1.0f);

    glm::mat4 rotate = glm::rotate(glm::mat4(1.0f), glm::radians(this->rotation), glm::vec3(0, 0, 1));
    glm::mat4 trans = glm::translate(glm::mat4(1.0f), newModel);
    this->setModel(trans * rotate);
}

```

I believe that the issue is due to the fact that my game window is not a square given that OpenGL uses window coordinates from -1 to 1. However, I can't figure out how I would take this into account to achieve the desired effect of rotation without any stretch.

In case it helps, a GUI element knows its own top left corner and its own dimensions (in OpenGL coordinates), and the game window's width and height in pixels.

# Answer
I sloved this by changing the GUI system to pass **real position** instead of **normailzed position**, just an example conecpt here:

```
float vertexPosition[] =
{
  //  x         y
  -1.0f/2.0f,  1.0f/2.0f, // top left
  -1.0f/2.0f, -1.0f/2.0f, // bottom left
   1.0f/2.0f,  1.0f/2.0f, // top right
   1.0f/2.0f, -1.0f/2.0f, // bottom right
}

```

And for each `vertexPosition`, I multiply it by texture's Width and Height.

```
for (int i = 0; i < length; i++)
{
    if (i % 2 == 0)
        vertexPosition[i] *= (float)width;
    else
        vertexPosition[i] *= (float)height;
}

```

Then we got the real position, and you should use `glBufferData` to update your vbo (note: you should bind the vao properly before), and in the shader do the normailize in the final output position, like this:

**Start Edit(1):**

```
#version 330 core
// All positions should be half around the origin in ndc.
in vec2 position;
uniform vec2 translate;
uniform mat4 scale;
uniform mat4 rotate;
uniform vec2 screenSize;

out vec2 TexCoords;

void main()
{
    vec4 realPosition = rotate * scale * vec4(position.x, position.y, 0.0f, 1.0f);
    float normX = realPosition.x / (screenSize.x / 2.0f) + translate.x / screenSize.x;
    float normY = realPosition.y / (screenSize.y / 2.0f) + translate.y /screenSize.y;
    gl_Position = vec4(normX, normY, 0.0f, 1.0f);
}

```

You need to **pass translate seperately**, because we use real postion, otherwise, you might need to compress translation outside and make a matrix.

**End Edit**

You maybe have a final question, how could get the `TexCoord` in shader ? there is two option to get it. One option, pass a Texture Coord that you defined as a Vertex Attribtue in every loop, or if it is constant you should pass it out of loop. The other option is calculate in your shader.

In conclusion, the step of doing this is:

1. Pass the real position instead of normalized position.
2. Do your transformation in shader as usual.
3. Normalized your final position before you give it to `gl_Position`.

**Edit(2)(3):**

The `texCoord` part, I did it and share here :)

```
//.... just like above
out vec2 TexCoords;

void main()
{
    //.... just like above
    float texX = position.x / texSize.x + 0.5f;
    float texY = position.y / texSize.y + 0.5f;
    // if you need to flip image, use texY = 1.0 - texY; here
    TexCoords = vec2(texX, texY);
}

```
> 1 votes

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


# Question
Title: How long should a user's input be delayed?
For browsing the web, the UX site has a great answer.

My question is about games, not forms.

How long from the time a button is pressed, should the player's character react?

On the one hand, instantaneous could be nice. But how would that affect the visuals? I would expect some sort of preparation for the character's actions. For example, jumping would require some bending of the knees first. Swinging a sword would involve raising the sword in hand first. Neglecting these preliminary animations could feel better, but may not look nice. So should that preparation animation not exist? Should it be 100 ms? Can it be up to 500 ms?

On the other hand, many games add intentional delays to require timing by the player. Falcooooo punch! This is not what I am asking for this question, but I figured I should mention it.

So assuming we want instantaneous results for the player, how much time can be designated to the preliminary animations? Does 100 ms (as referred to for the forms answer) also apply to games? Or is there some other strategy used to find a good sweet spot?

And to address the inevitable "You must playtest!" answers - absolutely! But what is a good starting point? As an indie developer, I don't have the ability to iterate much on animations.

# Answer
As discussed in the question's comments, there should be **no delays between the moment the payer hits the button and the visual feedback on the screen**.

As for the time taken to "unsheathe the sword, swing it and hit", i.e. the time between the user hit the button and the *effective* action, the players are used to this pattern:

If the action is very effective (e.g. the 'attack' causes a lot of damage), the delay will be higher, and if the action is not that effective, the delay will be much shorter, allowing the player to do more attacks in the same amount of time.

Now since you want to shortcut the tests on all of your actions/delays, I would suggest you find the 'most effective' action (the one that does the most damage), test the delay that you think your players would not find annoying while still finding the action useful, and once your comfortable with that one, repeat the process with the 'least effective' action. Then scale all your other actions' delays based on these two values, and the actions effectiveness.

---

Alternatively, you could artificially increase the delay in the following case: Allow the users to get items/feats/skills to reduce the delay to an acceptable level. I.e. you can annoy your player by adding an *annoying* delay as an incentive to *buy* in-game items to reduce it. This is typical for games with in-app purchases.

In this case, you have to find the 'just-annoying-and-not-plainly-unplayable' spot, which is harder to do (and for this *\*coughs\* check how other games do it \*coughs\**).
> 3 votes

# Answer
Well, most of the attack sequences vary in length and realism. Hack&Slash games you would want to have it \<1f sec or even 0.5f and for Moba games you would want somewhere between 0.8f-2f secs so the PvP allows the other player to interact.

Mostly, you would have (or in the future have an animation for the attack which includes the swing/draw). Use the animation clip at different speeds and check does it match your game idea. With a simple binary search of 5 iterations from the interval of \[0-2\]sec will give you a 0.125 sec precision the whole speed of the animation. Then just run the animation at the speed and pause it at the moment you think it matches best that you have hit and calc the time that have passed.

Really good will be if you have a animation tool that gives you a slider along frames and also to sec the FPS of the animtion.
> 0 votes

---
Tags: animation, timing
---


# Question
Title: How Should I Go About Updating My XNA Game?
So, I've created an XNA game, but I'm not selling it... it's just a private game to give away to my friends, more of a practice project. But say I find a bug, or think of a new feature...

I don't want to have to resend the file to them every time an update comes out. That'd be too many people to send it to. How should I go about this issue?

If this question is a duplicate, please tell me, or if there's a Web page with this answer that I missed, also tell me.

Thanks in advace!

# Answer
If you want a website for free, then you can use Github Pages(\*.github.io) to get a free static(you don't handle the server side) website. I once built a launcher that you could download that would download from github raw files. A good example of a launcher is Minecraft's launcher. It allows you to select versions you would like to install by creating profiles that let you pick which version to download as well as how much ram you want that profile to use.
> 1 votes

# Answer
As David already mentioned, get a website and program an auto-updater for your projects. It works as follows: When your game starts check for the server version located on your website in a file. If the version is newer than your client one, you have to update.

Updating can be done by either downloading the whole project, or just the new and modified files, which saves time and unneccessary data transfers. If you're game is small or you only have a few files, updating the whole project should be enough.

But if you want to update only the modified part of your game, you have to compare all your files with the files on your website. A fast way to determine a difference between two files is to first compare their size and if they're equal copmare their hashes instead of the whole file, if any didn't match download the file.

Before uploading a new version, you create a file which contains all file paths, sizes, and hashes generated from each file, so that the client only has to download this file in orer to determine which files need to be downloaded. Also don't forget to zip your files, before uploading.
> 3 votes

---
Tags: c#, xna, xna-4.0, monogame
---


# Question
Title: How would you go about rendering something like a line of coke more realistically, say with shaders?
Im currently developing an app, where it simulates the snorting of cocaine. Im using LibGdx in Java to do that, I have got the mechanics down, but what Im currently left with is this:

Im currently rendering 1000 particles, which is doable by my Huawei P8, which isnt really high end. Doesnt really look good though. Any recommendations or other approaches you would use?

# Answer
> 1 votes
This question doesn't necessarily have to be about "cocaine" but could also relate to the rendering/animation of any sort of particle media.

You don't necessarily have to use particles to do what you want. You can just apply a decal or a texture to whatever surface you want to present the particulate material on. If you want it to animate, you can prebake something.

If you really need real time though, your best bet is going to be something with particles and some other techniques:

* You should look into something like 2D meta balls. This would allow your particles to have the volume that you want without actually rendering more particles because of how it fills the space. The goal would be to have it feel like 10,000 grains of particulate with only 1000 particles.
* Some sort of smudging or blurring of the particles might also make it look like there's more than there really are.
* Per particle lighting will give your particles some depth and make them contrast more from each other. Similarly, some sort of global lighting might help to actually make the particulate look like it has some height (shadow on the table underneath, shadowing the back faced particles)
* Add a little bit of variation to the particles. Color, shape, and size variation will help to sell it as less of a circle particle and more of a granular substance.
* Texturing your particles might help to show some variation and possible make each particle look like more than one. Only problem with this is that movement would look very odd.

All of the above are just for the particles. You might also think about having one large solid mass and then adding particles around this to better represent the looseness of the substance while still getting the volume and the "sharpness" that you loose with something like metaballs.

I'm not an expert in engineering realistic materials so this is from my own intuition, and expert might have a better answer.

---
Tags: java, libgdx
---


# Question
Title: C & SDL: Unexpected Behaviour with Renderer
I'm creating a clone of the memory testing game SIMON. My program is simply four differently colored squares that light up one at a time in a random order. I wrote some code that lights up one square, dims it, waits 250ms and then lights up the next in the sequence. Rinse and repeat until the sequence is complete.

My problem is that everytime it lights up a square, it's lighting up all of the previous lit ones as well, instead one at a time. I hope I'm explaining that clearly.

Below is my code. I know it's silly code, but I plan to come back and find a better way to do it.

```
SDL_SetRenderDrawColor(renderer, 255, 255, 0, 255);
SDL_RenderFillRect(renderer, &squareTwo);
SDL_RenderPresent(renderer);

SDL_Delay(250);

SDL_SetRenderDrawColor(renderer, 50, 50, 0, 255);
SDL_RenderFillRect(renderer, &squareTwo);
SDL_RenderPresent(renderer);

SDL_Delay(250);

SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
SDL_RenderFillRect(renderer, &squareThree);
SDL_RenderPresent(renderer);

SDL_Delay(250);

SDL_SetRenderDrawColor(renderer, 50, 0, 0, 255);
SDL_RenderFillRect(renderer, &squareThree);
SDL_RenderPresent(renderer);

SDL_Delay(250);

SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
SDL_RenderFillRect(renderer, &squareThree);
SDL_RenderPresent(renderer);

SDL_Delay(250);

SDL_SetRenderDrawColor(renderer, 50, 0, 0, 255);
SDL_RenderFillRect(renderer, &squareThree);
SDL_RenderPresent(renderer);

SDL_Delay(250);

SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255);
SDL_RenderFillRect(renderer, &squareFour);
SDL_RenderPresent(renderer);

SDL_Delay(250);

SDL_SetRenderDrawColor(renderer, 0, 0, 50, 255);
SDL_RenderFillRect(renderer, &squareFour);
SDL_RenderPresent(renderer);

```

With the above code, I was hoping only one square will be lit up at once. Instead the first one lights up, and dims. And then the first and second square light up at the same time.

And to make this even stranger, I ran it on my work computer and it works like expected (both systems it was tested on are Linux, if that matters)! Maybe I changed something by accident after last testing it, but I really just don't recall that. Very strange.

Would anyone have any ideas or clues for me on this one?

# Answer
From the documentation of `SDL_RenderPresent`:

> The backbuffer should be considered invalidated after each present; do not assume that previous contents will exist between frames. **You are strongly encouraged to call `SDL_RenderClear()` to initialize the backbuffer before starting each new frame's drawing**, even if you plan to overwrite every pixel.

You should try to call `SDL_RenderClear()` after each call to `SDL_RenderPresent()`.
> 0 votes

---
Tags: c, sdl2, linux
---


# Question
Title: Storing Highscores using PlayerPrefs in Unity
```
int highscore = 0;
void Update()
{
    storepoints();
    print(PlayerPrefs.GetInt("highscore", highscore));
}
void storepoints()
{
    if (points>highscore)
    {
        highscore = points;
        PlayerPrefs.SetInt("highscore", highscore);
        PlayerPrefs.Save();
    }

}

```

Using the following code:

it works first time. But not the second time

so, for e.g, when I play the first time, suppose my score is 2, my high score becomes 2. However when I play the second time, and my score is 1. My high score becomes 1. This shouldn't happen.

# Answer
> 1 votes
You most likely forget to update the highscore before checking it the second time:

```
int highscore = 0;
void Update()
{
    storepoints();
    print(PlayerPrefs.GetInt("highscore", highscore));
}
void storepoints()
{
    highscore = PlayerPrefs.GetInt("highscore", highscore); // ADD THIS LINE

    if (points>highscore)
    {
        highscore = points;
        PlayerPrefs.SetInt("highscore", highscore);
        PlayerPrefs.Save();
    }
}

```

# Answer
> 0 votes
The highscore field starts off as 0 so any points over 0 will count as a highscore and write over the score stored in PlayerPrefs. Set highscore to the PlayerPrefs value before calling storepoints.

You could do this in a start method:

```
void Start () {
     highscore = PlayerPrefs.GetInt("highscore", highscore);
}

```

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


# Question
Title: Move object forward according to rotation
How do I make an object (like a bullet) go forward according to its rotation in vanilla nodejs (my game server language)? For example, if an object's rotation is 0 degrees, then it goes straight up.

# Answer
Enter trigonometry!

You need to have an angle and the speed of the bullet to get a velocity vector for the bullet.

Getting a directional vector can be done the following way (v is the vector, x and y are it's components)

```
v.x := cos(angle) * speed
v.y := sin(angle) * speed

```

If you don't multiply with speed you get a vector with a length of 1 (a unit vector), which is the directional vector of the bullet

Note: if you have your angle in degrees, then you need to convert in to radians by doing `newAngle := angle / 180 * PI`
> 2 votes

---
Tags: geometry
---


# Question
Title: Create Full Tile Map Zone in an Art Software, then generate corresponding tile name list?
I'm completely new to tile map creation. I'm a programmer and I'd like to make life easier for myself. It's a bit long to explain the problem I think I have, but bear with me.

**The Scenario:** From what I understand, in my code I need an array which holds my tile information for a zone/area in my game. Lets say for simplicity this zone was a 10x10 grid, so 100 indexes in the array. Now, lets say each index holds a number that corresponds to a specific tile. ex) Number 1 means grass tile. Number 4 means rock tile. etc.

So far so good. From this array (and additional coding), my tile map will be generated on my game screen.

**The problem**: As it stands I have to individually type each tile identifier for each index in the array. Now let's say that I have already fully designed the visual tile grid map for my zone in a particular art software. Simply put, I am staring at my fully completed zone in my art software screen and it is my visual aid for creating my array. My strategy now is to look at each grid cell, see what tile I put in there, and type its identifying number into my array. Rinse and repeat hundreds of times, looking at each individual tile until I manually complete the array. This is an extremely tedious and long process.

**What I want:** So my full tile map is already in my art software. What I want is for the software to more or less generate the array for me! I press a button, and It will see what tile is in each grid square, and accordingly generate a list in a text document with each tile's identifying number that I give it. That's literally all I need. I can then copy and paste the list into my array in my code. It shaves off tons of time.

**The Question:** Notice that I have used the generic term "art software". Is there any art software that can do what I described? Is there any art software (e.g. adobe illustrator, photoshop, gimp, etc.) which upon having a fully completed tile map, will be able to generate a text file list of each tile's identifying name?

# Answer
> 2 votes
Very sorry for posting this without doing my proper research. I have found a program called Tiled. It does exactly what I want it to do (or close enough). When I save my finished tile map in Json format, I can open it up in a text editor and the array is right there in the "data" section.

---
Tags: procedural-generation, tilemap, tiles, automation
---


# Question
Title: Rotating an object at the user specified speed in corona
I am developing a globe animation, in which the speed of the rotation changes with the length of the user's drag event.The globe when touched and moved attains positive acceleration,reaches maximum value,rotates there for sometime and starts retarding and comes back to its original position.Can anybody tell me how to do this in corona.A sample code will be really helpful.

Thanks.

# Answer
Well first off, Corona is a 2D SDK so I'm not sure how effective it would be to do an animated globe like this. Still, it's pretty easy to get the length of a user's drag, and then you can use that length to modify the speed of your animation.

First off, make sure to set your event listeners for "touch" and not "tap". "Touch" events respond to both the beginning and end of a user's gesture, while "tap" events simply responds to the user tapping a spot.

In the documentation for "touch" event listeners, you'll see you can check the "phase" property of the event in order to check for "began" and "ended":

http://developer.anscamobile.com/content/events-and-listeners#touch\_single\_touch

Simply calculate the distance from start to end when event.phase=="ended"
> 1 votes

# Answer
I used Series of png images and changed images on swipe.The images had gradient in it hence looked like 3d rotation.
> 0 votes

---
Tags: corona-sdk
---


title: How to make the AI Chase in Multiplayer

text:
# Question
Title: How to make the AI Chase in Multiplayer
Im Currently develop a little Dungeon Crawler. The Singeplayer works fine, but it also should have multiplayer so i implemented it. But there's one problem. I have no idea how to make the AI chase the player and the other players. In singleplayer it works like this :

```
if(distanceToPlayer <= 400f){

   entity.chase(playerEntity);

}

```

Heres my full chasing code :

// in enemy update method i put all multiplayers into a map with their login number..

```
 // Pick a random Multiplayer and chase him

        boolean isAvaible = false;

 //Convert Map to Object array
        Object[] values = ((EnemyEntity)arg0).mpSortedPos.values().toArray();

        int rdm = 0;

        float randomValue = 0;

        // wenn map isnt empty
        if(((EnemyEntity)arg0).mpSortedPos.size() > 0){

            rdm = generator.nextInt(values.length);

            randomValue = (float)values[rdm];

            isAvaible = true;

        }

        //selecting the key
        // +2 because the first joined player is the second Player in the game so it begins with connection 2, the second with 3 and so on.
        int key = rdm + 2;

        // Only printing stuff
        System.out.println("Found a Map : "+((EnemyEntity)arg0).mpSortedPos + "Size of da HashMap : "+ ((EnemyEntity)arg0).mpSortedPos.size());
        System.out.println("Found a Random Value : "+rdm + " "+randomValue );
        System.out.println("Found a Key: "+key + " "+((EnemyEntity)arg0).mpSortedPos.get(key) );

        // When the multiplayer is near the enemy than
        if (/*((EnemyEntity)arg0).distanceToNextPlayer < 400 && arg0.isAlive() == true */ isAvaible && ((EnemyEntity)arg0).mpSortedPos.get(rdm) != null && ((EnemyEntity)arg0).mpSortedPos.get(rdm) < 400) {

            ((EnemyEntity)arg0).activated = true;

            arg0.stateMachine.changeState(CHASE_ENTITY);

        }

```

This is my code for multiplayer chasing but it doesnt work ... any ideas ? What could i improve ?

But how should i do that with multiple players ? Any ideas ? :)

# Answer
> 2 votes
Just the same way. You just have to pick an algorithm to select a player to chase from available players. E.g. by factoring distance to the player, remaining hitpoints, random, etc.

---
Tags: c#, java, libgdx, ai
---


title: Push cube outside triangle face

text:
# Question
Title: Push cube outside triangle face
I'm creating a 3D game, and I need to know how to push a player (axis aligned box/cube) outside a triangle.

How can I get get the push direction?

# Answer
I'm not quite sure what exactly do you need to achieve based on the vague question, but these are some solutions you can consider, assuming you do not use a third party physics engine.

Firstly, if your player is a axis aligned, you can first implement a variation of a ray-box intersection check. One of the fastest method is the slab method. There is a very good article for visualising the slab method on tavianator.com.

Once you are able to detect collisions with your AABB player with rays, it is a simple process to draw 3 rays from one vertex of the triangle to the next to detect if the player is colliding with the triangle. Perhaps with a few more rays if your triangle is bigger than your player.

You can then figure out the push direction based on the player's position, as well as the midpoint of the two points on the ray intersecting the player:
> 1 votes

---
Tags: geometry
---


title: Move around object

text:
# Question
Title: Move around object
I have problem with Unity - 2D objects. I want to rotate object around circle and on click translate it (with same angle) outside the circle to another and still rotate.

Rotating is working with RotateAround. But what about translating it to another circle?

I explained it in the image:

# Answer
Here is one theoretical solution you can try.

Your moving object (that I'll call **Dot**) is moving around other objects (that I'll call **Gravity Points**). The Dot knows what Gravity Point it is attached to and should know the position of other Gravity Points. Also as they are defined as circles I imagine that they have a radius that you can easily know.

When the player clicks you can detach the Dot from its current Gravity Point and make it "float through space" until it enters in the radius of another one. To know the direction where to float to you just need to know the position of the current Gravity Point and the Dot position.

`(Dot.position - GP.position).Normalize` will give you the floating direction. Applying this direction every frame to the Dot will make it go straight through space.

Once done you need to know if the Dot meets a new Gravity Point. As every Gravity Point has a radius you just have to compute the distance from the Dot to all the Gravity Points and compare it to their radius. Doing something like `Vector3.Distance(Dot.position,GP.position)` will give you the distance from the Dot to a given Gravity Point. If this distance is shorter or equal to the Gravity Point radius, then you can attach your dot to it, and start the rotation again.

I hope it helps.
> 1 votes

# Answer
A quick and easy solution if you do not want to deal with too many calculations (you can refer to Ivictorino's solution if you want that), is to simply parent the small rotating circle to the big circles.

The hierarchy might look something like this:

```
BigCircle
|
|_ EmptyObjectAtCenterOfBigCircle
   |
   |_ SmallRotatingCircle

```

In code, all you're doing is rotating the "EmptyObjectAtCenterOfBigCircle". When you need to do the transfer, lerp the small circle to the appropriate position, reset the parent, and start spinning the new "EmptyObjectAtCenterOfBigCircle".

```
smallCircle.transform.position  = Vector3.Lerp(
         smallCircle.transform.position,
         targetCircle.transform.position + targetCircle.radius + 0.1F,
         Time.deltatime);

//When the lerp is done:
smallCircle.transform.parent =
         targetCircle.transform.Find("EmptyObjectAtCenterOfBigCircle");

targetCircle.GetComponentInChildren<SpinCode>().SetActive(true);
smallCircle.GetComponentInChildren<SpinCode>().SetActive(false);

```

*Spincode* simply rotates the *EmptyObjectAtCenterOfBigCircle*.
> 0 votes

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


# Question
Title: How can I make particles glow and cast light on its surroundings?
Im currently attempting to make a firefly effect on a dark forest. The level has very low light and the player is one of the few light sources. To let the player see the level better, I am attempting to making glowing fireflies appear randomly on the map. One way is to use a particle system. But I cant make the particles cast light one the surroundings. Is there a way to do this?

# Answer
Light emiting particles is now a built in Unity feature in 5.5.

Simply enable Lights in the particle inspector, throw in a reference to a light prefab (both point and spot lights work), and change the Ratio to 1.

And voilà, particles that emit lights:

Turns out, this is a rather optimized setup, running at 1500+fps on my rig even with maximum lights in the hundreds.

Edit: After some observation, it seem to me that the particle lights toggle between per fragment lighting and vertex lighting (presumably for optimization?). This might produce small amounts of visual artifacts if maximum lights is set too high.

Edit2: As pointed out by DMGregory, the artifacts are a byproduct of forward rendering optimizations. Deferred lighting solves the issue. Added nicer gif
> 8 votes

# Answer
---

## Heads-Up:

**This answer is outdated. Unity now supports point light particles natively.** Please see this answer for full details.

I'll leave post this here for anyone curious, or using old versions of Unity, or needing more manual control than the native method offers - just note that the native support is likely to be much more efficient and scalable than the approach presented below.

---

I'm not sure why so many answers claim this is difficult or impossible. Handling a few dozen dynamic point lights is pretty conventional for a modern deferred rendering pipeline running on PC.

Here's a quick example I cooked up:

I use this script to dynamically spawn enough lights for my max particles (make sure you adjust your Particle System settings so the max is reasonable - the default of 1000 will not make your graphics card very happy), and then updates them to follow the active particles:

```
[RequireComponent(typeof(ParticleSystem))]
public class ParticleLights : MonoBehaviour {

    public Light lightPrefab;

    ParticleSystem _system;
    ParticleSystem.Particle[] _particles;
    Light[] _lights;

    void Start () {
        _system = GetComponent<ParticleSystem>();
        _particles = new ParticleSystem.Particle[_system.maxParticles];

        _lights = new Light[_system.maxParticles];
        for(int i = 0; i < _lights.Length; i++)
        {
            _lights[i] = (Light)Instantiate(lightPrefab);
            _lights[i].transform.parent = transform;
        }
    }

    void Update () {

        int count = _system.GetParticles(_particles);
        for(int i = 0; i < count; i++)
        {
            _lights[i].gameObject.SetActive(true);
            _lights[i].transform.localPosition = _particles[i].position;

            // Looks like the GetCurrentColor function was added in 5.3.
            // You can use other methods in earlier Unity versions.
            _lights[i].color = _particles[i].GetCurrentColor(_system);
        }

        for (int i = count; i < _particles.Length; i++)
        {
            _lights[i].gameObject.SetActive(false);
        }
    }
}

```

**Edit:** you can create a prefab by first creating a game object (in this case, Create -\> Light -\> Point Light), setting it up with the name/parameters/scripts/children you want, then dragging it from your Hierarchy into your Project explorer. This saves the object as an asset you can reuse across multiple scenes & scripts, with a degree of inheritance. You can delete the copy in your scene and the asset will remain in your Assets folder to be referenced when needed.

Make sure the lightPrefab has a relatively small range and is not shadowcasting, to give you the most performance headroom for everything going on in your scene. You don't need to make the lightPrefab itself green (or the colour of your fireflies) - it will pick it up from the particles' colour.

You might find though that you have better control over the fireflies' flight if you make each one its own GameObject, with a billboarded quad and a light attached with a custom movement/blinkig script, since getting a convincing wander takes more particle system artistry than I know. ;)
> 31 votes

# Answer
Years ago, before dynamic lights were affordable, we would simply use a 2D-billboarded particle effect with additive blending. It would brighten the scene towards white. By drawing it with the correct depth of the firefly, you get almost correct sorting. Additive alpha doesn't need sorting when overdrawing itself compared to alpha blending. It won't light up ALL the scene, but it will light up the area surrounding the firefly. You could then take a dynamic light and pick one of the fireflies every few seconds to actually light the scene, if you need it.

There's a question & answer already about glow effects How to achieve lighting like this in Unity for 2D games?
> 4 votes

# Answer
Unfortunately, I've not had much experience with Unity in it's current form (I toyed around with it many years ago), so I don't know exactly what feature sets you have to work with in the engine.

In any case, no matter what engine you work with, dynamic lights are something to avoid whenever you can. They are very computationally expensive, and tend to add scene complexity in a very exponential way. However, as is the order of the day for most 3D rendering, there are many ways you can achieve similar effects by cheating;

A possible way to achieve a similar effect is to map a premade glow texture to the terrain below your fireflies, (assuming a Y = up/down coord. system) with X and Z positions controlling location of the glow on the terrain and Y offset from the terrain controlling the texture's alpha (brighter = closer to terrain)

There are of course several drawbacks to this method. You won't cast shadows as no light is used, and you won't affect any other geometry in the world (props, foliage, etc)
> 0 votes

# Answer
Use `Light` at the origin of fire and play with its size in script so it will give effect of burning. And use your particle system :)
> -2 votes

---
Tags: lighting, unity, particles
---


# Question
Title: Would it perform faster to split calculation between vertex and fragment shaders?
Assuming the total amount of computation would be the same (at least as far as my code goes), would there be any performance increase in splitting the calculation and using separate vertex and fragment shaders vs. doing all the calculations in just a fragment shader?

In my use case, I would not be using vertex shaders as they are typically intended (so, not processing actual vertices). I just thought if the GPU hardware is set up such that the pipeline is expected to be used, would it be better to take advantage of that, or would it be just as fast to put it all in a fragment shader. Conceptually, it would be simpler to just use the fragment shader.

Note, that I do need a lot of data going to the fragment shader that is updated every frame (eg. texture buffer object).

# Answer
Nowadays, GPUs use an hardware design called Unified Shading Architecture.

This implies that GPUs are basically an array of general working units (shader cores) that can handle any type of shader operations. Since they all can process any form of shaders, when you need to compute something, a scheduler is going to allocate some units to your shader and use as many as possible to keep them busy with your tasks.

Still, modern GPUs still have fixed-functions elements in their pipeline. That is, for example, after a shader core is allocated a Vertex Shader-kind of work, it will have to go through the fixed-function Primitive Assembly Same for the Fragment Shader, it will have to go through Blending Operations, and so on, for other stages.

The best you should do is to keep vertex operations in a Vertex Shader and fragment ones in a Fragment shader. This will help take advantage of dedicated hardware for some tasks, like early-z culling, etc...

But you could, still defer some of the computations to a compute shader, but that's something else.

Hope this helps
> 1 votes

---
Tags: opengl, shaders, fragment-shader
---


# Question
Title: Help setting up money system in game maker
I am trying to make a clicker game where one button makes the item and then one button sells the item. My problem is that I don't know how to make the one button stop selling when it reaches 0 items to sell. My code for the selling of the item as of right now looks like this in game maker:

```
///Sell items
global.money+=global.PC
global.items-=global.PC

```

It works to subtract per click, but once it reaches 0, it keeps going in to negatives. I am very new to this so forgive my asking probably simple questions.

# Answer
> -1 votes
I would go with most short and simple method.

```
//Sell items

global.money+=global.PC * (global.items > 0)

global.items-=global.PC * (global.items > 0)

```

# Answer
> 2 votes
Use a conditional IF statement.

```
// First, check IF there are enough items left to sell
if (global.items >= global.PC) {
    // Condition passed -- Sell items now
    global.money+=global.PC
    global.items-=global.PC
}

```

If the condition fails, the code will not execute.

# Answer
> 0 votes
```
global.items = 10
if (global.items >= 1) {
    // There are more than one item, so it passes.
    global.money+=global.PC
    global.items-=global.PC
} else
{
draw.text"No more items" //Im at work, so i cant get on game maker to test the draw. text function, but you get the idea here.
}

```

This would be my solution to your problem, i have implemented systems like this before in my games. I hope it helps.

---
Tags: game-maker
---


title: OpenGL managing many textures smoothly

text:
# Question
Title: OpenGL managing many textures smoothly
I'm working on a game right now and running into some noticeable performance issues and limitations.

Basically, I have this:

* A few `QGLWidget`s, all sharing contexts with eachother (probably irrelevant that I'm using Qt \[also: Windows, fwiw\]).
* About 216000 total frames of 128x128 videos (with alpha, internal format GL\_RGBA, data format GL\_BGRA/GL\_UNSIGNED\_INT\_8\_8\_8\_8\_REV, video codec is Quicktime RLE, decoded with libav), spread into approximately 120 videos of 1800 frame average length. This translates to roughly 216000\*128\*128\*4 = 14.2 GB of raw data, not including overhead.

The game behaves as follows:

* There are many "modes". At any given time only one mode is active. Each mode uses a very small known subset of the available videos, say 5-10 videos (= about 9000 - 18000 frames) tops.
* There's a bunch of 2D quads flying around the screen, each displaying whatever videos depending on the current mode. Objects don't all display the same frame, the video time offsets are random. The videos loop.
* Every few minutes, the mode changes. Objects cross-fade to their new videos, so there is some overlap regarding when various sets of videos are needed.
* It is *critical* that this thing keep running smoothly, at 60 FPS, with no pauses for loading, etc.

My problem is this:

My initial approach was to simply preload all videos off the disk and into textures, in video memory (via `glTexImage2D` and friends). I didn't mind the slow startup. This worked great early on, when I didn't have a lot of videos. The game could run smoothly because all the textures were already loaded.

Now I have too many videos. I'm becoming extremely limited by available video memory, and the preload-everything strategy is no longer working. I haven't become limited by system memory *yet* but that's also inevitable. I suspected this was going to be an issue and kept my fingers crossed, but alas. I hit the limit way sooner than I expected.

I tried switching to a strategy where, every time a mode transition started I pre-loaded the videos for that mode (and every time a transition ended I unloaded the videos for the previous mode). This works as far as memory goes but it pauses everything for a very long time while loading (as in 3-8 seconds depending on the number of videos and the graphics hardware).

I've done the best searching that I know how to do, all of the texture memory management posts, blogs, tutorials etc. just talk about the basic technique of creating and destroying textures, rather than strategies for managing large numbers of them in an application. I went through every question in the auto-search on here that had a relevant-looking title. I did find out that OpenGL is definitely not thread-safe, which kind of kills my asynchronous background loading idea, unless there's some other way to implement that.

So my question is: **What's a good strategy to use for swapping out tons of textures (200000+, 128x128 typical size) when at any given time only a small portion of those are needed, while maintaining a smooth frame rate?** How is this typically done?

# Answer
> 7 votes
While OpenGL is thread unsafe, you can load such data asynchronously.

Say you know you will transition in about 20 seconds. You start loading the image data on another thread. The thread loads the image data from disk to memory, then sets a flag for the main thread(which owns the OpenGL context), to load it to the GPU.

In the main loop, perhaps in your update function, you will check if there is anything to load, but do it cleverly, so you will load an image, and check if you have some frame-time left. If you do, load another, if you don't then bail out, and continue uploading the video frames next frame/iteration.

If you start processing early enough, there will be no delay when the time to transition comes. You just need to make sure your program doesn't crash if the resources aren't loaded yet, and handle all the corner cases this solution imposes.

It definitely is a much more complex solution than just pre-loading, but to me it seems this is a necessary complication to solve your problem.

---
Tags: opengl, c++, textures, qt
---


title: Blender->Unity materials problem

text:
# Question
Title: Blender->Unity materials problem
I have a pproblem with materials and their texture. I have a model with 1 material called 'Car\_Jack', after i put my .blend file into unity, unity adds 'Car\_Jack\__Car\_Jack\_UV', which is white material without textures. I have the only one UV map, called 'Car\_Jack\_UV'. What is wrong with Unity/Blender?

# Answer
> -1 votes
Try exporting your Blender scene as .fbx and import the fbx from Unity

---
Tags: blender, uv-mapping, materials
---