# Question
Title: Storing rendering data for voxel game 1 VAO and VBO or 1 for every chunk
I have a minecraft style voxel game with placing and digging blocks. it runs at 400+ fps on my computer but when I added semi-transparent water it started running at ~40 fps. so a time per frame increase of 0.0175s or 8 times what is used to be. What I am currently doing is having a VAO and VBO for each chunk and every time a chunk is changed or loaded it finds all of the non occluded blocks and puts their positions into another buffer in the chunk. then I use instancing to render the whole chunk in one draw call so every frame I am doing ~300 draw calls.

Once I added the water(using order independent transparency http://www.openglsuperbible.com/2013/08/20/is-order-independent-transparency-really-necessary/) I was individually calling gldrawelements() for every visible water block so around 9000 if half the visible area is ocean. I know using instancing with these blocks would help but then I have 2 VAOs for every chunk and 600+ draw calls of buffers with only a couple hundred blocks in them. would there be a better way to organize these things.

# Answer
> 1 votes
I base my water shader off of this work, its directX based but I'm sure with a bit of work you can convert it over but ill go over how I do it so you have an idea\recipe.

First up I make a copy of the current frames back buffer to use as the refraction buffer or you can draw everything again and use clip planes but I only do that for the reflection buffer to save a heap of draw calls at the cost of some artifacts in the refraction buffer.

I then compute a reflection camera and then draw everything that I want to reflect into the reflection buffer using the reflection camera as the view matrix.

Water Camera View:

```
    // play with the (0,0,0) value here to adjust the water camera offset
    Dim WaterPos As Vector3 = BasePos + CType(Vector3.Transform(New Vector3(0, 0, 0), Matrix.RotationX(MathHelper.ToRadians(0)) * Matrix.RotationY(MathHelper.ToRadians(_yaw))), Vector3)

    WaterPos.Y = -WaterPos.Y + 175 * 2 // sets the camera Y cord(adjust 175 to water height +- 3-5)

    //locks the pitch part of the rotation matrix
    Dim watertemp As Matrix = Matrix.RotationX(MathHelper.ToRadians(15)) * Matrix.RotationY(MathHelper.ToRadians(_yaw)) * Matrix.Translation(WaterPos)

```

I have the reflection buffer resolution set to 1/4 full screen resolution make sure it has the same aspect as the back buffer it the projection will fail, the normal perturbation(waves+wind) hides the jaggyness.

When I come to render the water I just draw the water plain with an opaque blendstate and use this shader to blend it all togeather.

Water shader:

```
WaterVertexToPixel WaterVS(float4 inPos : POSITION, float2 inTex: TEXCOORD)

{

WaterVertexToPixel Output = (WaterVertexToPixel)0;

float4×4 preViewProjection = mul (xView, xProjection);

float4×4 preWorldViewProjection = mul (xWorld, preViewProjection);

float4×4 preReflectionViewProjection = mul (xReflectionView, xProjection);

float4×4 preWorldReflectionViewProjection = mul (xWorld, preReflectionViewProjection);

Output.Position = mul(inPos, preWorldViewProjection);
Output.ReflectionMapSamplingPos = mul(inPos, preWorldReflectionViewProjection);

Output.RefractionMapSamplingPos = mul(inPos, preWorldViewProjection);

return Output;

}

void WaterPS(WaterVertexToPixel PSIn)

{

    float3 eyeVector = normalize(WorldCameraPos - WorldPos);

float3 NormalData1 = 0;
float3 NormalData2 = 0;

NormalData1 = BumpMap1.Sample(samANISOTROPIC,texturecoords).rgb;
NormalData2 = BumpMap2.Sample(samANISOTROPIC, texturecoords).rgb;

float3 normalT = normalize(lerp(NormalData1 - 0.5, NormalData2 - 0.5, flowLerp) *2);
  float2 perturbation = WaveHeight * normalT.rg;

// Project Reflection Buffer To Water Surface
ProjectedTexCoords.x = PSIn.ReflectionMapSamplingPos.x/PSIn.ReflectionMapSamplingPos.w/2.0f + 0.5f;

ProjectedTexCoords.y =   PSIn.ReflectionMapSamplingPos.y/PSIn.ReflectionMapSamplingPos.w/2.0f + 0.5f;
float2 perturbatedTexCoords = ProjectedTexCoords + perturbation;
float4 reflectiveColor = tex2D(ReflectionSampler, perturbatedTexCoords);

 // Project Refraction Buffer To Water Surface
ProjectedRefrTexCoords.x = PSIn.RefractionMapSamplingPos.x/PSIn.RefractionMapSamplingPos.w/2.0f + 0.5f;

ProjectedRefrTexCoords.y = -PSIn.RefractionMapSamplingPos.y/PSIn.RefractionMapSamplingPos.w/2.0f + 0.5f;
    float2 perturbatedRefrTexCoords = ProjectedRefrTexCoords + perturbation;
float4 refractiveColor = tex2D(RefractionSampler, perturbatedRefrTexCoords);

float3 combinedColor;

//The Fresnel equations, deduced by Augustin-Jean Fresnel, describe the behaviour of light when moving between media of differing refractive indices.

float fresnelTerm;

fresnelTerm = dot(eyeVector, normalVector);
fresnelTerm = 1 - fresnelTerm*1.3f;

fresnelTerm = fresnelTerm * FresnelAdjust;

//just to be sure that the value is between 0 and 1;
fresnelTerm = fresnelTerm < 0 ? 0 : fresnelTerm;
fresnelTerm = fresnelTerm > 1 ? 1 : fresnelTerm;

// creating the combined color
combinedColor = lerp(WaterColor, ReflectionColor.rgb, fresnelTerm);

combinedColor = lerp(RefractionColor.rgb, combinedColor , alpha);

return combinedColor ;

}

```

I know you have a mine craft style world but I assume you would just apply the shader to each block or each chunk of blocks.

when you come to draw the reflection buffer you will need to clip everything bellow the water or it looks funky also have a play with the cull mode as you may need to flip it.

Clip plain:

```
 dim  reflectionPlane as plain = CreatePlane(120, New SharpDX.Vector3(0, -1, 0), True)
    //Use this float4 on the GPU to clip my geometry when filling the reflection buffer, not sure how to do it in openGL

    dim  planeConvert as vector4 = New SharpDX.Vector4(reflectionPlane.Normal, reflectionPlane.D)

 Public Function CreatePlane(Height As Single, planeNormalDirection As SharpDX.Vector3, clipSide As Boolean) As SharpDX.Plane
    planeNormalDirection.Normalize()
    Dim planeCoeffs As New SharpDX.Vector4(planeNormalDirection, Height)
    If clipSide Then
        planeCoeffs *= -1
    End If
    Dim tempCoeffs As Single() = New Single(3) {}
    tempCoeffs(0) = planeCoeffs.X
    tempCoeffs(1) = planeCoeffs.Y
    tempCoeffs(2) = planeCoeffs.Z
    tempCoeffs(3) = planeCoeffs.W
    Dim finalPlane As New SharpDX.Plane(tempCoeffs)
    Return finalPlane
End Function

```

I also have not tested that shader because I had to pull it out of my messy beast of a water shader but you should get the general idea.

Vertex shader takes World, View, Projection and WaterView as inputs(float4x4).

Pixel shader has two textures Relfection and Refraction, two normal maps for the details on the surface of the water.

Maybe use bigger chunks and some GPU occlusion queries to cull out even more chunks you cant see.

---
Tags: opengl, voxels, vbo, transparency, vao
---


title: What does SlerpUnclamped do?

text:
# Question
Title: What does SlerpUnclamped do?
Unity has a Slerp method:

```
public static Vector3 Slerp(Vector3 a, Vector3 b, float t);

```

Where it returns an interpolated position between a and b by the percentage of t. So if t = 0.5, and a = Vector3.zero, and b = Vector3.one, it returns a Vector3 of (0.5, 0.5, 0.5).

But what does SlerpUnclamped do?

```
public static Vector3 SlerpUnclamped(Vector3 a, Vector3 b, float t);

```

t is not clamped between 0 and 1. So what what is t relative to? How do you use this method?

# Answer
Unclamped would mean that you can get points on the spherical interpolation curve that lie beyond the initial vectors. (After all the SLERP curve is defined by a mathematical function). So a `t` value \> 1 would mean a point on the curve that lies beyond vector `b`

Thanks @UnholySheep for the answer!
> 2 votes

---
Tags: unity, vector, lerp
---


title: Random range of items?

text:
# Question
Title: Random range of items?
I want to add random function into this script. If boxDestroyed is true, three items pop up. What i need is to give random number of items between 0 to 3.

```
    public GameObject[] items = new GameObject[3];
    public bool boxDestroyed = false;

void LateUpdate ()
{
    if (boxDestroyed == true)
    {
        Vector3 position = transform.position;
        foreach (GameObject item in items)
        {
            if (item != null)
            {
                //  int amont  = Random.Range(0,3);
                Instantiate(item, position, Quaternion.identity);

            }
        }

        Destroy(gameObject);
    }
}

```

# Answer
> 3 votes
The 2nd integer (max) of Random.Range(min, max) is exclusive, meaning it wont return that number so you need to set it 1 higher.

```
for(int amount = Random.Range(0,4); amount-- > 0; ){
    Instantiate(item, position, Quaternion.identity);
}

```

This will loop 0 to 4-1 (AKA 3) times.

Alternatively you can write it as:

```
for(int amount = Random.Range(0,4); amount > 0; --amount){
    Instantiate(item, position, Quaternion.identity);
}

```

---
Tags: unity
---


title: Every Item is colliding but 1

text:
# Question
Title: Every Item is colliding but 1
In my game I have a *BULLET, MOONS, STARS, and A SHIP*. I shoot bullets from the ship and hit stars or moons and collisions occur. Yet when a moon runs into my ship there is no detection even though I set the a Collider for 2D on both of them.

```
    void OnCollisionEnter2D (Collision2D col) {
        Debug.Log (this.transform.tag);//moon hit ship not printing
        Debug.Log (col.transform.tag);//only bullet hit moons and stars
    }

```

Heres a quick snippet https://i.gyazo.com/acc0bbf5d2aab994db3a6598bfd206aa.mp4

# Answer
> 2 votes
So comparing bullet and player I learned bullet worked because it wasn't a trigger so I set my player object to not be a trigger and now it works, Im embarrassed Lol.

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


# Question
Title: How can I place prefabs into a world in Unity?
I've looked around for a bit and can't seem to find any way to get a prefab with "Resource.Load" and then to place that object into the world. I'm making a roguelike so when the player enters a room, all rooms around load in. The room to the top would load a random prefab from a list of rooms, check if there's already a room where it wants to go and then `PlacePrefab(transform.position, transform.position + 10units);` So it would place the prefab 10 units above where the current room is (All code for the rooms will run from a centre object and the prefab would be placed on the centre.)

Thanks in advance for any help :)

# Answer
Thanks to @DMGregory for helping :)

My code for doing this is:

```
newPrefab = Resources.Load("SizeTest", typeof(GameObject)) as GameObject;
Instantiate(newPrefab, new Vector3(transform.position.x - 8, transform.position.y - 5, transform.position.z), Quaternion.identity);

```

This loads a 16x10 prefab room above the current room. Change the numbers for where you want it to load. It loads off a middle or centre point where the code is attached to.

Something I didn't realise is that you need to make your files in a "Resources" folder. I thought "Resources" was the same as "Assets". Put everything in there and then the string in the `Resources.Load` is the file name (No extension)

Hopefully this can help someone doing something similar out :)
> 3 votes

---
Tags: unity, roguelikes
---


# Question
Title: SDL_Image setup problems on windows / mingw 64 / eclipse
I've been a software developer for a while, but I haven't done C++ in a long time and I thought I'd try it out with some game developement. I'm following the tutorial on youtube for Remaking Cavestory in C++ (great tutorial so far). I'm on Episode 4. I liked the sound of doing some 64 bit dev, so after a bunch of struggling I got SDL2 to work, scouring the internet and some trial & error I got it set up using the x86\_64 libraries with a MinGW-w64 installation. I opted not to copy lib and include files into mingw as suggested by some guides. Instead, I figured I could "point" eclipse at the proper folders and everything should work. This was true up until trying to integrate the SDL\_Image library. I have everything set up such that SDL.h is found by the compiler, and SDL\_image.h is found by the compiler. That is, the SDL.h and SDL\_image.h as referenced by my project code are fine. The problem is the compiler fails on SDL\_image.h because IT references SDL.h and that reference is apparently bad.

```
Windows 10 64 bit (pro I think, though I doubt it matters)
eclipse Neon.2 (4.6.2)
MinGW-w64 (I think 4.3.0)
SDL2 (2.0.5)
SDL_image (2.0.1)

```

Here's where all of my files are:

```
C:\MinGW-w64\mingw64
C:\MinGW-w64\mingw64\bin
C:\MinGW-w64\mingw64\include
C:\MinGW-w64\mingw64\lib
C:\MinGW-w64\mingw64\x86_64-w64-mingw32
C:\MinGW-w64\mingw64\x86_64-w64-mingw32\bin
C:\MinGW-w64\mingw64\x86_64-w64-mingw32\include
C:\MinGW-w64\mingw64\x86_64-w64-mingw32\lib

F:\Dev\SDL2-2.0.5\x86_64-w64-mingw32
F:\Dev\SDL2-2.0.5\x86_64-w64-mingw32\bin
F:\Dev\SDL2-2.0.5\x86_64-w64-mingw32\include
F:\Dev\SDL2-2.0.5\x86_64-w64-mingw32\lib

F:\Dev\SDL2_image-2.0.1\x86_64-w64-mingw32
F:\Dev\SDL2_image-2.0.1\x86_64-w64-mingw32\bin
F:\Dev\SDL2_image-2.0.1\x86_64-w64-mingw32\include
F:\Dev\SDL2_image-2.0.1\x86_64-w64-mingw32\lib

```

In eclipse I have the following configured:

**Project -\> Properties -\> C/C++ Build -\> Settings -\> Tool Settings -\> GCC C++ Compiler -\> Includes:**

```
"${workspace_loc:/cavestory-development/source/headers}"
"F:\Dev\SDL2-2.0.5\x86_64-w64-mingw32\include"
"F:\Dev\SDL2_image-2.0.1\x86_64-w64-mingw32\include"

```

**Project -\> Properties -\> C/C++ Build -\> Settings -\> Tool Settings -\> MinGW C++ Linker -\> Libraries:**

(top box: Libraries (-l))

```
SDL2
SDL2main
SDL2_image

```

(bottom box: Library search path (-L)

```
"F:\Dev\SDL2-2.0.5\x86_64-w64-mingw32\lib"
"F:\Dev\SDL2_image-2.0.1\x86_64-w64-mingw32\lib"

```

**Project -\> Properties -\> C/C++ General -\> Paths and Symbols -\> Includes -\> GNU C++:**

```
/cavestorye-development/source/headers
F:\Dev\SDL2-2.0.5\x86_64-w64-mingw32\include
F:\Dev\SDL2_image-2.0.1\x86_64-w64-mingw32\include

```

**Project -\> Properties -\> C/C++ General -\> Paths and Symbols -\> Libraries:**

```
SDL2
SDL2main
SDL2_image

```

**Project -\> Properties -\> C/C++ General -\> Paths and Symbols -\> Library Paths:**

```
F:\Dev\SDL2-2.0.5\x86_64-w64-mingw32\lib
F:\Dev\SDL2_image-2.0.1\x86_64-w64-mingw32\lib

```

I've also copied all of the DLLs from these two folders into my Debug (where my .exe is created)

```
F:\Dev\SDL2-2.0.5\x86_64-w64-mingw32\bin
F:\Dev\SDL2_image-2.0.1\x86_64-w64-mingw32\bin

```

When I build the project, I get the following error:

```
F:\Dev\SDL2_image-2.0.1\x86_64-w64-mingw32\include/SDL2/SDL_image.h:27:17: fatal error: SDL.h: No such file or directory

```

It seems that when the compiler looks at SDL\_image.h, it sees that THAT file includes SDL.h, which it can't find. Again, this worked when I was only including SDL2, and broke when I tried to include SDL2\_image because the image library references the normal library in a way that can't be reconciled.

Has anyone dealt with this before? Let me know if I've left out any pertinent information.

# Answer
> 1 votes
**The problem is** SDL\_image.h has `#include "sdl.h"` is because it's expecting two things, it's expecting it to be in the local directory because "" instead of \<\>, the latter would suggest it's expecting it's directory to be added `-Ilike/this` at compile time. The second thing it's expecting is that SDL.h shares a directory with SDL\_image.h, because `#include "sdl.h"` says search right where we are, for the file named such.

**To remedy the problem** the appropriate solution for SDL is to add the link and include SDL paths into your project, and with the SDL\_extension libraries, to copy the files directly into the matching directories of the SDL path. With SDL\_image this means copying SDL\_image.h into SDL-version-number/include(/SDL2 whether this is present depends on download, but the idea is it needs to be in the same folder as SDL.h). Then copy the SDL\_image .so/.a/.dll/etc. into the matching SDL-version-number/lib(/x86 or /x64 may be present depending on your download, but it needs to be in the same directory as sdlmain.a and sdl.a).

Any used functionalities that are additional sub-extensions of an SDL\_extension library are generally linked on their own, or linked directly by the SDL\_extension library, and you must determine their usage yourself, such as using PNG images. PNG images will be linked automatically because the PNG library was linked at the time of compiling SDL\_image, however libpng-some-version.dll and zlib-some-version.dll must be copied into your project binary folder yourself, and you simply determine which ones you need by what sort of image you're using (if you need jpegs, copy the jpeg.dll no additional linking or compilation flags required it's already done)

**Main Signature** The required main signature for SDL/SDL2 is:

```
int main( int argc, char *argv[])

```

`char **argv` is equivalent to `char *argv[]`, either may be used.

This issue is discussed here and other places, the fact that the tutorial writer's compiler allowed this usage is probably just a decision made by the compiler writers knowing that C++ SHOULD allow this usage, but doesn't.

For why the main signature has a macro making it be defined differently check here. It's not generally good practice, so don't copy this behavior ever, but SDL did it because it was written in C, and not too recently either.

---
Tags: windows, sdl2, eclipse, mingw
---


# Question
Title: Is it better to have object components in a variable than using GetComponent everytime? (Unity c#)
Is this:

```
Rigidbody2D rb = GetComponent<Rigidbody2D>();

void Update()
{
    rb.AddForce(transform.up * 20 * Time.deltaTime);
}

```

Better than this?:

```
void Update()
{
    GetComponent<Rigidbody2D>().AddForce(transform.up * 20 * Time.deltaTime);
}

```

And can you please tell me why?

# Answer
> 3 votes
Yes, caching component references is good for performance. `GetComponent<>` involves a search through the object's components for the one you want, so if you already have a reference to it then you can skip the search.

But it doesn't work quite the way you've written it.

```
Rigidbody2D rb = GetComponent<Rigidbody2D>();

```

As a field initializer, we're not allowed to reference non-static methods of the class we're constructing, so this will generate a compile error. (Generally, you should avoid doing much in these initializers in Unity - they run on a separate loading thread so they're limited in what they're allowed to touch)

Instead, you'd want to do this in `Start`, or optionally `Awake`/`OnEnable` if you need it sooner.

```
// If our code is going to assume there's an RB attached,
// let's make that assumption explicit so the editor can enforce it.
[RequireComponent(typeof(Rigidbody2D))]
public class MyPhysicsScript : MonoBehaviour {

    // Cache a reference to our attached Rigidbody on startup.
    Rigidbody2D _rb;

    void Start() {
        _rb = GetCoponent<Rigidbody2D>();
    }

    // Physics code can now reference the Rigidbody without
    // repeatedly searching for it every frame.
    void FixedUpdate() {
        // Code that uses _rb goes here.
    }
}

```

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


# Question
Title: Reason for white lines in tile-based game
My game is tile-based. I am getting this lines between two tiles. They don't look nice. How can i resolve this issue?

# Answer
These lines are caused by the interpolation in the texture sampler which samples texels from adjacent tiles in your tile atlas.

Both bilinear and trilinear (mipmaps) interpolation (and some rounding errors within the GPU) will cause this.

You need to add a border to your tiles consisting of N repeating pixels from your tiles on all sides & corners.

For example:

Where N is 2 to the power of (mipmap levels).

So if you want 3 mipmap levels you need to add a border of 8 pixels (1 \<\< 3) all around your tiles in your atlas to ensure the texture sample will not sample texels from adjacent tiles.

You also need to limit the mipmap level by calling `glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, max_mipmap_level);`

The first level is 0, level 1 is (width/2, height/2), level 2 is (width/4, height/4), and so on.
> 5 votes

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


# Question
Title: Non-real time simulation of overlapping repulsive balls
I want to make a non-real time simulation of overlapping repulsive balls, initially in 2D and later in 3D. With "non-real" I mean that rendering is not needed after each time step.

First of all, consider a simple closed domain for simplicity. In practice, domains will be complex and irregular but always closed.

The balls on the boundaries are fixed and could be overlapping. A fixed ball duplicates itself to produce a free ball of the same size whenever no other ball overlaps it. Both fixed and free balls repel each other but fixed balls cannot move. Note that, duplicant ball should be sufficiently tilted to start repulsion. In elastic colliding balls case, after two balls collide they change direction with some velocity but in this case the balls can stop quickly once they stop overlapping. Free balls move until there is no motion or let's say we solve motion problem until convergence. Then each fixed ball produce a free ball again and this process goes on until no fixed ball can duplicate due to being overlapped by any other ball(s).

I think GPU (CUDA) would be faster to solve this problem but initially I am thinking to write on CPU. However, before proceeding to coding I would like to know "feasibility" of this work. That is, considering a million of balls, approximately how long it would take to simulate this or similar kind of problems in non-real time. For a million of balls, if solution time is in order of minutes, I will dive into the problem. So, my question to experienced programmers is that approximately how long it takes to simulate this kind of problem for a millions of variables? Is it in order of seconds, minutes or hours?

# Answer
It would be on the order of seconds for CPU-based code, and much faster for GPU-based code. I have two sources of experience for this.

The first, writing gravitational simulations (force-based repulsion, exact intersection resolution. As you can see I got much farther with force-based repulsion!). Because this is a sparse problem, for short-ranged collision detection, I use a hash table. Particle positions are mapped to a pair of integers (a,b), and the hash table looks up lists of particles from pairs of integers. There are a million particles in one of the linked videos, and doing the force calculation on a single thread (including the much more expensive gravitational calculations!) took three to four seconds, if I recall correctly.

The second, writing statistical simulations of rigid disk phase transitions. See image below for what I'm talking about. In this case, the disks are densely packed and so a hash table makes no sense. You might as well just create a grid to store the particles in. Every grid would point to an array of pointers to particles (so that if multiple disks lie in a single grid cell, they can be properly handled). Again looking up adjacent disks is easy: just look at the adjacent array indices. The avoidance of mutual intersection of any two disks can be assured much more easily than in what you want to do: You START in a valid configuration where no two disks intersect. Then you choose one disk, and move it randomly in the x,y directions. If the new position intersects any disks, you move it back to where it was. If it doesn't, you leave it. Repeating this millions of times (which can be done very quickly because of the quick collision detection) gives the random images you see below. I would expect single threaded CPU performance for this kind of code for a million particles to be around a second, maybe less (for proposing and checking a new random move for each of a million particles). For reference, this approach is called a "Markov Monte-Carlo approach".

(see Werner Krauth's faculty webpage, his book, or his Coursera course for more. The idea is that as the density of nonintersecting disks increases, there is a phase transition from short-range order \[liquid\] to infinite-range order \[solid\] at a critical temperature \[rather, critical density\].)

To detect collisions, just check if the distance between two adjacent circles is less than the sum of their radii. (if d

To handle collisions between two movable particles, if your particles are at positions x1 and x2, the algorithm I used for the "exact intersection resolution" video above was like this:

```
Vector x1, x2; //assuming we have a vector class all written.
double d=(x1-x2).lengths();//calculate sqrt((x1.x-x2.x)^2+(x1.y-x2.y)^2) and store it in d.
if(d<2*r){ //if the distance is less than the sum of the radii, there is a collision
   Vector direction=(x1-x2).normalized(); //assuming "v.normalized" returns the unit vector in the direction of v
   Vector center=(x1+x2)*0.5; //average position of the two circles
   x1=center+direction*r; //move it to +r along the axis of collision
   x2=center-direction*r; //move it to -r along the axis of collision
}

```

The problem is that in resolving the collision between TWO particles, we may have introduced collisions of either one of the particles with some third particle. You can see this problem in the "exact intersection resolution" video! That is why I prefer force-based methods.

If your goal is just to generate pictures/distributions like Krauth's above, use the Monte Carlo approach. If you MUST use the algorithm in your OP, I would really really suggest a physics based approach (ie, storing a position and velocity and applying a strong spring repulsion force, then updating for many timesteps dt). Going from a valid configuration of particles to a valid configuration of particles is easy (Monte Carlo). Going from an invalid configuration of intersecting particles to a valid configuration is hard, impossible in some cases, and is best solved by using a physics force-based approach.
> 1 votes

---
Tags: c++, simulations, cuda
---


# Question
Title: If I want to create a top-down 2D game should I rotate the camera?
Do I have to rotate the camera to top-down view if I want to crate a top-down 2D game or just disable gravity?

# Answer
You can do *whatever you want*.

---

That said, it is worth considering *standards*. Picture your game space as a 2D grid. If you retain the default camera angle, you would be working along the *X* and *Y* axis. If you rotate your camera to a down-facing position, you would be working along the *X* and *Z* axis.

*I* would say "leave the camera the way it is"; it is far more conventional to refer to a position on a 2D plane as "X, Y". While you could easily portray coordinates as "X, Y" to the *user*, you still have to work in "X, Z", *yourself*. Any built in methods that apply to two-dimensional coordinates will also *assume* use of "X, Y", including the directional vectors housed in the `Vector2` class.

Why add another layer of complexity to your project? Use the "X, Y" plane, and stick to 2D standards.
> 0 votes

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


# Question
Title: Creating a 3rd Person Flying Camera for 3D asteroids game
In order to learn PyOpenGL and test out an engine I am developing, I am trying to write a 3D asteroids flying space shooter game. Currently, I am implementing the camera using a "look at" function positioned right behind the player's ship. The player is able to control the yaw and pitch with the left+right and up+down arrow keys respectively. The results look like this (forgive the placeholder art):

And here is the code snippet in my `Player` class that implements that:

```
from pyorama.entity import Entity
from pyorama.math3d.vec3 import Vec3
from pyorama.math3d.mat4 import Mat4
import math

class Player(Entity):

    def __init__(self, model, camera):
        self.model = model
        self.center = self.model.mesh.compute_bounding_sphere().center
        self.model.transform = self.model.transform.translate(-self.center)
        self.camera = camera
        self.key_down_status = {"Left": False, "Right": False, "Up": False, "Down": False}
        super(Player, self).__init__()

    def update(self):
        messages = super(Player, self).update()
        for message in messages:
            if message.event_type == "key_down":
                key = message.data["key_name"]
                if key in self.key_down_status.keys():
                    self.key_down_status[key] = True
            if message.event_type == "key_up":
                key = message.data["key_name"]
                if key in self.key_down_status.keys():
                    self.key_down_status[key] = False

        self.model.transform = self.model.transform.translate(self.center)
        if self.key_down_status["Up"]:
            self.model.transform = self.model.transform.rotate_x(-0.01)
        if self.key_down_status["Down"]:
            self.model.transform = self.model.transform.rotate_x(0.01)
        if self.key_down_status["Left"]:
            self.model.transform = self.model.transform.rotate_y(0.01)
        if self.key_down_status["Right"]:
            self.model.transform = self.model.transform.rotate_y(-0.01)
        self.model.transform = self.model.transform.translate(-self.center)
        self.model.transform = self.model.transform.translate(Vec3(0, 0, 0.1))

        right = self.model.transform.data[0:3]
        up = Vec3(*self.model.transform.data[4:7])
        forward = Vec3(*self.model.transform.data[8:11])
        position = Vec3(*self.model.transform.data[12:15])

        temp = self.model.transform
        self.model.transform = self.model.transform.translate(+self.center)
        right = self.model.transform.data[0:3]
        up = Vec3(*self.model.transform.data[4:7])
        forward = Vec3(*self.model.transform.data[8:11])
        position = Vec3(*self.model.transform.data[12:15])

        self.camera.view = Mat4.look_at(position - 20 * forward, position, up)
        self.model.transform = temp

```

As you can see, the ship stays perfectly still behind and the world rotates around. As a result, it looks very unnatural, as if a 2D ship sprite was simply glued onto the screen!

So my question is, how are third-person cameras in flying games typically implemented? What would a keyboard+mouse control scheme look like that controls yaw, pitch, roll, banking, acceleration/deceleration, etc? Would the camera controls for the camera be separated from moving the ship? Any help would be greatly appreciated.

# Answer
> 1 votes
The camera control is usually semi-separated from the ship's rotation. Instead of making the camera have the same angles as the ship, the camera should try getting closer to the ship's angles.

In your update method get the difference between the ship's angles and the camera's angles, multiply it with a value between 1 and 0 (The greater the value is, the faster the camera will follow the ship) then add it to the camera's angles.

---
Tags: opengl, 3d, camera, python
---


# Question
Title: Coding different states in Adventure Games
I'm planning out an adventure game, and can't figure out what's the right way to implement the behaviour of a level depending on state of story progression.

My single-player game features a huge world where the player has to interact with people in a town at various points in the game. However, depending on story progression, different things would be presented to the player, for e.g. the Guild Leader will change locations from the town square to various locations around the city; Doors would only unlock at certain times of the day after finishing a particular routine; Different cut-screen/trigger events happen only after a particular milestone has been reached.

I naively thought of using a switch{} statement initially to decide what the NPC should say or which he could be found at, and making quest objectives interact-able only after checking a global game\_state variable's condition. But I realised I would quickly run into a lot of different game states and switch-cases in order to change the behaviour of an object. That switch statement would also be massively hard to debug, and I guess it might also be hard to use in a level editor.

So I thought, instead of having a single object with multiple states, maybe I should have multiple instances of the same object, with a single state. That way, if I use something like a level editor, I can put an instance of the NPC at all the different locations he could ever appear at, and also an instance for each conversation state he has. But that means there'll be a lot of inactive, invisible game objects floating around the level, which might be trouble for memory, or simply hard to see in a level editor, i don't know.

Or simply, make an identical, but separate level for each game state. This feels the cleanest and bug-free way to do things, but it feels like massive manual work making sure each version of the level is really identical to each other.

All my methods feel so inefficient, so to recap my question, is there a better or standardised way to implement behaviour of a level depending on state of story progression?

PS: I don't have a level editor yet - thinking of using something like JME SDK or making my own.

# Answer
> 9 votes
I think what you need in this case is the State Design Pattern. Instead of having multiple instances of each game object, create a single instance, but encapsulate its **behavior** in a separate class. Create multiple classes, one for each possible behavior, and give all classes the same interface. Associate one to your game object (the initial state) and, when conditions change (a milestone is reached, the time of the day passes, etc) you switch that object's state (i.e. associate it with a different object depending on your game logic) and update its properties if applicable.

One example of how a state interface would look like (completely made up - just to illustrate the level of control this scheme gives you):

```
interface NPCState {
    Scene whereAmI(NPC o);
    String saySomething(NPC o);
}

```

And two implementing classes:

```
class Busy implements NPCState {
    Scene whereAmI(NPC o) {
        return o.getWorkScene();
    }
    String saySomething(NPC o) {
        return "Can't talk now, I'm busy!";
    }
}

class Available implements NPCState {
    Scene whereAmI(NPC o) {
        return TAVERN;
    }
    String saySomething(NPC o) {
        String[] choices = o.getRandomChat();
        return choices[RANDOM.getInt(choices.length)];
    }
}

```

And switching states:

```
// The time of day passed from "afternoon" to "evening"
NPCState available = new Available();
for ( NPC o : list ) {
    Scene oldScene = o.state.whereAmI(o);
    o.state = available;
    Scene newScene = o.state.whereAmI(o);
    moveGameObject(o, oldScene, newScene);
    ...

```

Important NPCs may have their custom states, the state choosing logic may be more customizable, and you can have different states for different facets of the game (in this example, I used a single class to tell both location and chat, but you could separate them and do many combinations).

This works well with level editors too: you can have a simple combo box to switch the "global" state of a level, then add and reposition the game objects as you want them to appear in that state. The game engine would be responsible for only actually "adding" that object to the scene when it has the correct state - but its parameters would still be editable in an user-friendly way.

(Disclaimer: I have little real-world experience with game editors, so I can's say with confidence about how professional editors work; but my point about the State Pattern still holds, organizing your code this way should be clean, maintainable and not waste system resources.)

# Answer
> 2 votes
The choices I would consider are either making the individual objects respond to different gamestates, or serve up different levels in different gamestates. The choice between those two would depend on what exactly I am trying to do in the game (what are the different states? how will the game transition between states? etc.)

Either way however I wouldn't do it by hard-coding the states into the game code. Rather than a massive switch statement in NPC objects, I would instead of the NPC behaviors loaded into an associative array from a data file and then use that associative array to run different behavior for their associated states, something like this:

```
if (state in behaviors) {
  behaviors[state]();
}

```

# Answer
> 2 votes
What about using a observer pattern to look for milestone-changes? If a change happens, some class would recognize this and handle for example a change that has to be done to a npc.

Instead of the mentioned state design pattern I would use a strategy-pattern.

If a npc has n ways to interact with the character and m positions where he could be, there is a maximum of (m\*n)+1 classes you have to design. Using the strategy-pattern you would end up with n+m+1 classes but these strategies could also be used by other npcs.

So there could be a class handling the milestones, and classes who observe this class and handle either npc or enemies or whatever should be changed. If the observers get updated they would decide if they have to change something to the instances they rule. The NPC class for example would, in the constructor, inform the NPC-Manager when he has to be updated and what has to be updated...

# Answer
> 0 votes
All of the approaches given are valid. It depends on the situation you are in at any given moment. Many adventures or MMOs use a combination of these.

E.g. if a pivotal event changes a large part of the level (e.g. a debt collector cleans out your apartment and everyone in it gets arrested), it is usually easier to replace the entire room with a second room that just looks similar.

OTOH, if characters walk around the map and do different things in different places, you often have a single actor that rotates through different behaviour objects (E.g. walk straight ahead/no conversations vs. stand here/conversation about Mitch's death), which might include "hidden" if their purpose has been fulfilled.

That said, usually having duplicates of an object that you create manually should not cause any problems. How many objects can you create? If you can create more objects than your game can loop over, look at their "hidden" property and skip, your engine is too slow. So I wouldn't worry about that too much. Many online games actually do this. Certain characters or items are always there, but are not displayed to characters who do not have the corresponding mission.

You can even combine the approaches: Have two doors in your apartment building. One leads to the "before the debt collector" apartment, one to the apartment after. When you enter the corridor, only the one that applies to your progression in the story is actually shown. That way, you can just have a generic mechanism for "item is visible at current point in story" and a door with a single destination. Alternately, you could make more complicated doors that can have behaviours that can be swapped out, and one of them is "go to full apartment", the other "go to empty apartment". This may seem nonsensical if really just the door's destination changes, but if its appearance changes as well (e.g. a big lock in front of the door that you first have to crack), this may be a better approach than replacing the entire corridor as well.

---
Tags: adventure-games
---


# Question
Title: How could I render a star like those in Elite Dangerous - coronas and some sort of 3D "plasma" effect on the surface?
Lets assume I wish to render a large, 3D, star object in a game engine using OpenGL. I can use a few different meshing methods: this includes mapping a cube to a sphere (with better subdivision to reduce distortion), a primitive lattitudional/longitudional based "globe" mesh, or a selectively subdivided icosphere. I would choose whatever would be easiest to apply the 3D effect to: I'm guessing an isocahedron, since it doesn't distort as much and the issues with mathematical discontinuities (when finding the Tangential, Normal, and Binormal) vectors should not be a worry (unless rendering the following effect would use a bump/normal mapping technique with a GPU-generated texture?)

Further, lets assume I wish to render a boiling, roiling, or vaguely evolving surface. The diamond-square algorithm could generate the proper effect, but how could this be used in 3D to generate something that looks vaguely like the surface of a star? Could I use the GPU to generate a texture that is then evolved with time, and use a procedural noise algorithm that includes the analytical derivatives to do so(for acquiring normal/bump map components to add "depth")? Should the noise algorithm be in 2D or 3D?

Lastly, what if I want to render the corona of the star in some volumetric fashion as well? Corona's created with billboards work well enough, but rapidly fall apart in appearance once the viewpoint gets closer to the star (as is common with sprite-based techniques).

Example images:

# Answer
The texture can be achieved by using a 3d noise, like simplex noise. If you can, use a multi octaved noise (it makes the texture look rougher).

Get the current coordinate of the fragment relative to the center of the sphere, and get the noise value with this 3d vector. Once you have the value, blend it with the star's color.

The coronas on the image are probably just arc shaped meshes with a texture on them.
> 2 votes

---
Tags: opengl, c++, rendering, graphics-programming, procedural
---


# Question
Title: How to display distance between Player and object in UI text? Unity 5.5
I am an beginner in Unity, with no experience in scripting. Can someone help me with a script to display distance between Player and object in UI text? Using Unity 5.5, the scene is quite simple just one room with the third person character moving around the object (CT scan). Thanks. Alex

# Answer
As @csisy pointed out, it's better to make **a few** researches before asking a question. Especially for basic stuff like : computing a distance between two points and displaying a text on the screen.

I haven't tested the following code :

```
using UnityEngine ;
using UnityEngine.UI ;

public class DistanceVisualiser : MonoBehaviour
{
    // Drag & Drop the player gameobject using the inspector
    public Transform objectA ;

    // Drag & Drop the other object
    public Transform objectB ;

    // Drag & Drop the gameobject, child of a Canvas holding a Text component
    public Text UIText ;

    // Use LateUpdate to compute the distance **after** the player / object has moved
    private void LateUpdate()
    {
        UIText.text = Vector3.Distance( objectA.position, objectB.position ).ToString();
    }
}

```
> 3 votes

---
Tags: unity, 3d
---


# Question
Title: How to add the concept of entities and components into an isometric tile map?
To get some practice with SpriteKit, entities and components I built a little demo.

I created a `SKNode` subclass (`IsometricMapNode`) which renders an isometric map. It does so by adding `SKSpriteNode` (`TileSpriteNode`) subclasses to itself.

The data of the map is stored in a platform agnostic class `IsometricMap` which manages `IsometricLayer`s and `Tile` objects. The map can do things like loading a TMX file and generate tiles which carry information (type of tile, texture name, ...).

The map is then passed to aforementioned `IsometricMapNode` and displayed.

All is working fine but then I read about `GKEntity` and I wonder if I can introduce the concept of entities into my code. I was wondering if every tile in my map should be an entity which would then get a render component and maybe a physics component or a particle component.

What I don't understand though: Would my model class `Tile` become a `GKEntity`, or its visual cousin `TileSpriteNode`? Or is it just philosophical?

If `Tile` is the entity, users of my map would add new entities to it, hopefully with a render component attached to them.

If I keep my `Tile` model class, the map would internally create entities *from* this class, add some standard components (mainly rendering) and allow the user to change those components later.

Is this making sense at all? :-)

# Answer
Note: I've never used SpriteKit, so the below answer is agnostic. Someone else may be able to provide a SpriteKit specific answer.

There are many other questions here that discuss what an Entity-Component design paradigm is, so I'm going to be intentionally brief in that part of the explanation:

* The entity is an identifier - in a lot of systems, the class just wraps what essentially boils down to an integer
* The components decide what the entity "is" - do I have a position? Am I renderable? Does the player control me? etc.

Whether your map is tile based doesn't change this a whole lot.

While you -could- make every tile into an entity, and assign a position+render component to each one, you may find it better to let your tilemap renderer render any cosmetic tiles on it's own, without assigning entities/components. Entities/Components are generally most useful when you have something that affects gameplay logic - a spike trap, a breakable object, a pickup, a turret.

Regardless of whether you make all of your tiles into entities, or just specific ones, your entity should likely have a component that references the Tile object that the tilemap controls, as opposed to holding the Tile itself.

The tilemap renderer itself shouldn't know, or care, that you want to render the Tile because it's part of an entity. You'd just want to add code that manages the creation/destruction of those objects if you encounter an entity that has a Render component.

In an ECS setup, this would be handled by a Render system, that processes the components, and interfaces with the map renderer to create/destroy tiles based on the components set up for the entities.

The map renderer isn't "really" part of the Entity System itself, all the map renderer cares about is, "oh, I have a list of tiles, better render them".
> 1 votes

# Answer
I would say that tiles are not entities. You can think of Entities as things that are added to your scene e.g. The Player, Enemies, Obstacles, Collectibles etc. These are objects in your game that have functionality that can be modelled with components.

Tiles are not like objects. They don't have functionality, though they may have metaData e.g. in SpriteKit you can have userData associated with tiles, but this userData applies to all tiles of that type.

Another point to note is not to forget about the System part of Entity Component System. It's overlooked in most examples I see. In SpriteKit you can inherit from `GKComponentSystem<GKComponent>` to create your own systems.

`Entity`: Just a number. Nothing else.

`Component`: Which is just data. Nothing else.

`System`: This is where the logic sits.
> 1 votes

---
Tags: tiles, entity-system
---


# Question
Title: How import and draw a tiledmap with slick2d
How I can import and draw a tilemap with different layers? I have the next code and send me error if the tilemap have more than one layer.

```
public class Map {

    private TiledMap map = null;

    private int bg,level,extras;

    public void init(GameContainer container) throws SlickException {

        map = new TiledMap("assets/levels/default.tmx", false);

    }

    public void render(int type, GameContainer container, Graphics g) {

//      map.render(0, 0, 0, 0, 19, 13);

    }

    public void update(GameContainer container, int delta) {}

}

```

I was thinking to save each layer in a different variable for later draw each layer. But Im not sure how I can do it. I have been looking for tutorials, and the slick2d API. And this is the error.

```
Fri Feb 06 22:18:30 GMT 2015 ERROR:For input string: ""
java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at org.newdawn.slick.tiled.TiledMap$ObjectGroup.<init>(TiledMap.java:1008)
    at org.newdawn.slick.tiled.TiledMap.load(TiledMap.java:688)
    at org.newdawn.slick.tiled.TiledMap.<init>(TiledMap.java:106)
    at gameEngine.Map.init(Map.java:54)
    at states.Play.init(Play.java:26)
    at org.newdawn.slick.state.StateBasedGame.init(StateBasedGame.java:171)
    at org.newdawn.slick.AppGameContainer.setup(AppGameContainer.java:393)
    at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:317)
    at gameEngine.Main.main(Main.java:31)
Fri Feb 06 22:18:30 GMT 2015 ERROR:Failed to parse tilemap
org.newdawn.slick.SlickException: Failed to parse tilemap
    at org.newdawn.slick.tiled.TiledMap.load(TiledMap.java:695)
    at org.newdawn.slick.tiled.TiledMap.<init>(TiledMap.java:106)
    at gameEngine.Map.init(Map.java:54)
    at states.Play.init(Play.java:26)
    at org.newdawn.slick.state.StateBasedGame.init(StateBasedGame.java:171)
    at org.newdawn.slick.AppGameContainer.setup(AppGameContainer.java:393)
    at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:317)
    at gameEngine.Main.main(Main.java:31)
Caused by: java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at org.newdawn.slick.tiled.TiledMap$ObjectGroup.<init>(TiledMap.java:1008)
    at org.newdawn.slick.tiled.TiledMap.load(TiledMap.java:688)
    ... 7 more

```

# Answer
You should probably be using LibGDX. Slick2d is no longer under active development. I had the same problem, and it was solved by switching to LibGDX, which has an updated version of the Tiled Map support classes that were started in Slick2d.
> 1 votes

# Answer
I found a discrepancy between the Tiled Map Editor and the nature of the int data type. When in an object layer, you must make sure each of the objects have no decimal values, either in their width, height, X, or Y location. Because an int cannot support decimal values (you could edit slick's code to support a double data type if you needed a decimal value) the parseInt method throws that error. The simple fix I did was to make sure all of those values were in increments of my tiles, which also fixed the problem.
> 0 votes

---
Tags: tilemap, slick
---


# Question
Title: If there is possibility to use two or more activities in gdx?
I wanted to open another activity or show native android dialog from AndroidLauncher in gdx. But when I add MyActivity and MyDialog classes, there is an error "Error: The number of method references cannot exceed 64K". But when I delete this classes everything works fine. Is there a way to open another activity in LibGDX game?

# Answer
You need to use add a `Multidex` support to exceed the 65k methods limit. Here's a guide to integrate `Google Play` with `GDX`. Search in there for the 'DEX' part and apply it to your project.

https://chandruscm.wordpress.com/2015/12/30/how-to-setup-google-play-game-services-in-libgdx-using-android-studio/

You'll be fine!
> 1 votes

---
Tags: android, libgdx
---


# Question
Title: Networking problems when sending textures from the server
When a client connects to my game server, the server sends textures and then the world information.
The problem is that the texture information may come after the world information and so the client errors out because it has no texture to give the models.

How would I combat this?

# Answer
Don't send asset data during game-play sessions.

Either use a launcher to make sure that the game assets are up to date with what's on the server before the game starts, or do the download process in a loading screen.

In both cases, I suggest you use two different servers: one from which the game clients will download the assets, and one that will be used to process the actual game-play.

Otherwise, I suggest you re-think your game design: make the image not mandatory to continue the game-play, like a player guild icon, or a decorative hat.

Textures are generally much bigger to send over the network than your usual game packets. So it would be easy for a small group of players who know *when* the assets are sent in game to create a situation where too many assets are sent at once to the clients, and make your server slow down to a crawl because it's busy sending images to 50% of your players, not having time to process the actual game, and send actual game packets. Like a DDOS attack. (This has happened before.)
> 3 votes

# Answer
That's what a loading screen is for, to buy you time until you have the assets in place for rendering, also you can probably use placeholder assets or lower detail assets (that will download faster) for a lot of the assets you are dynamically downloading this way.

However you shouldn't make the game server send the textures instead have a load balanced asset server cluster.

That way when the game server sends "you need asset pack 5" and the client can then check its own cache and if it's not there go to the asset server and say "give me asset pack 5" and start downloading it.
> 1 votes

---
Tags: libgdx, networking
---


# Question
Title: Delta compressed world state when networking in JavaScript
Lets say we send a snapshot from the server to the clients about world details, containing object positions, velocities etc, every second. We should send only delta-data based on the previous snapshot that was sent.

For example, if the player moved from `(x:50, y:0)` to `(x:100, y:0)`, then the snapshot will only contain `(move_x:50: move_y:0)`, and the clients will add the previous position and `move_x`. We should sending delta values, as it is less data to send.

---

How do I achieve this in Javascript?

My objects already have data stored in `Float32` (by `TypedArray`) and there is no `Float16` data type in JavaScript.

For example:

```
delta = currentPos - prevPos
20 = 100 - 80

```

okey, now I have 20 instead of 80, but this isn't less data to send.. still both will be send as Float32.

```
data.writeFloat32(delta); //for simplesness

```

there is no Float16 and I am afraid that even if JS will has Float16 TypedArrays, then it still would be not enough, because for example 20.3454356 from Float32 to Float16 will lose precision to lets say sth like 20.34, or I'm wrong?

How to send delta data in JS and gain the benefits of this technique in JS?

# Answer
> 3 votes
I think you misunderstood what people mean when they say that you should only be sending deltas in your netcode.

The message is about sending data *when* it changed. It means that when the player isn't moving, you don't keep sending the same position every frame. You only send position updates when the player is moving. It's not saying anything about whether you send absolute position updates (the new coordinates) or relative position updates (the difference between new and old positions).

Relative movement coordinates usually require a far smaller number-range than absolute coordinates. That means truncating the data-type you use for relative position updates can save a few bytes of network traffic. But **only when you use integer-coordinates!**

You have recognized correctly that it is a much worse idea with floating-point values. When you use 16bit instead of 32bit or 64bit floats, you aren't just losing range, you are mostly **losing precision**!

But even when you are dealing with floating point values with uniform precision, keep in mind that floating-point arithmetics are always a bit fuzzy. When you only send differences and never absolute positions, these imprecisions are going to accumulate. This effect will get worse with less precise floating-point values, but they even occur with high-precision floats. So you might still want to send an absolute update from time to time to re-synchronize.

If you still want to go down this route, I would recommend you to encode your position differences in Int16 by multiplying them with your desired precision factor while encoding and then dividing them again by the same value when decoding. That way you retain complete control over the tradeoff between range and precision.

---
Tags: javascript, networking, precision
---


# Question
Title: Audio Source object reference not set to instance of an object in Unity.
I have the following script:

```
public class soundcontrol : MonoBehaviour {
    AudioSource theaudio ;
    public AudioClip clip1;
    public AudioClip clip2;
    public AudioClip clip3;
    AudioClip[] cliparray;
    int currentclip = -1;
    int maxclip = 0;
    bool isclip1null = false;
    bool isclip2null = false;
    bool isclip3null = false;

    // Use this for initialization
    void Start () {
    }

    // Update is called once per frame
    void Update () {
        maxclip = 0;
        if (clip1 != null) {
            isclip1null = true;
            cliparray [maxclip] = clip1;
            maxclip = maxclip + 1;
        }
        if (clip2 != null) {
            isclip2null = true;
            cliparray [maxclip] = clip2;
            maxclip = maxclip + 1;
        }
        if (clip3 != null) {
            isclip3null = true;
            cliparray [maxclip] = clip3;
            maxclip = maxclip + 1;
        }
        if (!theaudio.isPlaying) { // the error is here
            if (!((maxclip - 1) == -1)) {
                currentclip = currentclip + 1;
                if (currentclip > maxclip) {
                    currentclip = 0;
                }
                if (!((maxclip - 1) == -1)) {
                    theaudio.PlayOneShot (cliparray [currentclip]);
                }
            }
        }
        if ((maxclip - 1) == -1) {
            Debug.Log (" no clip attached ");
        }
    }
}

```

The error was at `theaudio.isPlaying` checking, the method I use is the same as what's in the documentation.

So, why is this thing happening? The documentation is just too bad to be understood (they can use that magic while I can't).

I also have audio source attached.

I'm a beginner with Unity so before you guys downvote please help me solve my problem first, and I'm sorry if this has already been asked somewhere, Google just seems to not give me the answer I want :\

# Answer
> 2 votes
The error *"object not set to an instance of an object"* means that you're trying to use an object that is null (NullReferenceException). When you get that error, the first thing to do is to isolate *which* object/access is generating the error, then to trace back if that object is effectively initialized, and then make sure it's properly initialized before using it.

There is a more complete explanation on StackOverflow.

In your specific case, you need to initialize the `audioSource` object before you can use it.

The documentation about the method you're trying to use is quite explicit on how you do that: you set up the `audioSource` in the `start` function by getting the appropriate component.

```
// When the audio component has stopped playing, play otherClip
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public AudioClip otherClip;
    AudioSource audio;

    void Start() {
      audio = GetComponent<AudioSource>();
    }

    void Update() {
        if (!audio.isPlaying) {
            audio.clip = otherClip;
            audio.Play();
        }
    }
}

```

---
Tags: unity, audio
---


title: Collision using Tilemaps

text:
# Question
Title: Collision using Tilemaps
How do I get the player in a platformer to collide with tiles My code for my for loop is

```
        for(var i = 0; i < game.map.length; i++) {
        for(var j=0; j < game.map[i].length; j++) {

            if(game.map[i][j] === 2) {
                drawImage(game.backgroundContext, game.images[0], game.x, game.y, 50, 50);
            }
            if(game.map[i][j] === 1) {
                drawImage(game.backgroundContext, game.images[1], game.x,game.y,50,50);
            }
            if(game.map[i][j] === 0) {
                game.backgroundContext.fillStyle = "#14FFDA";
                game.backgroundContext.fillRect(game.x, game.y, 50, 50);
            }
            game.x += 50;
        }
        game.x = 0;
        game.y += 50;
    }

```

I was thinking to put

```
        if(game.player.y >= game.y && game.player.y <= game.y+height) {
            game.player.falling = false;
        } else {
            game.player.falling = true;
        }

```

inside one of the if its equal to one (0 = background 1=floor)

Anyone have the annswer

**Edit** Image  (The player goes through the bricks)

**Edit** Due to downvotes nobody gets the bounty If it gets back to 0 downvotes I will give the bounty away

# Answer
There is something pretty strange in your code.

Your `game` has `x` and `y` attributes and you increment them in order to draw your scene. You then use the same `game.x` and `game.y` in your collision detection code, that does not make sense.

First of all you could just change your loop like this

```
for(var i = 0; i < game.map.length; i++) {
    for(var j=0; j < game.map[i].length; j++) {

        if(game.map[i][j] === 2) {
            drawImage(game.backgroundContext, game.images[0], j * 50, i * 50, 50, 50);
        }
        if(game.map[i][j] === 1) {
            drawImage(game.backgroundContext, game.images[1], j * 50, i * 50,50,50);
        }
        if(game.map[i][j] === 0) {
            game.backgroundContext.fillStyle = "#14FFDA";
            game.backgroundContext.fillRect(i * 50, j * 50, 50, 50);
        }
    }
}

```

Which allows you to get rid of these `game.x` and `game.y`.

Then concerning collision detection, you should parse all the `brick` tiles and check if `player.y + player.height >= brick.y` (in canvas y = 0 is on top of the screen). That means somewhere you should stock the brick elements.

This might look like this

```
detectCollision()
{
     falling = true;
     for (brick in bricks)
     {
         if (player.y + player.height >= brick.y)
         {
             falling = false;
             break;
         }
     }
}

```

If the floor is supposed to be linear all way long, you can make it even more simple. Just store the y position of the floor and check if `player.y + player.height >= floor.y` only once.
> 1 votes

---
Tags: tiles, tilemap, maps
---


# Question
Title: Möller-Trumbore false positive result in specific point
I copied code from this whitepaper and i can't figure out while it gives me false-positive intersections.

Here's problematic values:

Triangle points: (100.0, 100.0, 100.0), (-100.0, 100.0, 100.0), (-100.0, 100.0, 50.0);

Ray origin point: (0.0, 98.0, 50.0);

Ray direction point: (-100.0, 5.88235, 73.5294).

This points gives me an intersection when it shouldn't.

Here's my implemetation:

```
#include <iostream>
#define EPSILON 0.000001
#define CROSS(dest, v1, v2) \
    dest[0] = v1[1] * v2[2] - v1[2] * v2[1]; \
    dest[1] = v1[2] * v2[0] - v1[0] * v2[2]; \
    dest[2] = v1[0] * v2[1] - v1[1] * v2[0];

#define DOT(v1, v2) (v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2])
#define SUB(dest, v1, v2) \
     dest[0] = v1[0] - v2[0]; \
     dest[1] = v1[1] - v2[1]; \
     dest[2] = v1[2] - v2[2];

int intersect_triangle(double orig[3], double dir[3],
                    double vert0[3], double vert1[3], double vert2[3],
                    double *t, double *u, double *v) {
    double edge1[3], edge2[3], tvec[3], pvec[3], qvec[3];
    double det, inv_det;

    // find vectors for two edges sharing vert
    SUB(edge1, vert1, vert0);
    SUB(edge2, vert2, vert0);

    // begin calculating determinant - also used to calculate U parameter
    CROSS(pvec, dir, edge2);

    // if determinant is near zero, ray lies in plane of triangle
    det = DOT(edge1, pvec);

    if (det > -EPSILON && det < EPSILON)
        return 0;
    inv_det = 1.0 / det;

    // calculate distance from vert to ray origin
    SUB(tvec, orig, vert0);

    // calculate U parameter and test bounds
    *u = DOT(tvec, pvec) * inv_det;
    if (*u < 0.0 || *u > 1.0)
        return 0;
    //prepare to test V parameter
    CROSS(qvec, tvec, edge1);
    //calculate V parameter and test bounds
    *v = DOT(dir, qvec) * inv_det;
    if (*v < 0.0 || *u + *v > 1.0)
        return 0;
    // calculate t, ray intersects triangle
    *t = DOT(edge2, qvec) * inv_det;

    return 1;
}

int main() {
    double orig[] = {0.0, 98.0, 50.0};
    double dir[] = {-100, 5.88235, 73.5294};

    double vert0[] = {100.0, 100.0, 100.0};
    double vert1[] = {-100.0, 100.0, 100.0};
    double vert2[] = {-100.0, 100.0, 50.0};
    double* u;
    double* v;
    double* t;

    if(intersect_triangle(orig, dir, vert0, vert1, vert2, u, v, t))
    {
        std::cout << "Intersect" << std::endl;
    }
    else
    {
        std::cout << "Doesn't intersect" << std::endl;
    }
    return 0;
}

```

Another implementation of this algorithm tells me that intersection is in (-34, 100, 75).

# Answer
**EDIT1: Looks like an intersection...**

I've just plugged that triangle and origin/ray direction into a plotter and it looks like there is an intersection:

Are you sure about expecting it not to intersect with these values? Are you mistaking orig/dir here as end/begin points rather than origin and direction?

**Original**

Möller-Trumbore usually works only with triangles that have counter clockwise winding (unless you test both windings, I think thats whats the CULL testing is about in that paper...)
> 0 votes

---
Tags: c++, algorithm, intersection
---


# Question
Title: How to stop movement when an action key is pressed even if movement key is pressed
I'm making a 2d side-scrolling fighting game in game maker:studio and I want to make a code that when the player attacks he stops moving. I've tried some options:

```
keyboard_check(ord("D"));

```

both this and

```
keyboard_check_pressed(ord("D"));
x += 0

```

I also tried

```
hspeed = 0

```

I also tried adding these to my left and right key events:

```
if (sprite_index = spr_atk_right)
 {
 x -=4 for right key event or x += 4 for left key event
 }

```

I have a right key and left key event with the simple code `x += 4` for the right key and `x -= 4` for the left key. I was hoping the second set of codes would cancel it out but neither worked.

# Answer
Might I suggest looking into Finite State Machines? I came across it the other day and I thought it interesting because for every action you add, more bugs require squashing. However, finite state machines work in a way where when you're in a "state" only on pressing of certain keys, does your avatar/character perform an action. So while standing (stand state) you can only walk, jump and duck. While jumping (jump state) you can only move left and right, which removes the ability to jump and duck while in midair. In your case it'd probably look a little like:

Stand state (nothing pressed): Jump Attack Walk Duck(?)

Jump state: Attack

Walk state: Attack Jump Duck(?)

Duck state: (Perform duck animation only)

Attack state: (Perform Attack animation only)

In this way, you can't move while attacking, even if you tried. Though it would mean you can only move AFTER you're done attacking.

Read it here: http://gameprogrammingpatterns.com/state.html

This at least reduces the need for adding way more than you need to any if else statements and does away with having a billion flags.
> 2 votes

# Answer
How about this, create an alarm that has a timer for your players attack duration. start the timer when they press the attack button to count down, then release them when they are allowed to move again.

create event:

```
can_move = true;
attack_speed = room_speed*2; //2 seconds

```

alarm 0:

```
can_move = true;

```

step event:

```
if(keyboard_check_pressed(ord("D"))) {
    can_move = false;
    alarm[0] = attack_speed;
}

if(can_move = true) {
    //put your move code here
    //so it only executes when you are allowed
}

```
> 0 votes

# Answer
You should not do `x += 4` and `x -= 4` directly inside the event. Instead, **store the pressed keys in an array**.

You can then process the array in the priority order you find appropriate, for example :

```
if (keyPressed["D"])
{
     // Attack
}
else if (keyPressed["RightArrow"])
{
     x += 4;
}
else if (keyPressed["LeftArrow"])
{
     x -= 4;
}

```

This will definitly make your life simpler.
> 0 votes

# Answer
if your using game maker studio you can use if statements to make sure that only 1 key is being pressed for the movement in a step event like this

Movement Event (Coded in GML\[Game Maker Language\])(Make sure this is in the step event of the player)

```
if keyboard_check_pressed(ord('W')) && string_length(keyboard_string) == 1{
     y -= 5;
}

```

Action Event (In GML)(In Step Event)

```
if keyboard_check_pressed(vk_control) && keyboard_check_pressed(ord('W')){
    <Action Event Code Here>
}

```
> 0 votes

---
Tags: input, game-maker
---


# Question
Title: What is the best practice to handle event with order?
When you play card games, you always face some abilities and effects will be triggered at the same time. To resolve this, players relies on the rules. For example, if a minion dies, it triggers effects on my side and opponent side. If the effects is handled on my side first if it is my turn.

But how would you resolve it in computer games. Even you are using mediator for event handling, the event is usually handled by the order of subscription. Unless there are some indicators for the subscribers, you will not able to distinguish between the subscribers. But wouldn't it defeats the purpose of observer pattern? What is the best way implement it?

# Answer
Pending a clarifying edit to your original question, I assume the following:

1. The game implements the observer behavioral design pattern using some base`TableObserver` class from which `Player` inherits.
2. Some `TableTop` class exists that subscribes, unsubscribes, and notifies its vector of `TableObserver` references.
3. Each `Player` submits actions to an instance of `TableTop` for processing *in turns*, for example `table.SubmitAction( playerOne, action );`
4. The `TableTop` instance resolves all submitted actions **after** a round of `Player` action submissions.

Wherein `table.SubmitAction( playerOne, action );`:

* `table` is an instance of `class TableTop` which is either globally visible, or that each player has a reference to.
* `SubmitAction` is a `public` member function of `class TableTop`
* `playerOne` is an instance of `class Player` (which inherits from `TableObserver`)
* `action` is either an instance of `class PlayerAction`, or some other arbitrary argument such as a `std::string` like `"floop the pig"`

---

## Option 1

Start a **globally visible timer** at the beginning of the game that continuously counts up using an `unsigned` 32-bit value.

Then, either modify `TableTop`'s `SubmitAction` function to take an additional game-time-stamp `table.SubmitAction( playerOne, action, gameTime );`, or have `TableTop` internally cache the game-time during `SubmitAction` execution.

After the `TableTop` instance processes all the submitted actions for a round of play, it can **sort** its list of `TableObserver` references in order of submission time-stamps. Finally, the `TableTop` can iterate over the newly sorted list of `TableObserver` references.

---

The same time-stamping idea could also be applied during the `TableObserver` notification process:

Either `TableTop` can send the game-time-stamp as `observer.notify(notificationTime)`, or `TableObserver` can internally cache the game-time during `notify` execution. Both require that the `TableObserver` class have an `unsigned` 32-bit `notifiedTime` variable.

A `Player` can then use `notifiedTime` for whatever duration/delay calculations it may need.

---

## Option 2

Forget the **round of play before resolution** mechanic, and replace the overly-specific base observer class `TableObserver` with the general `Observer`.

Assume there is a `MinionCard` class, that inherits from a`Card` class which can subscribe, unsubscribe, and notify instances of `Observer` (for example a `Player`), as before.

If an instance of `MinionCard` has its `health` drop below 0, then -- as-per your question's initial example -- it would need to notify the `Player` whose turn it currently is, *then* any other players that event may affect.

This can be accomplished by giving the base `Observer` class an internal `priority` value, which is updated either each turn, or updated based on some other rule such as physical proximity of `Player` instances.

For example, the `Player` whose turn it is always has `priority == 1`, and the remaining `Player`s' priorities are calculated by the square of the distance between the `Player` with `priority == 1`, hence increasing with range.

This `priority` updating can either be handled by each `Player` instance internally, or more simply by a `PlayerManager` class or some other such object that tracks all the players on a moment-to-moment basis.

Now, going back to `MinionCard`'s death, *before* it begins it iteration over its vector of `Observer` references, it can **sort** that vector based on `Observer` `priority`.

For example, using C++'s STL:

```
std::sort( observerList.begin(),
           observerList.end(),
           [] (auto && a, auto && b) {
               return a.priority < b.priority;
           }
);
for ( Observer & observer : observerList ) {
    observer.notify();
}

```

---

The overall idea is to sort the `Observer` references before notifying them. I hope that helps. Again, SE is more useful if questions are as specific as possible.
> 0 votes

# Answer
I would use global counter or timestamp on event delivery and process them by this ordered.
> -1 votes

---
Tags: algorithm, events
---


# Question
Title: Unity / Animation / Change the "Transition Speed" between 2 animations during runtime
I need to change the Transition Duration per Runtime. I just didnt find a way to do access it. I found questions with similar problems though (links below)- those didnt work for me because they accessed it to change it via editor - script. But I need it in runtime. Is that even possible?

https://stackoverflow.com/questions/29315507/unity-5-access-modify-animatorcontroller-from-c-sharp-script-in-editor

# Answer
Alright so this was a difficult question that I had to do some thorough research on. To access the transition duration of a certain state you have to go through the animation controller, then find the right layer, then find the right state on that layer, then access the correct transition in that state. After all this you can then change the transition duration. Now you said you wanted the duration per runtime, in order to do anything per runtime in the animation controller I believe you would have to access the Animator class' runtimeAnimatorController. This class has limited abilities and you can not access even the layers, much less a state's transition duration so you have to use the "as" keyword to change it into a normal AnimatorController class. Now you can change the necessary values per runtime. The code would look something like this. (The majority of this code is to help you find the transition you wish to change)

```
void ChangeTransitionDuration(float value)
{
    // Get a reference to the Animator Controller:
    UnityEditor.Animations.AnimatorController ac = GetComponent<Animator>().runtimeAnimatorController as UnityEditor.Animations.AnimatorController;
    //This part is IMPORTANT ^^

    // Number of layers:
    int layerCount = ac.layers.Length;
    Debug.Log(string.Format("Layer Count: {0}", layerCount));

    // Names of each layer:
    for (int layer = 0; layer < layerCount; layer++)
    {
        Debug.Log(string.Format("Layer {0}: {1}", layer, ac.layers[layer].name));
    }

    // States on layer 0:
    UnityEditor.Animations.AnimatorStateMachine sm = ac.layers[0].stateMachine;
    UnityEditor.Animations.ChildAnimatorState[] states = sm.states;
    foreach (UnityEditor.Animations.ChildAnimatorState s in states)
    {
        Debug.Log(string.Format("State: {0}", s.state.name));
    }

    // Access the duration variable to change it
    ac.layers[desiredLayer].stateMachine.states[desiredState].state.transitions[desiredTransition].duration = desiredValue;
    // You can split this up into different variables if you like
    // I just wrote it all on one line so you could see the path to take
}

```

This code was taken and altered from TonyLi's answer here: http://answers.unity3d.com/questions/418854/getting-a-list-of-mecanim-states-in-animator.html

I hope this helps!
> 0 votes

---
Tags: unity, animation
---


# Question
Title: How to design Client-server hybrid hit detection with projectile weapons?
Hybrid hit detection here refers to a architecture where client sends a hit claim to server and server verifies it with a tolerable error limit to confirm the hit or deny it.

This technique may work well with hit scan or instant hit weapons because you only have to check it for one frame/tick. But in case its a physics projectile I.e where an actual projectile flies to the target like a real bullet, the hit is the result of flight over more than one frames and varying physics state. As such verifying the hit could be very cumbersome and resource intensive.

So how would one go for server client hybrid approach in this scenario?

# Answer
I solved a similar problem in a multiplayer spaceship game by using a different distance checker on the client and the server. Basically the client used a smaller collision radius, and the server used a larger collision radius.

The end result is that the client sometimes sees false negatives. At first he may think that he missed, but within a few hundred milliseconds he learns that the target was hit.

This turns out to work really well, because seeing your missile hit visually always turns into a hit, but not the other way around.

The example is on the incheon NPM package, click the demo link to see the game experience
> 1 votes

---
Tags: collision-detection, physics, networking, multiplayer
---


# Question
Title: Clientside interpolation - update rate fixed to client framerate
I am trying to implement client side prediction as in this article http://www.gabrielgambetta.com/fpm2.html

Currently I'm doing it like this: the game runs at 60 FPS. 60 times per frame I check if an arrow key is pressed, if so, I move the player character slightly and send the message about the movement done to the server (direction + delta time). The server applies the movement. On the next player positions broadcast, the server also sends the ID of the last\_received\_input. Client then updates the state based on what it received from the server, then reapplies all the inputs after the last\_received\_input.

It works in general. The problem is, that now client packet send rate is tied to the client framerate. If I keep rendering at 60 FPS, but check inputs/send input packets at only 30 FPS, I will start to experience jerky movement on the player character. How is it done properly? How to reduce the client tickrate, but still achieve smooth movement?

# Answer
> 2 votes
One approach is to give each server step a incrementing number. For example, a server may be currently executing step **500**, and after one second, this server running at 60 FPS will have reached step **560**.

The client keeps count of the steps on the client side, and tries to stay within a certain time-bound from the corresponding server step.

That way when a client receives new data from the server, it knows two things: (1) which inputs have already been applied in the new data, and (2) which steps it needs to re-enact (on the physics engine) and at what client step.

This approach has another nice advantage: it removes the assumption that the client loop and the server loop will always be in sync. In reality there can be drift, or network spikes between the game loop on the client and the server. They both attempt to run at 60 FPS but with time they drift apart.

---
Tags: networking, multiplayer, client-server, interpolation, movement-prediction
---


title: How does client-side prediction work?

text:
# Question
Title: How does client-side prediction work?
I've read Valve + Gafferon and hundreds of pages from Google, but for whatever reason I can't get my head around client prediction.

To my understanding, the basic problem is:

* Client A sends input at `T0`
* Server receives input at `T1`
* All clients receive the change at `T2`

At `T2` however, using client prediction, Client A is now at a position appropriate to `T4`.

How do you ensure that the Client A, when predicting that the server will accept the movement request, won't be ahead of the server? Obviously all the time they are ahead, this results in snapping back to where the server last saw them. With all corrections I've tried, this is still noticeable when you stop, because the server stops behind you

# Answer
> 38 votes
I wrote a series of articles on this. It is based on the same ideas you've read elsewhere, but explained in a very detailed and (I hope) accessible way.

In particular, the article about the client-side prediction is this one.

# Answer
> 4 votes
I haven't actually implemented this (so there might be some problems I'm not immediately seeing), but I thought I'd try to help.

Here's what you said is happening:

> Client A sends input at T0
>
> Server receives input at T1
>
> All clients receive the change at T2
>
> At T2 however, using client prediction, Client A is now at a position appropriate to T4.

It probably would be useful to think in terms of server time. Its (probably) very similar to how interpolation works.

Every command is sent up with a server time. This server time is figured out at the start of a match by querying for the server tick, compensating for ping time. On the client you have your own local tick count, and each command you send up is converted to server ticks (it's a simple subtraction operation)

Also, the client is always rendering "in the past". So you assume that the world the client sees is, say, 100ms behind what the server's time really is.

So let's rephrase your example with server time (designated by S).

Client sends input at T0 with server time S0 (which I'm guessing is really "client representation of server time minus interpolation time"). Client doesn't wait for response from server and moves immediately.

Server receives input at T1. Server figures out client's authoritative position at server time S0 given by the client. Sends that to the client.

Client receives the authoritative position at T2 (still with designation of server time S0). The client keeps track of some past amount of time worth of previous events (probably just a queue of all unconfirmed predictions).

If the predicted position/velocity/whatever that the server sends back at S0 is different than what the client has stored at S0, the client handles this somehow. Either by snapping the player back to their past position, or resimulating the previous input, or maybe something else I haven't thought of.

# Answer
> 2 votes
Actually there is an open-source implementation in github which shows how this is done. Check out Lance.gg

github repo: https://github.com/lance-gg/lance

The client prediction code is implemented in the module called `src/syncStrategies/ExtrapolateStrategy.js`

Besides extrapolation, there are two concepts which I didn't see mentioned above:

1. **Incremental Bending.** Basically rather than applying the server correction all at once, you let the delta apply in small increments. That way remote objects will gradually adjust their positions to match the server positions. There is position bending, velocity bending, angle bending, and angular velocity bending. Also you may want different bending factors for different objects.
2. **Step Re-Enactment.** The fact that the data is in the past means you can rollback time to the server data time, and restart from that point. Of course you will still need to bend towards the new-found position, rather than jump to it.

# Answer
> 1 votes
Client A is always ahead of the server - but it doesn't matter. You only have to snap the client back if the server says there was a problem with the reported position, at which point the client re-runs all the changes it has made since the error with the corrected values, to bring it to a state compatible with the server.

To do this, the client needs to remember some of its past state and past updates. This may only be a few simple values such as position, velocity, orientation, that sort of thing. The server will periodically send an acknowledgement that various client updates were legit, meaning they can now be forgotten from the client. If the server however reports that an update was invalid, the client state rolls back to that point and the future changes are applied to that modified state.

There are some extra links at the bottom of the Valve article that are worth reading - this is one of them: https://developer.valvesoftware.com/wiki/Prediction

---
Tags: networking, multiplayer, movement, movement-prediction
---


# Question
Title: Unity 3D C# - Setting Material's Emission Texture via Script
Hi, I just wanted to know if there is a way to set emission's texture via script. I haven't found nothing in the documentation, neither on any forum, except the setting of the emission color setting via script.

Thanks in advance.

# Answer
If you take a look at the Standard shader, you will see the name of the property you want :

```
_EmissionColor("Color", Color) = (0,0,0)
_EmissionMap("Emission", 2D) = "white" {}

```

Then, using the documentation you will see how to assign a named texture to a given material.

```
GetComponent<MeshRenderer>().material.SetTexture("_EmissionMap", yourTexture ) ;

```

Here is a link to download the shaders provided by Unity.
> 3 votes

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


title: SDL Function for Loading PNGs

text:
# Question
Title: SDL Function for Loading PNGs
I'm learning SDL 2.0 at the moment and I've seen this method for loading BMPs:

```
SDL_Texture* LoadImage(std::string file)
{
    SDL_Surface *loadedImage = nullptr;
    SDL_Texture *texture = nullptr;
    loadedImage = SDL_LoadBMP(file.c_str());

    if (loadedImage != nullptr)
    {
        texture = SDL_CreateTextureFromSurface(renderer, loadedImage);
        SDL_FreeSurface(loadedImage);
    }
    else
        std::cout << SDL_GetError() << std::endl;
        return texture;
}

```

How could I switch it up to load PNG files?

EDIT: Woops, forgot to add my method of loading PNGs.

```
SDL_Texture* grass_image = nullptr;
grass_image = IMG_LoadTexture(renderer, "res/grass.bmp");
SDL_Rect grass_rect;
    grass_rect.x = 0;
    grass_rect.y = 0;
    grass_rect.w = SCREEN_WIDTH;
    grass_rect.h = SCREEN_HEIGHT;

if (grass_image == NULL)
    std::cout << "Couldn't load grass_image" << std::endl;

while (!quit && mainEvent -> type != SDL_Quit)
{
    SDL_RenderCopy(renderer, grass_image, NULL, &grass_rect);
}

```

I just don't want to have to do that for EVERY image. So how could I put that into a function?

Thanks!

# Answer
You should use SDL\_Image API, it has one simple function that loads everything:

```
SDL_Surface *IMG_Load(const char *file);

```

More precisely, it loads ICO(Icon)/CUR(Cursor)/BMP, PNM (PPM/PGM/PBM), XPM, LBM(IFF ILBM), PCX, GIF, JPEG, PNG, TGA, TIFF, and XV thumbnail formats.

It also has individual format functions such as `IMG_isPNG` and `IMG_LoadPNG_RW`.

This lib is one of the most commonly used for image file loading with SDL, I think.

Website and Documentation
> 11 votes

# Answer
**SDL 2 SDL\_image minimal runnable example**

main.c

```
#include <stdlib.h>

#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>

int main(void) {
    SDL_Event event;
    SDL_Renderer *renderer = NULL;
    SDL_Texture *texture = NULL;
    SDL_Window *window = NULL;

    SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);
    SDL_CreateWindowAndRenderer(
        500, 500,
        0, &window, &renderer
    );
    IMG_Init(IMG_INIT_PNG);
    texture = IMG_LoadTexture(renderer, "flower.png");
    while (1) {
        SDL_RenderCopy(renderer, texture, NULL, NULL);
        SDL_RenderPresent(renderer);
        if (SDL_PollEvent(&event) && event.type == SDL_QUIT)
            break;
    }
    SDL_DestroyTexture(texture);
    IMG_Quit();
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return EXIT_SUCCESS;
}

```

GitHub upstream.

Compile and run:

```
sudo apt-get install libsdl2-dev libsdl2-image-dev
gcc -std=c99 -o main -Wall -Wextra -pedantic main.c -lSDL2 -lSDL2_image
./main

```

Outcome:

Tested on Ubuntu 16.04, GCC 6.4.0, SDL 2.0.4, SDL Image 2.0.1.
> 6 votes

# Answer
In order to load PNG files with SDL you need to have the SDL\_Image library extension.

http://www.libsdl.org/projects/SDL\_image

A description of this library extension:

"SDL\_image is an image file loading library. It loads images as SDL surfaces, and supports the following formats: BMP, GIF, JPEG, LBM, PCX, PNG, PNM, TGA, TIFF, WEBP, XCF, XPM, XV."
> 4 votes

---
Tags: c++, sdl
---


title: XNA - 2D camera orbit around sprite

text:
# Question
Title: XNA - 2D camera orbit around sprite
OK, I have a 2d sprite in a scene and I would like to know the theory behind the camera orbiting around it with an analog stick. I know the basic code to get the input from the gamepad, but I'm having trouble getting the desired result. Basically, to simplify, the sprite is at the center of the screen. With the left analog stick I want to orbit the sprite between its a maximum distance (-1 or 1) and its minimum (0) around the centered sprite. It must be a simple thing to do, but I'm struggling with it. Thanks in advance.

# Answer
If you're using Matrix based camera, you can use Matrix.CreateRotationZ(radians) to rotate a camera. There is a good tutorial available http://www.dylanwilson.net/implementing-a-2d-camera-in-monogame
> -1 votes

---
Tags: xna, 2d, camera, monogame, orbit
---


# Question
Title: What is the order of execution, when calling an instantiation method, in Unity?
In my `GameManager` script, I instantiate a player game object, and call another method like this:

```
void Start()
{
   Debug.Log("GameManager Start() called...");
   Instantiate(player, Vector3.zero, Quaternion.identity);
   InitNewLevel();
}

void InitNewLevel()
{
    Debug.Log("GameManager InitNewLevel() called...");
}

```

In my `Player` script, I have this:

```
void Start()
{
    Debug.Log("Player Start() called...");
}

```

---

I was expecting `Player.Start()` to be called after the `Instantiate(player, Vector3.zero, Quaternion.identity);` line, and before the `InitNewLevel()`. However, if I look at my debug log output, I see this:

> GameManager Start() called...
> GameManager InitNewLevel() called...
> Player Start() called...

Why do my methods execute in this order? Why does `Player.Start()` get called *after* `GameManager.InitNewLevel`?

# Answer
> 11 votes
The order is:

1. `Instantiate` or `AddComponent` called by our spawning method
2. `Awake()` \<-- You can think of this like a "Constructor" for MonoBehaviours
3. `OnEnable()`, skipped if script is disabled in prefab or GameObject is inactive
4. `Instantiate` or `AddComponent` return and the calling method continues executing

As Gnemlock points out, Start will get called later after the calling method has completed (if the script & its gameObject are enabled/active), but before the newly-spawned script instance gets its first Update or FixedUpdate, ie...

5. (Sometime later) `Start()`
6. `FixedUpdate()`, skipped if there's no physics tick this frame (short frame), or called multiple times we tick multiple times this frame (long frame)
7. `Update()`
8. `LateUpdate()`

Here's a script you can use to test & verify this yourself:

```
public class InstantiatorTest : MonoBehaviour {

    static bool hasSpawned;

    // Editor-only, zeroth for objects already in the scene.
    void OnValidate()
    {
        Debug.Log(gameObject.name + " Validated");
    }

    // First!
    void Awake()
    {
        Debug.Log(gameObject.name + " Awake");
    }

    // Second!
    void OnEnable()
    {
        Debug.Log(gameObject.name + " Enabled");
    }

    // Third!
    void Start () {
        Debug.Log(gameObject.name + " Start");

        if (!hasSpawned)
        {
            hasSpawned = true;

            var go = new GameObject("spawned");
            go.AddComponent<InstantiatorTest>();

            Debug.Log("Spawn returned.");
        }
    }

    // Fourth! (If enough time has elapsed)
    void FixedUpdate()
    {
        Debug.Log(gameObject.name + " Fixed");
    }

    // Fifth!
    void Update () {
        Debug.Log(gameObject.name + " Update");
    }
}

```

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


# Question
Title: Why do my 3D models look so different when imported into Unity?
I am importing an image from Maya into Unity but the shapes look drastically different from one another as well as the color and I am not sure what is causing this how can I fix it?

From maya

From Unity

# Answer
I made a quick mockup with primitives in Unity, and it looks like this could be explained with just camera settings:

This is the same collection of primitives, rendered with two cameras in Unity simultaneously in splitscreen.

* On the left I've used an orthographic camera, which is able to see a whole hemisphere of the body all at once. That makes the face look quite small in comparison to the full diameter.
* On the right I've used a camera with a very wide field of view, positioned quite close to the penguin's beak.

Because it's so close, the face appears very large in the camera's view, while more distant content like the distance between the wingtips shrinks away. (Think of looking down a set of parallel railroad tracks - the ties are the same width all the way down, but as they get further away it looks like they get shorter and the rails seem to converge).

This camera is too close to the body sphere to see more than a portion of it - the rest curls away from its view, like the Earth curving away over the horizon.

So, how do you fix this?

You can...

* Use an orthographic camera in Unity if you like that pure geometric look
* Or, using a perspective camera, pull your viewpoint back away from the character, so there's not such a drastic difference in relative depth from its front to its back (perspective distortion is sharpest near the camera, where moving a few centimeters doubles your distance from the "lens". Far from the camera, the same depth change is pocket change relative to the total depth).

If this makes the object too small on screen, reduce your camera's field of view, which effectively zooms back in without adding shape distortion. As the camera FoV gets narrower and it pulls further away, it becomes more "orthographic-like" - this is the trick used in those dolly zoom shots in movies:

Here we start with a distant & tight camera, shifting to a close & wide one, making the background appear to shrink or zoom away while the foreground stays almost the same.
> 2 votes

---
Tags: unity, maya
---