# Question
Title: Can I release any sort of app or game on the PlayStation Store?
I'd like to develop a game, and try it out mainly on the Playstation 4.

Can I build *any* game, or app, and release it on the Playstation Store? Or does Sony only allow what it wants in the store, much like Apple and the AppStore? Note that I'm not asking *how* to build a game, but whether or not there are restrictions that would prevent me from releasing certain kinds of games or applications to the Store.

# Answer
No, you can't release "anything" on the Store. So yes, to *some* extent the store, like all software portals like it (including Apple's App Store, Steam, Xbox Live) could be considered a "walled garden."

The question is *how* walled, really. Unfortunately details on the licensing agreements you sign when you become a licensed PlayStation developer aren't public (at least, not that I could find), so it's difficult to provide solid examples sans legal entanglements.

That said, the Store requires a license agreement to publish to, and it would be baffling and foolish for Sony not to include a clause in that agreement that would allow them to block the publishing or distribution of your product if they deemed it inappropriate for their store. After all, they have their brand image to worry about and consumers won't really care if you are selling a horribly inappropriate or scammy game on the store, they'll focus on the fact that Sony *let you*.

Anecdotally, by browsing the store you can see very few things labelled "apps" (as opposed to "games"), so it's unlikely that Sony will want you to try to sell, for example, a spreadsheet program.
> 1 votes

---
Tags: playstation4
---


# Question
Title: Unity3d simple material color display correctly in windows built but yellow color turns to blue in android build?
I have a simple roll a ball game as shown in unity 3d tutorials, and I have set the wall color as a shade of yellow using the standard shader and material. This runs flawlessly in windows application, however when running in android phone( Nexus 5 MM) the wall turns into a blue color. Can anyone tell me how to fix it?

# Answer
> 1 votes
Found what was causing the problem, it was because of my dedicated graphics card! Switched over to intel and all the color related issues vanished.

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


# Question
Title: How are Stencil Buffer Operations Applied in ShaderLab
In Unity's Shader lab, I've read that the Stencil buffer is implemented with a mask, and an object reacting to the mask.

The mask may be defined like the following:

```
SubShader {
    Tags {
        "RenderType"="Opaque"
        "Queue" = "Geometry-100"
    }

    Stencil{
        Ref 1
        Comp always
        Pass replace
    }
    ...
}

```

To my understanding, because Comp is defined as `always` and Pass as `replace`, every pixel that this geometry covers, will have its stencil buffer replaced with `1`.

The object to be masked may have a shader similar to the following:

```
SubShader
{
    Stencil{
        Ref 1
        Comp equal
        Pass keep
        Fail keep
    }
    ...
}

```

And supposedly, this object would only render if its is rendered over the pixels affected by the mask.

***Does this mean that every object rendered with a shader that contains the `Stencil` function will automatically discard any pixels where the `Comp` fails, before passing it to the fragment shader?***

Consider the following: There are no masks, but only a single object containing the `Stencil` function. If the stencil function is declared as

```
Stencil{
    Ref 1
    Comp never
}

```

then this object will never render to the screen? What is the default value in the stencil buffer? Does rendering path affect any of this?

# Answer
I think the quirky part of stencil shaders is the overloading on the keywords:

* The reference value can be used for both conditional testing (e.g. in combination with pass greater) and for writing (pass replace)
* The comparison function can be used for controlling which pixels are drawn and/or for controlling which stencil values are written.

With that I'll try to answer your specific questions:

> To my understanding, because Comp is defined as always and Pass as replace, every pixel that this geometry covers, will have its stencil buffer replaced with 1.

and

> And supposedly, this object would only render if its is rendered over the pixels affected by the mask.

Are correct. I verified by reading Unity documentation and doing some tests in which I drew a sphere over a cube (mask) and only the area of intersection was drawn.

> Does this mean that every object rendered with a shader that contains the Stencil function will automatically discard any pixels where the Comp fails, before passing it to the fragment shader?

That is true, however the shader could still write to the stencil buffer - for example `Fail IncrSat` would increment the value in the stencil buffer. So objects with Comp never will not render to the screen. An exception would be if you have shadow map shadows enabled, then shadows can still be drawn (where the object is, and shadows casted onto other objects) even though your pixels are not - that is because shadows are drawn in a separate pass.

> What is the default value in the stencil buffer?

The default value is zero. Unity cameras allow you to select what is cleared (depth, color, none etc) however there are no options to control if the stencil buffer is cleared and to what value. If you check in the frame buffer tool, then you'll be able to see exactly where the stencil buffer is cleared - it will show up as Clear (color+z+stencil).

> Does rendering path path affect any of this?

Generally, stencils should work in both deferred and forward. In deferred mode you may want to use this function https://docs.unity3d.com/ScriptReference/Camera-clearStencilAfterLightingPass.html to clear the buffer. There are also some limitations in deferred mode. See the deferred lighting path section on this page:

> Stencil functionality for objects rendered in the deferred rendering path is somewhat limited, as during the base pass and lighting pass the stencil buffer is used for other purposes. During those two stages stencil state defined in the shader will be ignored and only taken into account during the final pass. Because of that it’s not possible to mask out these objects based on a stencil test, but they can still modify the buffer contents, to be used by objects rendered later in the frame. Objects rendered in the forward rendering path following the deferred path (e.g. transparent objects or objects without a surface shader) will set their stencil state normally again.
>
> The deferred rendering path uses the three highest bits of the stencil buffer, plus up to four more highest bits - depending on how many light mask layers are used in the scene. It is possible to operate within the range of the “clean” bits using the stencil read and write masks, or you can force the camera to clean the stencil buffer after the lighting pass using Camera.clearStencilAfterLightingPass.
> 1 votes

---
Tags: unity, shaders, stencil, shaderlab
---


# Question
Title: How to check mouse coordinates and mouse events
I'm building a simple game where if the mouse's X coordinate is greater than 200, and you click, the screen will turn red. Here's the code:

var mouseX = event.clientX;
var mouseY = event.clientY;

```
function startGame(){
 if(mouseX > 200){
  document.body.style.backgroundColor = "red";
 }
}
document.addEventListener("onmousedown", startGame);

```

Am I using an incorect way of finding coordinates or am i using an incorrect way of finding mouse down or what? I can't use Jquery btw.

# Answer
The event should be "mousedown", not "onmousedown". Also, you need to put an event parameter inside your startGame function and declare your variables inside it. Try this:

```
function startGame(event){

  var mouseX = event.clientX;
  var mouseY = event.clientY;

  if(mouseX > 200){
    document.body.style.backgroundColor = "red";
  }
}
document.addEventListener("mousedown", startGame);

```

https://jsfiddle.net/a7pn0seb/1/
> 0 votes

---
Tags: javascript, coordinates, mouse
---


# Question
Title: How to get a safe index for glVertexAttribPointer without shader?
I'm learning to use VBOs and trying to keep it simple before building up. Trying to do it without writing a shader right now. It looks like this is possible, but I cannot seem to find a way to get the index parameter for `glVertexAttribPointer`.

I've seen that you can get the index with `glGetAttribLocation`, but that function seems to require a shader be passed in to get the index.

I don't want to assign the index, because I'm worried about different pieces of a project accidentally using the same index and causing problems. (If there's some reason I shouldn't be worried about that, please let me know)

Question is: Without using shaders and without assigning the index, how can I get the index for `glVertexAttribPointer`?

# Answer
What you're asking for is impossible.

You are essentially asking how to get the address of an object in memory without ever actually creating the object.

> I don't want to assign the index, because I'm worried about different pieces of a project accidentally using the same index and causing problems.

You shouldn't be worried about that. That isn't a real problem unless you're being *really* sloppy.

The indices should be assigned *with names* to avoid sloppiness. That is, in your C code make a define/enum named something like `ATTRIB_POSITION` that's assigned to 0, and then in your GLSL code use defines or includes (via a GLSL preprocessor) named the same thing assigned to the same value. Then you know that `POSITION` always matches. Do the same thing for other common properties (normals, texcoords, colors, etc.).

You can take this a step further and have pre-defined full layouts (e.g. a `SkinnedMesh` layout that has various attributes and their locations hard-coded). Then instead of trying to check if a shader has all the same attributes as some source data you're instead just making sure that a shader matches a particular pre-defined layout, of which all objects will use.
> 1 votes

---
Tags: opengl, vbo
---


# Question
Title: Is using Spherical Harmonics still viable as a technique nowadays?
I've been implementing spherical harmonics in my Engine for learning purpose.

I was wondering if Spherical Harmonics are still used in modern engine or if they moved on to the more simple cubemaps or pre-convolved environment map with PBR and IBL (e.g in UE4) or any other technique for performance and good visual purpose ? What is the technique with the best performance/good visual ratio compared to SH ?

# Answer
Ok so first up the way I use my Spherical Harmonics is to build a grid of probe points along the top of the terrain\objects, I offset the y value of the probe so that when I capture a cubemap of the location I get all 6 faces filled.

I render the cubemap at 16x16 or 32x32 pixels, you don't need lots of resolution because u only want to capture small amounts of color. eg: for ambient lighting from what I can see after getting this up and running as long as u are getting green from the ground, blue from the sky and brown\gray for the mountains it looks good.

Once I have my probe grid I then convert each of the cubemaps into 3rd order Spherical Harmonic that gives me 9 vector3 color values.

The Spherical Harmonics are loaded into an octree for CPU culling and then passed of to my tilebased deferred compute shader to do finer per tile culling, once I have my Spherical Harmonics list on the GPU I just render them like lights, sampling from the Spherical Harmonics using the world normal and adding the result to my ambient light term.

The only slow part of all of this is building the probe grid and computing the Spherical Harmonics from cubemaps so I do it all offline and just load the octree on start up.

I'm using this because its the cheapest\easiest to implement fake Global Illumination(ambient light) so if you mix it with a per frame global dynamic cubemap you end up with really nice ambient lighting.

HLSL(Reading SH values on GPU)

```
// 'sphericalHarmonicBase' is the lighting environment projected onto SH (3rd order in this case),
// and 'n' is the surface normal
float3 ProjectOntoSH9(float3 n, float3 sphericalHarmonicBase[9])
{
float3 result = 0.0f;

// Cosine kernel
const float A0 = 1.0f;
const float A1 = 2.0f / 3.0f;
const float A2 = 0.25f;

// Band 0
result += sphericalHarmonicBase[0] * 0.282095f * A0;

// Band 1
result += sphericalHarmonicBase[1] * 0.488603f * n.y * A1;
result += sphericalHarmonicBase[2] * 0.488603f * n.z * A1;
result += sphericalHarmonicBase[3] * 0.488603f * n.x * A1;

// Band 2
result += sphericalHarmonicBase[4] * 1.092548f * n.x * n.y * A2;
result += sphericalHarmonicBase[5] * 1.092548f * n.y * n.z * A2;
result += sphericalHarmonicBase[6] * 0.315392f * (3.0f * n.z * n.z - 1.0f) * A2;
result += sphericalHarmonicBase[7] * 1.092548f * n.x * n.z * A2;
result += sphericalHarmonicBase[8] * 0.546274f * (n.x * n.x - n.y * n.y) * A2;

 // Clamp to zero

return result;
}

Ambientcolor += ProjectOntoSH9(normalW, SH);

```

Just the ambient light(SH):

Render output:

I still have more tweaking to do but for now I'm happy with how it looks.

As for roughness and stuff like that because you are only modifying the ambient term you just do you specular and diffuse light the way u want, I have materials set up in my engine once again the compute shader does the work of selecting the right material based off a uint material ID texture.
> 2 votes

---
Tags: rendering, cubemap, spherical-harmonics
---


# Question
Title: Is it possible with DirectX11 to have pixel shader output an integer rather than float4?
I am trying to implement object picking via a shaders. My intent is to create a texture2d that I would write out ID values describing individual objects.

Following drawing the objects, I would query back the pixel value at the focus point and read out the ID of the object.

I've created my texture2d as follows:

```
// Create a very tiny selection texture.
// This will record the color ID as unique identifier of a selectable object.
D3D11_TEXTURE2D_DESC desc;
desc.Width = 1;
desc.Height = 1;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R32_UINT;  // 16 bit integer, hold up to 65536 possible unique IDs.
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D11_USAGE_STAGING; // We will write via GPU and read to CPU!
desc.BindFlags = D3D11_BIND_RENDER_TARGET;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
desc.MiscFlags = 0;

HRESULT result = m_deviceResources->GetD3DDevice()->CreateTexture2D(&desc, 0, &m_colorRenderTarget);
if (FAILED(result)) {
    OutputDebugString(L"PickRenderer: Unable to create Texture2D");
}

```

Is it possible to then to make a pixel shader that would write out an R32 integer value, rather than the float values for RGBA? If so, how would I best do this?

My pixel shader currently writes float RGB values out as follows:

```
// A constant buffer that stores the model transform.
cbuffer ModelConstantBuffer : register(b0)
{
    float4x4    modelToWorld;
    float3      color;  // Instead use unsigned int32 here if possible?
};

// Per-vertex data used as input to the vertex shader.
struct PixelShaderInput
{
    min16float4 pos     : POSITION;
};

// Can this use a different return value for uint?
min16float4 main(PixelShaderInput IN) : SV_TARGET
{
    return min16float4(color, 1.f);
}

```

Thanks, I've been trying to find an answer to this, but it seems very unusual to write out non-float values if it is possible.

# Answer
> 1 votes
I use a uint texture to store material ID's.

The shader output struct I use for this is and the ID constant:

```
uint matID;

struct PixelShaderOutput
{
 uint RenderMaterialID : SV_Target0;
};

```

Write to the output targets:

```
PixelShaderOutput PShader(PixelShaderInput input)
{
 PixelShaderOutput output = (PixelShaderOutput) 0;
 output.RenderMaterialID = matID;

 return output;
}

```

Then just read back the ID texture at a later stage in your render pipeline

```
Texture2D<uint> RenderMaterialIDs;
uint MatID = RenderMaterialIDs.Load(uint3(globalIdx.x, globalIdx.y, 0));

```

# Answer
> 0 votes
Pixel Shaders output float values that are converted to the appropriate format as they are placed into the Render Target. If you look at Direct3D feature levels, some feature levels support a `UINT` or `SINT` format for a render target. So if you returned `255.0`, it would write `255` into the `UINT` render target.

Otherwise you need to use DirectCompute.

---
Tags: shaders, directx11
---


# Question
Title: Cannot use my objects method when accessing from Stage LibGDX
I have a class `Card` with the method `setOwner`. I have set up my touch input to use a `hitActor` to identify touches by getting the `Actor`'s name like so :

```
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
   Vector2 hitCoord = stage.screenToStageCoordinates(new Vector2((float) screenX, (float) screenY));
   Actor hitActor = stage.hit(hitCoord.x, hitCoord.y, false);
    if (hitActor != null) {
            stage.getRoot().findActor(hitActor.getName()).setOwner();// here it doesnt identify the setOwner() method;
    }
    return false;
}

```

The problem is that it doesn't identify the method `setOwner()`. My `Card` actors are in a ListArray `deck` so I type casted them like so :

```
  for (Card c : deck) {
        c = (Card) stage.getRoot().findActor(c.getName() + c.getSuit());
    }

```

But still it doesn't identify the methods declared in the `Card` class. My goal is to call the method`setOwner` on the `Actor` that got touched.

# Answer
I am assuming your `Card` class extends `Actor`, but since `setOwner` only exists on `Card` you can't call it without casting the `Actor` to a `Card` first.

Also, since the hit test returns an `Actor` you shouldn't have to ask the `Stage` for it by name using the `findActor` method.

Consider changing your code to something like this;

```
if (hitActor != null && hitActor instanceof Card) {
    ((Card)hitActor).setOwner ();
}

```
> 0 votes

---
Tags: java, android, libgdx
---


# Question
Title: How do I make a sprite fire a bullet in a direction using SFML and C++?
I'm learning game programming for the first time using sfml and c++. I have sucessfully animated my sprite in all four directions watching some video tutorials. But now i want my sprite to fire in a facing direction. I just want to do it a very basic way. It would be great if i could get some idea of it. I am using xcode 7.

# Answer
What you want to do is to keep track of the player orientation when you update it. It can be as simple as setting a vector value when the player presses the movement keys. Something like

```
if (leftKeyPressed)
{
    playerForward = vec2(-1, 0)
}
if (rightKeyPressed)
{
    playerForward = vec2(1, 0)
}
if (upKeyPressed)
{
    playerForward = vec2(0, -1)
}
if (downKeyPressed)
{
    playerForward = vec2(0, 1)
}

```

Now, you can use the variable `playerForward` to set the movement direction and even initial position of the bullet. You probably want to spawn the bullets somewhere around the player, so you can use the movement direction and multiply it by a constant size to move it relative to the player's origin. Something like the following pseudo code should do.

```
if (shootKeyPressed)
{
    vec2 bulletPosition = playerCenter + playerForward * playerSize / 2;
    vec2 bulletVelocity = playerForward * Bullet::Speed;

    spawnBullet(bulletPosition, bulletVelocity);
}

```
> 1 votes

---
Tags: c++, 2d, game-design, sfml, xcode
---


# Question
Title: How to export unity project to play in HTC Vive?
I have an Unity project which I want to export and use in HTC Vive. How do I do that and in addition is there any resource online which I can use to refer how do I code to use the controllers for HTC Vive?

# Answer
> 4 votes
*So here is the answer for your different parts of questions(also for beginner VR developer with unity and HTC-Vive):*

1. **Instead of exporting your project into HTC Vive project** you are required to import Free **SteamVR Official Plugin** into your project. After exporting the plugin, you can bring **CameraRig** prefab (*from the prefab folder of the plugin*) into you main scene project in order to view it through your HTC Vive head set. (its simple, now you can watch your project through htc-vive)
2. If you are familiar with Unity and C# then you can easily work with VR. For Object interaction in VR & different purposes here comes the lovely **VRTK - SteamVR Unity Toolkit**. Its amazing, you can import it in to your project. It provides ***40 demo Scenes*** that defines different things like object interaction, door interaction or teleportation, movement etc etc. Simply you require to import the package and explore its demo scenes to understand it. It also provide very healthy **documentation**.
3. If you looking exactly for object interaction with your **Vive controller** you are required *Interactable Objec*t script in your object. You can follow its details here

So it is simple, you require SteamVR (its essential) and VRTK (its optional - to make VR development easy) in order to bring HTC-Vive application development into reality. (VRTK make HTC-vive development more simple and easy, thanks to VRTK team).

---
Tags: unity, virtual-reality, htc-vive
---


# Question
Title: What is wrong with this character slope math?
I'm making a sidescrolling platformer and have implemented some code that should convert the characters speed to an X speed and Y speed based on the angle of the surface they are on. This actual math for this was taken from a web page and I don't know if it's right or not.

```
// xSpeed and ySpeed are derived from speed, based on the angle
    xSpeed = speed * Mathf.Cos(angle);
    ySpeed = (speed * -Mathf.Sin (angle)) - gravity;

```

The angle is found with this code:

```
RaycastHit ground;
    Physics.Raycast (transform.position, Vector3.down, out ground, 1.5f);
    Debug.DrawRay (transform.position, Vector3.down.normalized, Color.green, 2, false);
    if (ground.collider != null)
    {
        angle = Vector3.Angle (ground.normal, Vector3.up);
    }
    else
    {
        angle = 0;
    }

```

This works fine when walking on a flat surface, but freaks out when walking on a slope. I believe the problem lies with the angle itself.

# Answer
> 1 votes
I think you want to get the angle between the horizontal "default" ground and the line formed by the surface of the slope. So I think the `angle = Vector3.Angle (ground.normal, Vector3.up);` should be changed to `angle = Vector3.Angle (ground.normal, Vector3.right);`

# Answer
> 0 votes
So, based on your description, it seems like you have an angle issue.

I don't know about unity, but it seems like you get the angle in degrees instead of radians.

To hopefully solve your issue, before you pass the angle to the sin and cos function, convert it to radians with the following formula:

```
rad = deg / 180 * PI

```

Side note: I'm seriously curious why unity returns the angle in degrees, when radians are arguably more useful.

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


# Question
Title: Mixing perspectives in an oblique-perspective game
I've been creating an adventure game using 45 degree angled tiles to create a 3D illusion- aka oblique style.

Using 45-degree angles...

I can create pretty much any size or shape building I want:

I found I can easily get another perspective if I simply flip the tiles horizontally:

While doing this gains an oblique perspective from the other way, it does change the vanishing point to be in the center of the map, versus towards the top left.

Is this style of mixing perspectives common? Does it ruin the perspective or add to it? I thought that just maintaining the point of origin at the top left the whole time would be monotonous.

**To be clear**, I wouldn't keep the two styles together. It'd be either like the buildings on the river or the buildings in the northwest.

Thanks

---

Edit: More of a full shot:

# Answer
Mixing perspectives is very uncommon and, at least in your example, is bad because the perspective of the foreground (buildings in front of the river) do not match those in the background. There is one notable game that uses mixed perspectives:

> *Zelda: A Link to the Past*

If you look carefully, there is no single vanishing point. The corner walls in particular are simply reused. The perspective makes no sense in this game.

However, it's not so bad in this game because the camera is fixed. The same advice applies to your game: if your camera is fixed, you can get away with this, with the buildings all oriented with respect to the camera. But if your camera is dynamic, either stick with a single orthogonal projection, or go with proper 3D perspective.

Also, noting that you tagged with , the classic Sierra/LucasArts adventure games had these static perspective scenes, but again the camera was fixed.

> *Police Quest*

This is because when the projection clashes with the camera, it disrupts the visual coherence of the scene, making the scene and the subjects seem out of place. I won't say you definitely can't do it, it may even be a distinctive style, but according to common practice it would be awkward.
> 2 votes

# Answer
The problem here is not technical, but more one of how perspective and projection work in the real world. Isometric "perspective" is, strictly spoken, already wrong, but looks realistic enough if you assume a very flat angle from a distance, so people have seen something roughly like it in real life, and don't really notice it's wrong.

Your mixed-isometric tiles look fine right now because you only have the one building, and it is in the middle, but real perspective gets smaller toward the back, and if you have angled buildings in the back that are the same size, it'll look wrong anyway, and if you can side-scroll, it'll be even more wrong, because usually buildings on the right have only their left walls visible, and buildings on the left only their right walls.

Just try it. No technical reason not to do it, it just starts looking too unrealistic, or subtly weird, if you mix perspectives. Can be useful as a fun Inception-style effect though.

If your curious about why this is this way, you may want to get a book about perspective drawing from the local art supplies store.
> 0 votes

---
Tags: tiles, tilemap, rpg, adventure-games
---


# Question
Title: Can I use assets from the Unity store in a non Unity project I host publicly?
I'm working on a simple game for university that I'm making using HTML and Javascript (not Unity) that I'd like to be able to put up on a public github repo and/or maybe host online somewhere. I'd like to use some free assets from the unity store on it.

I've read Can free Unity Store assets be used in non-Unity games? so using Unity Assets is probably alright but if I store my project on a public github repo, anyone would be able to access those assets from there and not need to use the Unity Store for those specific ones.

To quote the linked page, "The only catch appears to be that you must download the assets through Unity, and that you are purchasing a license for the asset."

Also, if it's okay to store Unity Store Assets in a public repo, how should I do it? Just put each asset within a separate folder with a text file containing its license?

Edit: I found this in the Unity Asset Store Terms of Service:

```
Unless you have been specifically permitted to do so in a separate
agreement with Unity and except as permitted under the Unity-EULA,
you agree that you will not reproduce, duplicate, copy, sell, trade
or resell any Asset that you have acquired from the Unity Asset Store
for any purpose.

```

So, is that a definite no to what I'd like to do?

# Answer
> 2 votes
No, it wouldn't be legal.

From here: http://answers.unity3d.com/questions/342714/use-of-asset-store-assests-in-commercial-game.html

> You can NOT re-distribute the file, no matter how much you modify it you can use it but not share or re-sell it.

and based on

> Unless you have been specifically permitted to do so in a separate agreement with Unity and except as permitted under the Unity-EULA, you agree that you will not reproduce, duplicate, copy, sell, trade or resell any Asset that you have acquired from the Unity Asset Store for any purpose.

from the terms of service which I quoted above, I'm fairly certain hosting any assets in a public repository would not be legal.

---
Tags: unity, legal
---


# Question
Title: Trouble with mouseover effect in SDL for square menu buttons
I have a game with a menu made up of 9 'tiles'. I want the tiles to turn white when the cursor hovers over them (and play a sound), and go back to default when the mouse moves off. My code works when the cursor is moved slowly, but when it is moved quickly the tiles don't turn back to the default colour when the mouse is moved off, resulting in multiple tiles staying white. I'm not sure if the problem is with my code or with SDL event polling. Below are the relevant code snippets, the full source can be found here

```
void MenuState::handleEvents(SDL_Event& e) {
    //(...)

    if (e.type == SDL_MOUSEMOTION) {
        int x; int y;
        SDL_GetMouseState(&x, &y);
        mousePos = getActiveTile(x, y);

        if (mousePos >= 0 && tiles[mousePos].tileType() != Tile::type::buttonpressed) {
            tiles[mousePos].setTileType(Tile::type::rollover);
        }
        else if (prevMousePos >= 0 && tiles[prevMousePos].tileType() != Tile::type::buttonpressed) {
            // if mouse is *no longer* inside button
            tiles[prevMousePos].setTileType(Tile::type::button);
            prevMousePos = -1;
        }
    }

    //(...)
}

int MenuState::getActiveTile(const int &x, const int &y) {
    int tilenum = -1;
    for (int i = 0; i < tiles.size(); ++i) {
        if ( !(x < tiles[i].position().x || x > tiles[i].position().x + tiles[i].position().w ||
               y < tiles[i].position().y || y > tiles[i].position().y + tiles[i].position().h) )
            tilenum = i ;
    }
    return tilenum;
}

void MenuState::update() {
    if (mousePos >= 0 && prevMousePos == -1) { // only play when mouse first touches button
        Mix_PlayChannel(-1, rollOver, 0);
        prevMousePos = mousePos;
    }
    //(...)

```

}

**the render function (the 'buttons' are held in a vector of 'Tile's)**

```
void Graphics::drawBoard(const std::vector<Tile>& t, const bool& drawnumber) {
    for (int i = 0; i < t.size(); ++i) {
        SDL_Rect temp = t[i].position();

        if      (t[i].tileType() == Tile::type::invisible)
            SDL_SetRenderDrawColor(renderer, 163, 118, 172, 1); // bg colour

        else if (t[i].tileType() == Tile::type::rollover || t[i].tileType() == Tile::type::buttonpressed)
            SDL_SetRenderDrawColor(renderer, 255, 255, 255, 1); // highlight colour

        else if (t[i].tileType() == Tile::type::shadow)
            SDL_SetRenderDrawColor(renderer, 100, 65, 107, 1); // shadow colour

        else
            SDL_SetRenderDrawColor(renderer, 237, 229, 239, 1); // default colour

        SDL_RenderFillRect(renderer, &temp);

        if (drawnumber){
            if (t[i].tileType() != Tile::type::invisible) {
                std::string num = std::to_string(t[i].number());
                tilenumber = renderText(num, "assets/Calibrib.ttf", fontcolour, 25);
                SDL_QueryTexture(tilenumber, NULL, NULL, &temp.w, &temp.h);
                renderTexture(tilenumber, temp.x+(TILE_SIZE/2 - temp.w/2), temp.y+(TILE_SIZE/2 - temp.h/2), nullptr);
            }
        }
    }

```

}

# Answer
Adapted from my comment:

If you only have 9 tiles, just iterate over all 9 every time. Set the one currently being hovered to rollover, and reset the other 8 to button. Don't bother remembering the previous mouse position and trying to reset just one (unless you have hundreds of tiles, and even then I would recommend this approach until you empirically find it to be too slow).

I replaced getActiveTile() with setActiveTile(), which takes a mouse position and corrects highlighting for all tiles. It still returns the ID of the currently hovered tile in case you need that information to perform some other actions (e.g. marking it as pressed when a click event happens, without having to search by coords again).

```
void MenuState::handleEvents(SDL_Event& e) {
    //(...)

    if (e.type == SDL_MOUSEMOTION) {
        int x; int y;
        SDL_GetMouseState(&x, &y);

        int hoveredTile = setActiveTile(x, y);
    }

    //(...)
}

// Still returns tile ID in case you need it for something else
int MenuState::setActiveTile(const int &x, const int &y) {
    int hoveredTile = -1;

    int tileCount = tiles.size();
    for (int i = 0; i < tileCount; ++i) {
        if ( !(x < tiles[i].position().x || x > tiles[i].position().x + tiles[i].position().w ||
               y < tiles[i].position().y || y > tiles[i].position().y + tiles[i].position().h) )
        {
            // Don't change style when hovered button is already being pressed
            if (tiles[i].tileType() != Tile::type::buttonpressed)
            {
                tiles[i].setTileType(Tile::type::rollover);
            }
            hoveredTile = i;
        } else {
            // If the mouse isn't over this button, it can't be "buttonpressed",
            // so no need to check that. Just reset it to a regular button style.
            tiles[prevMousePos].setTileType(Tile::type::button);
        }
    }

    return hoveredTile;
}

```

Minor Tip:

You're doing `++i` in your for loop, which I assume someone told you to do because it's "faster than `i++`". The more important optimization here is to take the `.size()` call out of the loop, because calculating the size of the (vector?) every iteration is wasteful.

When you don't care about processing order (we don't in this case), you can also write your loops like this:

`for (int i = tiles.size() - 1; i >= 0; i--) {`

Which will cause `.size()` to only be evaluated once. If this is actually an `std::vector`, you might consider using iterators as well.
> 0 votes

---
Tags: c++, sdl2
---


# Question
Title: Unity (5.4.1) networking: messages guaranteed to arrive?
In Unity (5.4.1). Are Commands, ClientRpcs and SyncVar calls/events guaranteed to arrive? Or are they fire and forget (like UDP protocol)?

# Answer
All High Level API calls are guaranteed to arrive (With exceptions where clearly specified on the documentation). in UNet, there is an Unreliable channel and a Reliable channel.

Unity builds its own custom transport protocol ontop of the UDP protocol. Unity also allow you access the transport layer through Low Level API calls

Some resources:
> 1 votes

---
Tags: unity, networking
---


# Question
Title: Keeping a Character Controller grounded?
I've got a character that makes use of `isGrounded()` to determine whether I can jump, whether my air-jump is reset, and the amount of friction to be applied. I've run into a common problem, `isGrounded()` is fluctuating every frame returning true and false randomly resulting in jagged movement.

The standard suggestion is to constantly apply gravity. Unfortunately, aside from any other more nuanced issues that this could result in, this only works for me if I apply so much gravity that I am no longer able to climb up slopes. I need a way to keep the character grounded without applying large amounts of gravity every frame.

# Answer
> 2 votes
A common cause of this problem is using the Physics resolver for determining if a character is grounded. The issue arises because the physics solver's whole purpose is to push your character and the ground apart (so they aren't inter-penetrating).

Tricks like increasing gravity work by attempting to force the character back into the ground each frame. This isn't very reliable, as you've mentioned, and increases the work of the physics engine and decreases physics stability.

Some physics engines can further attempt to resolve this problem using things like separation slop (which means the objects aren't *completely* pushed apart) or by maintaining a contact cache. Using these features to solve the gound detection problem can require some extra work, though; the results of testing for sloppy collision or querying the contact cache may require the use of different APIs or events than what you're currently using. I'm not super familiar with Unity physics so I can't provide any specific insight for your case.

A very generalized solution that works for almost engine is to use a separate means of detecting the ground which doesn't directly rely on your character's physics body. These can include short ray casts (e.g., shoot some rays down about 1/5th of a unit or so from the corners and center of the character's feet) to probe for the ground, or using a thin physics sensor (or several sensors) attached to the character's feet. These methods don't try to test if the character is touching the ground but instead test if the character is *really close* to the ground. It sounds hacky but works phenomenally well.

Using multiple rays or multiple sensors can also help you detect some interesting scenarios that the simpler physics-collision method has trouble with. For instance, if you want to detect if a character is standing on a ledge, the use of multiple rays or sensors can indicate this clearly (e.g. the left sensor indicates there's ground but the right sensor does not, thus the character is standing on a ledge).

Using several rays or sensors of increased height can supply further information. For instance, short rays might detect if the character is *very* near to ground (close enough that you can consider them grounded) while some slightly longer rays can indicate that the character is near ground. This can be used to inform animation, to control game features like double jump, or to help keep characters grounded when running down ramps (if the character was grounded and the next frame - no jumping involved - the character is only very near the ground, snap the character back down to the ground).

Physics engines and platformers aren't a good fit for each other. You have to muck around behind the physics engine's back using techniques like I've described to achieve that ideal Nintendo-like feel to your characters.

# Answer
> 0 votes
I've run into similar problems and realized my character's animation was causing the fluctuation because I had both the physics engine and an animation moving my character.

My solution was to avoid collider collision detection as my means of ground detection. Instead I use ray casting. See this answer here: http://answers.unity3d.com/questions/575637/ground-detection.html

For my character I use three rays and perform a count. If at least two rays hit the floor I consider my character grounded.

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


# Question
Title: Making a 2D Game: Figuring out sprite sizes?
I'm currently making a 2D game as a school project using Game Maker and its language. My concern however is around the spriting and art...

I can't figure out how to correctly size everything so it shows up correctly on the end product. I originally used a temporary 32x32 character but it looks very small when I have the "Room Size" in Game Maker set to 720p...

Is this something that I need to change size-wise on Game Maker, such as changing how far in the perspective/camera is, or do I have to set actual dimension rules? I'm unsure of how to do this properly.

# Answer
Since you are working on a 2D game, you don't have a perspective camera, but a projection camera. However, you don't need to deal with its settings, because Game Maker lets you deal with the problem by simply using *Views*.

A view lets you show the player only a portion of the whole room. This is useful both to hide some parts of the level to limit the player sight, and to keep the arts and graphics proportioned to a given aspect ratio, independently of the room width.

Read the documentation to learn more about Views, View Ports, and experiment until you get the expected result.
> 0 votes

---
Tags: sprites, game-maker, art
---


# Question
Title: Unity2D: Item selection previous button not working!
I'm having a problem with my item selection script. As you can see in the video, button 3 (when the previous button is pressed) goes straight to button 1, instead of going to button 2 and then button 1. Can anyone help me with this issue! Thank you. My script is listed below;

```
int activeObject = 0;
public GameObject tool01, tool02, tool03, tool04, tool05, tool06;
public int max_number_of_objects;

// in the button press code
public void Right()
{

        // increment the active object, wrapping around to 0
        activeObject++;
        if (activeObject >= max_number_of_objects) {
            activeObject = 0;
        }
        // here's another way to do this that eliminates the conditional logic
        // just pick one of them - don't do them both
        // look up the modulus operator (%)
        activeObject = (activeObject + 1) % max_number_of_objects;
        RightActivateObject (activeObject);
}

public void Left()
{
    activeObject--;
    if (activeObject <= 0) {
        activeObject = max_number_of_objects;
    }
    // here's another way to do this that eliminates the conditional logic
    // just pick one of them - don't do them both
    // look up the modulus operator (%)
    activeObject = (activeObject - 1) % 1;
    LeftActivateObject (activeObject);
}
    // activate the selected object
void RightActivateObject(int activeObject)
{
    switch (activeObject)
    {
    case 0:
        tool01.SetActive(true);
        tool02.SetActive(false);
        tool03.SetActive(false);
        break;
    case 1:
        tool01.SetActive(false);
        tool02.SetActive(true);
        tool03.SetActive(false);
        break;
    case 2:
        tool01.SetActive(false);
        tool02.SetActive(false);
        tool03.SetActive(true);
        break;
    }
}

void LeftActivateObject(int activeObject)
{
    switch (activeObject)
    {
    case 0:
        tool04.SetActive(false);
        tool05.SetActive(true);
        tool06.SetActive(false);
        break;
    case 1:
        tool04.SetActive(false);
        tool05.SetActive(false);
        tool06.SetActive(true);
        break;
    case 2:
        tool04.SetActive(true);
        tool05.SetActive(false);
        tool06.SetActive(false);
        break;
    }
}

```

# Answer
You don't need the tools4,5,6 and the modulus operator. That way you could merge both movements in a single method.

Example:

```
int activeObject = 0;
public GameObject tool01, tool02, tool03;
public int max_number_of_objects; //In this example is set to 3, 1 for each tool

// in the button press code
public void Right()
{

    // increment the active object, wrapping around to 0
    activeObject++;
    if (activeObject >= max_number_of_objects)
    {
        activeObject = 0;
    }
    ActivateObject();
}

public void Left()
{
    activeObject--;
    if (activeObject < 0)
    {
        activeObject = max_number_of_objects-1;
    }
    ActivateObject();
}
// activate the selected object
void ActivateObject()
{
    switch (activeObject)
    {
        case 0:
            tool01.SetActive(true);
            tool02.SetActive(false);
            tool03.SetActive(false);
            break;
        case 1:
            tool01.SetActive(false);
            tool02.SetActive(true);
            tool03.SetActive(false);
            break;
        case 2:
            tool01.SetActive(false);
            tool02.SetActive(false);
            tool03.SetActive(true);
            break;
    }
}

```

You could always have a list of elements, and use the count for the `max_number_of_objects`, but that's up to your implementation.
> 0 votes

# Answer
You need to try adding some sort of way of keeping the selection moving too far. Try putting all of the code that changes in a if statement tthat only if a boolean to be false.make it true at the end of the satement. then go into update to see if the statment is true, then have the program wait a certain amount of time to make it false again. I am not at a computer, so I can't give you an example.
> 0 votes

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


title: BRDF Incorrect specular highlights

text:
# Question
Title: BRDF Incorrect specular highlights
I'm currently attempting to implement BRDF lighting, and am hitting a bit of a snag with my specular term - the specular highlights aren't rendering correctly.

To make things simple, I'm using a single directional light rendering down the **Z axis only**, and manually specify the gloss/specularity of each of the following spheres.

Glossyness increases left to right, and Specularity increases bottom to top. Notice how the highlights seem shifted nearly 90 degrees upwards:

## Calculating the specular BRDF

I use the generic Fresnel Shlick eq:

For the NDF, I use the GGX Trowbridge-Reitz eq:

And for the Geometric Shadowing function, I use the Smith / Shlick-Beckmann eq:

```
vec3 BRDF_Specular(vec3 F0, vec3 1minusF0, vec3 WorldPos, vec3 Normal)
{
    vec3 LightDirection         = vec3(0, 0, -1);
    vec3 ViewDirection          = normalize(EyePos - WorldPos);
    vec3 HalfVec                = normalize(LightDirection + ViewDirection);
    float NdotL                 = clamp(dot(Normal, LightDirection), 0.0, 1.0);
    float NdotV                 = clamp(dot(Normal, ViewDirection), 0.0, 1.0);
    float NdotH                 = clamp(dot(Normal, HalfVec), 0.0, 1.0);
    float VdotH                 = clamp(dot(ViewDirection, HalfVec), 0.0, 1.0);

    float Roughness             = max(1.0f - Gloss, 0.0); // Turn into roughness
    float Roughness_2           = (Roughness * Roughness);
    float NdotH_2               = NdotH * NdotH;

    /*  Normal Distribution Function
        GGX (Trowbridge-Reitz) */
    float D0                    = (NdotH_2 * (a_2 - 1.0f) + 1.0f);
    float D                     = a_2 / (M_PI * (D0 * D0));

    /*  Fresnel
        Shlick  */
    vec3 Fs                     = F0 + 1minusF0 * pow(1.0 - VdotH, 5.0);

    /*  Geometric Shadowing
        Smith / Shlick-Beckmann */
    float k                     = a_2 / sqrt(2.0 / M_PI);
    float GV                    = NdotV / (NdotV * (1.0 - k) + k);
    float GL                    = NdotL / (NdotL * (1.0 - k) + k);
    float G                     = GV * GL;

    vec3 brdfspec               = vec3(max(( Fs * D * G ) / (4.0f * NdotL * NdotV), 0.0));
    return brdfspec;
}

```

I've been following so many different resources and mimicked many other implementations, and even reducing it down to this basic level I'm still having this issue. I don't know why I'm not getting proper results

I'm using a deferred renderer, I derive the World position of each fragment from the depth buffer, and store my normals in viewspace. I don't use a "Metalness" map, but instead use a single rgb specular map, hense why my Fresnel calculation uses Vec3's instead of floats.

# Answer
Turns out I had miscalculated my camera position ever since I switched to a third person camera.

This in turn made my viewing direction vector point in the wrong direction, and systematically broke all the subsequent calculations.
> 0 votes

---
Tags: opengl, shaders, graphics, lighting, pbr
---


title: Loading scene before load the level?

text:
# Question
Title: Loading scene before load the level?
I didn't understand this point yet. for me its complicated. What i'm trying to do is a level as loading scene work to appear before load the game level. when loading progress bar complete you have to press any button to play the game. Here is my script:

```
// game level01
// game level02
// loading scene

 public float progressBar;
 public void nextlevel() // this for button
{
 LoadNextLevel();
}

IEnumerator LoadNextLevel()
{
    AsyncOperation async = Application.LoadLevelAsync("level02");
    yield return async;

}

```

Example from "ninja gaiden black". when you select any level to play. loading scene show up. when complete loading the level. new word appear inform yo to press X to play.

# Answer
There are lots of options to do this, here's one:

Have a 'loading screen' scene (or prefab) that contains the progress bar, and load that one before you do your actual loading. SceneManager.LoadSceneAsync can do your actual loading, with the additive loading mode - this way you can keep the button press screen there until they press a button. Once the button is pushed you'd disable or destroy the 'loading screen' contents.

Note that LoadSceneAsync returns an object that has a progress variable, that can be used to progress the loading bar (however, In my experience it's not fully accurate and the value may need some tweaking).
> 1 votes

---
Tags: unity, scenemanager
---


# Question
Title: Calculate target angle to a certain Vector
I'm developing a 3D game in LWJGL. I have a player class and a monster class and I need the monster class to chase the player when the player is within a certain distance. For that I have the monster directional vector (let's call it monDirVector) and the directional vector that points from the monster to the player (let's call it dirToPlayer)

So the way my monster class works is that it increments its current rotation to match a target angle (this way I can simulate the walking + turning animation). Given this I need to calculate the target angle so that the monDirVector overlaps the dirToPlayer making the monster walk right towards the player.

How would I go about this?

Here's a diagram for better understanding of what I need.

I pretty much need to get the cº angle and assign it as the target angle for the monster. The aº is the monster current rotation and the bº is the angle between the two vectors. Both of these are known. Please notice that the monster can be oriented any way and the player can be in any quadrant relative to the monster. This stands for a problem because I can't simply subtract the angle towards the player to the current rotation of the monster.

I would really apreciate if someone helped me.

# Answer
> 2 votes
Working with angles can be really tricky, you have to properly define your coordinate system, the convention whether clockwise direction should be positive or negative and especially what range of angle values will take. So assuming that all angles are measured in the range -180 to 180 degrees (as implied by your diagram), then this will give you the desired results

```
// Pseudo Code
Update()
{
    float a = monster.getAngle();
    float c = player.getAngle();

    // Convert both angles in the 0 to 360 degree range for a clean workflow
    if (a < 0) a += 360;
    if (c < 0) c += 360;
    float desiredAngle = c - a;

    // Compute its acute counterpart
    if (desiredAngle > 180)
        desiredAngle -= 360;
    else if (desiredAngle < -180)
        desiredAngle += 360;

    // Advance the monster towards player by a predefined value
    a += Math.Min(deltaAngle, Math.Abs(desiredAngle)) * Math.Sign(desiredAngle);

    // Convert this angle back in the -180 to 180 degree range
    if (a > 180) a -= 360;
    else if (a < -180) a += 360;
    monster.setAngle(a);
}

```

The deltaAngle will be a small positive value (say 3 degrees) by which the moster will rotate itself in each frame.

On a side note, I would recommend against using this approach as it will only provide realistic results as long as the monster has fixed speed (when OTOH a running monster should have hard time changing its rotation as fast as a walking monster and thus providing unrealistic results). Instead use the steering behaviour for autonomous agents.

# Answer
> 0 votes
1. Subtract a and c.
2. If the result is negative, multiply by -1.
3. Assuming you are interested in the acute angle, if the result is \>180, subtract 2 * (result - 180)

# Answer
> 0 votes
Correct me if I am wrong, but your question could be simplified as whether to turn right or turn left towards the player. I inferred this as you are able to get the delta angle but not the direction of the delta angle. Another assumption I have is that this is 2D vectors. (Though it can easily be expanded into 3D)

Obtaining the direction is a rather simple. Consider the following 2 cases where blue and red are the possible target vectors.

1. Obtain the right vector by rotating the forward vector by 90 degrees.
This is simply `<x,y>` -\> `<-y,x>`
2. Dot the right vector against the target vector and take the sign of the result.
This would result in `1` for the blue vector and `-1` for the red vector
You can turn your monster left if the result is `-1` and right if the result is `1`
3. Keep turning the monster until the angle between target and forward is 0

---
Tags: opengl, vector, angles, trigonometry
---


# Question
Title: How to map intensity from dot product to float RGB from 0 to 1?
I'm getting the dot product of the surface normal and light position. The weird thing is the dot product is larger than 1.

Also, I want to map that intensity from 0-\>1 to Float RGB from 0-\>1. Here is my code related to the issue:

```
if (the_object->polys[curr_poly].shading == 1)
{
    // compute the dot product between the light source vector
    // and normal vector to surface
    normal.x = normal.x / Vector_Mag_3D((vector_3d_ptr)&normal);
    normal.y = normal.y / Vector_Mag_3D((vector_3d_ptr)&normal);
    normal.z = normal.z / Vector_Mag_3D((vector_3d_ptr)&normal);

    dp = Dot_Product_3D((vector_3d_ptr)&normal,
        (vector_3d_ptr)&light_source);

    // test if light ray is reflecting off surface

    if (dp > 0)
    {
        // now cos 0 = (u.v)/|u||v| or

        intensity = ambient_light + ( dp / (the_object->polys[curr_poly].normal_length));

        float r = the_object->polys[curr_poly].color.R*intensity;
        float g = the_object->polys[curr_poly].color.G*intensity;
        float b = the_object->polys[curr_poly].color.B*intensity;
        Color color = Color(r, g, b, 1);
        // intensity now varies from 0-1, 0 being black or grazing and 1 being
        // totally illuminated. use the value to index into color table

        the_object->polys[curr_poly].shade = color.ToUInt32();
}

```

Updated code:

```
bool bOnce = true;

float normx = normal.x;
float normy = normal.y;
float normz = normal.z;
float mag;
if (bOnce)
{
    bOnce = false;
    mag =Vector_Mag_3D((vector_3d_ptr)&normal);
}

// compute the dot product between the light source vector
// and normal vector to surface
normal.x = normx / mag;
normal.y = normy / mag;
normal.z = normz / mag;

dp = Dot_Product_3D((vector_3d_ptr)&normal, (vector_3d_ptr)&light_source);

```

updated code version 2 :

```
if (dp > 0)
                {
                    // now cos 0 = (u.v)/|u||v| or

                    intensity = ambient_light + ( dp / (the_object->polys[curr_poly].normal_length));

                    if (intensity > 1)
                        intensity = 1;
                    if (intensity < 0)
                        intensity = 0;

                    float r = (float)the_object->polys[curr_poly].color.R /intensity;
                    float g = (float)the_object->polys[curr_poly].color.G/intensity;
                    float b = (float)the_object->polys[curr_poly].color.B/intensity;
                    Color color = Color(r, g, b, 1);
                    // intensity now varies from 0-1, 0 being black or grazing and 1 being
                    // totally illuminated. use the value to index into color table

                    the_object->polys[curr_poly].shade =  color.ToUInt32();

```

calculating normal vector of the polygon

```
void calculateNormalLenth(Rasterizer *rasterizer, object* the_object, int index)
{
    unsigned int vertex_0, vertex_1, vertex_2;
    vector_3d u, v, normal;           // working vectors
    vertex_0 = the_object->polys[index].vertex_list[0];
    vertex_1 = the_object->polys[index].vertex_list[1];
    vertex_2 = the_object->polys[index].vertex_list[2];

    // the vector u = vo->v1

    rasterizer->Make_Vector_3D((point_3d_ptr)&the_object->vertices_local[vertex_0],
        (point_3d_ptr)&the_object->vertices_local[vertex_1],
        (vector_3d_ptr)&u);

    // the vector v = vo->v2

    rasterizer->Make_Vector_3D((point_3d_ptr)&the_object->vertices_local[vertex_0],
        (point_3d_ptr)&the_object->vertices_local[vertex_2],
        (vector_3d_ptr)&v);

    rasterizer->Cross_Product_3D((vector_3d_ptr)&v,
        (vector_3d_ptr)&u,
        (vector_3d_ptr)&normal);

    // compute magnitude of normal and store in polygon structure

    the_object->polys[index].normal_length = rasterizer->Vector_Mag_3D((vector_3d_ptr)&normal);
}

```

# Answer
> 1 votes
First of all:

```
normal.x = normal.x / Vector_Mag_3D((vector_3d_ptr)&normal);
normal.y = normal.y / Vector_Mag_3D((vector_3d_ptr)&normal);
normal.z = normal.z / Vector_Mag_3D((vector_3d_ptr)&normal);

```

This is not normalization. After you divided x by the vectors length, the next call to `Vector_Mag_3D` will obviously calculate a new, smaller length, hence your vectors direction will change. Calculate the length **once** and divide all three axis by the same value.

---

```
Dot_Product_3D((vector_3d_ptr)&normal,
    (vector_3d_ptr)&light_source);

```

After you fixed the first problem, at least `normal` should be normalized, what about `light_source`? Is it normalized? If not, normalize it.

If both vectors are normalized, the dot-product *can only* result in a number between negative one and one. If you still got a bigger number, either the vectors are not normalized or your dot-product calculation is wrong.

---
Tags: graphics, c, software-rendering
---


title: UE4 - Viewport mouselook always on

text:
# Question
Title: UE4 - Viewport mouselook always on
Does anyone know how to set mouselook to always on instead of having to click and hold the RMB?

I would press and hold a different hotkey to "disengage" mouselook and allow object selection. I was just wondering if there is an option to remap the current RMB functionality within UE4, or is it hard-coded into the editor? I'm used to using RMB as walk in a game, and have never made the switch to WASD (this goes back to the days of Doom on PC). Ideally I would like to keep my current movement mapping of RMB-A-S-D where RMB is move forward. I see where I can remap forward from 'W' but remapping it to RMB is not allowed as far as I can tell.

# Answer
> 1 votes
When you press the key you want to use to enable mouse selection, set a boolean variable to true and set the input mode to "UI only". When you release the key, set the boolean to false and the input mode to "Game only".

Then you just have to add forward movement when you press the right mouse button and the mouse selection boolean is false.

See example in image below where I used left shift to enable the mouse. I added this to the first person BP template and it seemed to work like you described. You may want to add a check disable mouse movement input if mouse selection is enabled, similar to how right click is disabled in the example.

---
Tags: unreal
---


title: Downloading levels in UE4

text:
# Question
Title: Downloading levels in UE4
I'm a total newbie to UE4. I need to make a game which downloads levels, actors, materials etc. every time it starts from the web. What is the best practice to do that? Is it possible using UE4 only or should I "wrap" it in something? Thank you

# Answer
> 1 votes
Have you considered just making your game HTML5? UE4 has an experimental option for HTML5 you can enable so it streams the levels on the fly.

Other options do exist, but they look pretty complex for beginners. Here's One

---
Tags: unreal-4
---


title: Selective Image Effects with Stencils

text:
# Question
Title: Selective Image Effects with Stencils
I am trying to create an image effect where only a part of the image has the effect applied to.

One way I can think of to do this is to define the portion of the image using the stencil buffer.

Stencil Mask Shader:

```
Stencil
{
    Ref 1
    Comp always
    Pass replace
}

```

Image Effect Shader:

```
Stencil
{
    Ref 1
    Comp equal
    Pass keep
}

```

OnRenderImage Function

```
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
    saturationPassMat = CheckShaderAndCreateMaterial(saturationShader, saturationPassMat);

    saturationPassTex = RenderTexture.GetTemporary(source.width, source.height, 24);
    Graphics.SetRenderTarget(saturationPassTex.colorBuffer, source.depthBuffer);

    Desaturate(source, saturationPassTex, saturation);

    Graphics.Blit(saturationPassTex, destination);

}

```

Applying the stencil portion of the image effect shader to any other object produces a desirable stencil effect (aka: it works).

**The Problem:**

By the time OnRenderImage is called, it seems that the stencil buffer has already been cleared. Changing `Ref` to 0 in the Image Effect shader will apply the effect to the entire screen. Any other value will result in a black screen. This can only mean that the stencil buffer has been cleared to 0.

Is there a way to prevent the stencil buffer from clearing? Or is this the right method to use the stencil buffer with image effects? Or perhaps there are other solutions that are still efficient, without the use of Stencils?

# Answer
> 1 votes
After 3 sleepless nights, here is a somewhat hacky solution in case no one else is able to provide a better answer.

Turns out, blitting directly to `destination` works in forward rendering.

```
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
    Graphics.Blit(source, destination, stencilMat);
}

```

Many down sides though. Firstly, any image effect applied prior to this script will be culled by the stencil buffer for some reason. Any image effect applied after will stop this from working. Try it and you'll know what I mean.

To get around this, one can use a second camera, setting the render target to a custom render texture. The code above stays the same, and should be attached to the second camera instead.

On the main camera, you can pass this render texture into your shader and use it as a mask. Setting the rendertarget does not seem to work for me at all, no matter what I try.

```
stencilMat.SetTexture("_MaskTex", cam2.GetMaskTex());

```

Since in my case I'm doing a desaturation, the shader would look something like:

```
col.rgb = lerp((col.r + col.g + col.b), col.rgb, maskCol.rgb);

```

---
Tags: unity, shaders, stencil, image-effects, shaderlab
---


title: How to Handle my Collisions in java

text:
# Question
Title: How to Handle my Collisions in java
I'm currently making a color switch game. All my obstacles are made out of 4 shapes of a different color. The shapes are in an array with their index being the same index as its color in a array of colors. The player is a ball or Ellipse shape with a color `curColor`. How do I see if it overlaps shapes with a different color?

# Answer
Perhaps using something like a quadtree might be of some use here. By splitting collision detection into two stages, first coarse then fine you don't waste time computing collision between distant objects.

Split your game world up into rectangles and populate with the stationary(?) obstacles. Each time your player ball moves, find what quads in the tree the bounding box of the player intersects with and return obstacles in these quads. With these, use a more precise collision detection method between the two shapes, using color of the shape as a predicate before checking.

It might be worth considering if obstacles are moving and you need to add them to the quad tree every frame anyway, just adding in colored obstacles which are relevant for collision detection.
> 1 votes

# Answer
If the other shapes are rectangles you could use this to check if a circle intersects with it:

```
double left  = //rectangle's most left coordinate
double bottom = //rectangle's most bottom coordinate
//etc
double centerX = //player (circle) center X coordinate
double centerY //it's y coord
double radius //radius of the circle

if(((left-centerX)*(left-centerX)+(bottom-centerY)*(bottom-centerY))<radius){
//it is intersecting
}

```

And then the same for the top and right coords replacing bottom with top, replacing left with (you guessed it) right and replacing \< with \>.

If the shape is a circle it will be just a little bit more complicated:

```
double r0 //radius of player
double r1 //radius of shape
double x0 //center X of player
double x1 //center X of shape
double y0 //center Y of player
double y1 //center Y of shape

double DX = x1 - x0;
double DY = y1 - y0;
double D = Math.hypot(DX, DY);
if(D<r0+r1){
//They are intersecting
}

```
> 1 votes

---
Tags: java, collision-detection
---


title: AI character doesn't walk on the floor

text:
# Question
Title: AI character doesn't walk on the floor
When I execute my game, I have this script that makes the tiger follow me, but he doesn't detect the terrain under him and ends up floating in the air.

---

These are the components, on the tiger.

This is the script `TigerChase`.

```
public class TigerChase : MonoBehaviour
{
    public Transform player;
    static Animator anim;

    void Start ()
    {
        anim = GetComponent<Animator> ();
    }

    void Update ()
    {
        if (Vector3.Distance (player.position, this.transform.position) < 20)
        {
            Vector3 direction = player.position - this.transform.position;
            direction.y = 0;
            this.transform.rotation = Quaternion.Slerp
                    (this.transform.rotation, Quaternion.LookRotation (direction), 0.1f);
            anim.SetBool ("IsIdle", false);

            if (direction.magnitude > 5)
            {
                this.transform.Translate (0, 0, 0.20f);
                anim.SetBool ("IsWalking", true);
                anim.SetBool ("IsAtacking", false);
            }
            else
            {
                anim.SetBool ("IsAtacking", true);
                anim.SetBool ("IsWalking", false);
            }
        }
        else
        {
            anim.SetBool ("IsIdle", true);
            anim.SetBool ("IsWalking", true);
            anim.SetBool ("IsAtacking", true);
        }
    }
}

```

# Answer
You have IsKinematic set to true on the Rigidbody. This is telling the physics engine, among other things, that you will apply gravity yourself. Your script does no such thing, so you either need to manually apply gravitational movement, or disable IsKinematic and use the built-in physics engine.
> 1 votes

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


# Question
Title: Sprite editor "minimum size" feature alternative in Unity 5
As you know , unity has been removed its `minimum size` feature in sprite editor multiple auto slice mode. In some pics Unity discovers a lot of tiny rubbish sprites for example as 4x3 or 10x5 pixels. Is there anyway to set minimum size for good auto slicing in Unity 5?

# Answer
let me say that I don't know any way to set a minimum size. You might already know everything I'm telling you, but I figured I could try.

One way to "fix" it would be deleting those "wrong sprites" using CMD + delete if you're on a Mac (it *may* be only delete on Windows). Plus, is it possible that when creating the sprite in Photoshop/Krita/Gimp/Anything else you accidentaly drew a tiny line or point that you can't see but is still seen as sprite? It happened to me more than once. Just delete carefully around the shapes you want to keep.

Hope this can help even if I don't have a direct answer.
> 1 votes

---
Tags: unity, sprites
---


title: Random noise based on seed

text:
# Question
Title: Random noise based on seed
I am currently working on a program that should generate random noise on a screen based on the 'coordinates' of a pixel. The coordinates should have the same color every time you restart the program. However, using the Java's util.Random, the results I get are not as random as I'd like:

I thought that if I used the combined coordinates (as in one integer formed from both coordinates next to eachother) each coordinate would have a different number. By using that number as a seed I expected to get a different random numbers for each coordinate to use for the rgb value of that coordinate.

This is the code I used:

```
public class Generate {

static Random Random;

    public static int TileColor(int x, int y){
        Random = new Random(Integer.valueOf(Integer.toString(x)+Integer.toString(y)));
        int b = 1 + Random.nextInt(50);
        int g = 1 + Random.nextInt(50);
        int r = 1 + Random.nextInt(50);
        int color = -Color.rgb888(r, g, b);
        return color;
    }
}

```

Is the pattern that the program creates due to the way java's Random function works or am I doing something wrong and should I try a different approach?

**Update:** I now tried to get rid of the problems surrounding concatenation by using the following code:

```
public static int TileColor(int x, int y){
            Randomy = new Random(y);
            Randomx = new Random(x);
            Random = new Random(Integer.valueOf(Integer.toString(Randomx.nextInt(1234))+Integer.toString(Randomy.nextInt(1234))));
            int b = 1 + Random.nextInt(100);
            int g = 1 + Random.nextInt(100);
            int r = 1 + Random.nextInt(100);
            int color = -Color.rgb888(r, g, b);
            return color;
}

```

Somehow, this also provided a (in my opinion) sufficiently random image:

This code does however reseed three times per pixel. Even though this is not a problem for me right now, I do consider changing this code in case I need better preformance later on.

# Answer
> 21 votes
Java's `java.util.Random` class usually gives you sequences of pseudorandom numbers which are good enough for use in games1. However, that characteristic only applies to a sequence of multiple samples based on a seed. When you reinitialize the RNG with incrementing seed values and only look at the first value of each sequence, the randomness characteristics will not be nearly as good.

What you could do instead:

* Use the same seed to generate whole chunks of pixels at a time. For example, when you need the color value of pixel 425:487, feed the coordinates 400:400 into the RNG, generate 10000 random colors and use the color at index 2587 (25 * 100 + 87). Chunks generated in that manner should be cached to avoid re-generating those 10000 random colors for every single pixel of that chunk.
* Instead of using a random number generator, use a message digest function to turn a coordinate pair into a color value. The output of most MDF's is unpredictable enough to fulfill most tests of randomness. The output is usually more than the 24 bit you need for an RGB value, but truncating them is usually no problem.

To improve performance you can combine message digest generation with chunks. Generate small chunks of pixels which are just large enough to use of the full length of one output of your digest function.

1 when it is absolutely essential that nobody can predict the next number, use the slower but less predictable `java.security.SecureRandom`

# Answer
> 13 votes
> The coordinates should have the same color everyone you restart the program

In that case, you'll want to use a deterministic noise function such as Perlin noise or simplex noise.

(See this question for some more information on Perlin noise with some pretty pictures.)

For the most part, using a built-in `random()` or similar function will give you different values every time you run the program, as they may use the clock as an input or some other pseudorandom value.

Another option is to generate a "noise map" once, offline, and then use that as your random number source later on.

In your implementation, you're concatenating the string representations of x and `y`. That is bad as it's not unique across the domain. For instance,

```
x    y   concatenated
40   20  4020
402   0  4020
10   10  1010
101   0  1010
12   34  1234
123   4  1234
1   234  1234

```

Good luck!

# Answer
> 9 votes
Let's see what you are doing exactly:

* You loop through all pixels one by one
* For each pixel, you use the concatenation of its coordinates as a seed
* You then start a new random from the given seed and take out 3 numbers

All this sounds alright, but you are receiving a pattern because:

Pixel at 1,11 and pixel at 11,1 are both seeded the number 111 so they are certain to have the same color.

Also, as long as you always cycle the same way, you can use only one generator, no need to use one for each pixel. One for the whole image will do! There are still going to be some sort of patterns because of pseudo-randomness. @David\_Lively is right about using some Noise algorithm, it will make it look more random.

# Answer
> 1 votes
Make a color generator, then produce your colors for your tile. Seed only once! You don't need to seed more than that, at least per tile.

```
public class RandomColorGenerator {
  private final int minValue;
  private final int range;
  private final Random random;
  public RandomColorGenerator(int minValue, int maxValue, Random random) {
    if (minValue > maxValue || (long)maxValue - (long)minValue > (long)Integer.MAX_VALUE) {
      throw new IllegalArgumentException();
    }
    this.minValue = minValue;
    this.range = maxValue - minValue + 1;
    this.random = Objects.requireNonNull(random);
  }

  public int nextColor() {
    int r = minValue + random.nextInt(range);
    int g = minValue + random.nextInt(range);
    int b = minValue + random.nextInt(range);
    return -Color.rgb888(r, g, b);
  }
}

public class Tile {
  private final int[][] colors;
  public Tile(int width, int height, RandomColorGenerator colorGenerator) {
    this.colors = new int[width][height];
    for (int x = 0; x < width; x++) {
      for (int y = 0; y < height; y++) {
        this.colors[x][y] = colorGenerator.nextColor();
      }
    }
  }

  public int getColor(int x, int y) {
    return colors[x][y];
  }
}

```

And the usage will be like follow:

```
RandomColorGenerator generator = new RandomColorGenerator(1, 100, new Random(0xcafebabe));
Tile tile = new Tile(300, 200, generator);
...
// getting the color for x, y:
tile.getColor(x, y);

```

With this if you're not happy with the result just change `Random` seed. Also, you only have to store/communicate the seed and sizes so that all the clients have the same image.

# Answer
> 1 votes
Instead of using Random, considering using a hash digest like MD5. It provides a hard to predict 'random' value based on a certain input, but always the same value for the same input.

Example:

```
public static int TileColor(int x, int y){
        final MessageDigest md = MessageDigest.getInstance("MD5");
        final ByteBuffer b = ByteBuffer.allocate(8);
        b.putInt(x).putInt(y);
        final byte[] digest = md.digest(b.array());
        return -Color.rgb888(digest[0], digest[1], digest[2]);
}

```

NOTE: I Don't know where Color.rgb888(..) comes from, so I don't know what the allowed range is. 0-255 is normal though.

Improvements to consider:

* Make MessageDigest and ByteBuffer variables outside of the class, to improve performance. You will need to reset the ByteBuffer to do that, and the method will no longer be Thread safe.
* The digest array will contain byte values 0-255, if you want other ranges, you'll have to do some math on them.
* If you want different 'random' results, you can add some kind of 'seed'. For example change to ByteBuffer.allocate(12), and add a .putInt(seed).

# Answer
> 1 votes
Others have pointed out that one way to get the behaviour you want is to use a hash function, aka "message digest function." The problem is that these are often based on algorithms like MD5, which is cryptographically secure (i.e. really, really, really random) but very slow. If you use a cryptographic hash function every time you need a random pixel you will run into quite severe performance issues.

However, there are non-cryptographic hash functions that can produce values that are random enough for your purpose while also being fast. The one I usually reach for is murmurhash. I'm not a Java user but it seems there is at least one Java implementation available. If you find that you really need to have each pixel be generated from its coordinates, rather than generating them all at once and storing them in a texture, then this would be a good way to do it.

# Answer
> 1 votes
I would use a prime over 2000 (max typical resolution)
This will minimize (or eliminate duplicate seeds)

```
public class Generate {

    static Random Random;

    public static int TileColor(int x, int y){
        Random = new Random(x + 2213 * y);
        int b = 1 + Random.nextInt(50);
        int g = 1 + Random.nextInt(50);
        int r = 1 + Random.nextInt(50);
        int color = -Color.rgb888(r, g, b);
        return color;
    }
}

```

# Answer
> 0 votes
`Random` is random enough. You're using it wrong for two main reasons.

* It wasn't designed to be repeatedly re-seeded. The random properties only hold for a single sequence of random numbers.
* There's huge correlation of `Integer.valueOf(Integer.toString(x)+Integer.toString(y))` between pixels that you're seeding with.

I'd just use some variation of the following code, where you can pick a hash function (don't use Integer.getHashCode) from the answers at https://stackoverflow.com/questions/9624963/java-simplest-integer-hash

```
public static int TileColor(int x, int y) {
    return hash(x ^ hash(y));
}

```

where the hash function could be

# Answer
> 0 votes
You could try using the systems current clock time as a seed like this:

```
Random random = new Random(System.currentTimeMillis())

```

Hopefully it produces a more random value.

# Answer
> 0 votes
Here is a one line static shader function I came up with - poltergeist (Noisy Ghost).

It takes a 2D coordinate and a seed, and renders in monotone as requested. It runs at realtime fps, regardless of screen resolution. This is what GPUs are for.

```
// poltergeist (noisy ghost) pseudo-random noise generator function
// dominic.cerisano@standard3d.com 03/24/2015

precision highp float;

float poltergeist(in vec2 coordinate, in float seed)
{
    return fract(sin(dot(coordinate*seed, vec2(12.9898, 78.233)))*43758.5453);
}

void mainImage(out vec4 fragColor, in vec2 fragCoord)
{
    fragColor = vec4(poltergeist(fragCoord, iGlobalTime));
}

```

Any resolution, any texture, on any device (mobile too) supporting GL (which is pretty much any with a screen).

See it running here, right now!

https://www.shadertoy.com/view/ltB3zD

You can easily include this shader in your java program using standard opengl, or in any browser using standard webgl.

Just for fun, I throw down the gauntlet for anyone to beat Poltergeist in quality and performance on all devices. Noisy Ghost rules! Undefeated!

---
Tags: java, random
---


# Question
Title: 3.3x OpenGL Camera - how to do 3d rotation?
I'm trying my hardest to understand what this code is doing so far I think the `sin(theta)` and `cos(theta)` of the code is representing a point with an angle.

This point with an angle `sin(theta)` and `cos(theta)` will allow the `xmouse/16` value and `ymouse/16` value to rotate or translate on this point with an angle because of their layout representation in the `GLM::LookAt()` function (view/camera matrix).

The result of doing this is that the view matrix rotates on the x axis left and right when I move the mouse left and right and the y axis up and down when I move the mouse up and down.

Is this correct? It took a lot work to understand this and if I am correct does anyone know how to move the mouse left, right, up and down from the centre of the screen (as in the mouse cursor at centre of the screen when moved to the left, right, up and down will move the camera respectively) rather then from a small region of the top left hand corner thanks!.

N.B.: I'm using Model Matrix and Perspective Projection Matrix with this in the middle so `Model * View * Perspective`

* C++ OpenGL 3.3x GLSL 3.30 CORE Windows 10

**Code:**

```
GLuint OpenGL_Engine::SetupViewCamera(GLFWwindow *RenderWindow, glm::vec3 eyepos, glm::vec3 originpos, glm::vec3 viewrotationpos, GLuint program, GLfloat RotAng)
{
    double xmouse = 0.0f, ymouse = 0.0f;
    glfwGetCursorPos(RenderWindow, &xmouse, &ymouse);

    double theta = glm::radians(RotAng);

    glm::vec3 camera(cos(theta), 0.0f, sin(theta));
    camera *= 5;
    glm::mat4 ViewMatrix = glm::lookAt(
    camera,
    glm::vec3(xmouse/16, ymouse/16, 0.0),
    glm::vec3(0.0, 1.0, 0));

    glm::mat4 IViewMatrix = glm::inverse(ViewMatrix);

    GLint Viewmatrixloc = glGetUniformLocation(program, "VM");
    glUniformMatrix4fv(Viewmatrixloc, 1, GL_FALSE, &IViewMatrix[0][0]);

    return 80;
}

```

# Answer
> -1 votes
all this code helped me it's some of it's from learn opengl that was the most frustrating thing to fix almost ever apart from my first attempts at a 3d model parser which is now piss to do it's literally just sscanf vertexs , sscanf faces and then use the faces as the index for the vertexes index in a loop of the entire vertexes those vertex\[face\_index\] hand that to your vertexbufferobject do a vao and set the attribpointer and uniforms appropriately and wala "something definitly along those lines" but here is most of the code for a 3d camera and if I missed anything their's the link directly enjoy finally -\> http://www.learnopengl.com

```
void mouse_callback(GLFWwindow* window, double xpos, double ypos);

// Camera
glm::vec3 cameraPos = glm::vec3(0.0f, 0.0f, 0.5f);
glm::vec3 cameraFront = glm::vec3(0.0f, 0.0f, -1.0f);
glm::vec3 cameraUp = glm::vec3(0.0f, 1.0f, 0.0f);

GLfloat yaw = -20.0f;   // Yaw is initialized to -90.0 degrees since a yaw of 0.0 results in a direction vector pointing to the right (due to how Euler angles work) so we initially rotate a bit to the left.
GLfloat pitch = 10.0f;
GLfloat lastX = 1280 / 2.0;
GLfloat lastY =  720 / 2.0;

        GLfloat currentFrame = glfwGetTime();
        deltaTime = currentFrame - lastFrame;
        lastFrame = currentFrame;
glfwSetCursorPosCallback(RenderWindow, mouse_callback);
    glfwSetInputMode(RenderWindow, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

glm::mat4 view;
        view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp);

if (glfwGetKey(RenderWindow, GLFW_KEY_W) == GLFW_PRESS)
        {
            cameraPos += cameraSpeed * cameraFront;
        }

        if (glfwGetKey(RenderWindow, GLFW_KEY_S) == GLFW_PRESS)
        {
            cameraPos -= cameraSpeed * cameraFront;
        }

        if (glfwGetKey(RenderWindow, GLFW_KEY_A) == GLFW_PRESS)
        {
            cameraPos -= glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed;
        }

        if (glfwGetKey(RenderWindow, GLFW_KEY_D) == GLFW_PRESS)
        {
            cameraPos += glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed;
        }

bool firstMouse = true;
void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
    if (firstMouse)
    {
        lastX = xpos;
        lastY = ypos;
        firstMouse = false;
    }

    GLfloat xoffset = xpos - lastX;
    GLfloat yoffset = lastY - ypos; // Reversed since y-coordinates go from bottom to left
    lastX = xpos;
    lastY = ypos;

    GLfloat sensitivity = 0.05; // Change this value to your liking
    xoffset *= sensitivity;
    yoffset *= sensitivity;

    yaw += xoffset;
    pitch += yoffset;

    // Make sure that when pitch is out of bounds, screen doesn't get flipped
    if (pitch > 89.0f)
        pitch = 89.0f;
    if (pitch < -89.0f)
        pitch = -89.0f;

    glm::vec3 front;
    front.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch));
    front.y = sin(glm::radians(pitch));
    front.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch));
    cameraFront = glm::normalize(front);
}

```

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


# Question
Title: Is it possible that elements in the StreamingAssets folder are not read in build?
I'm making a 2D game. In my StreamingAssets folder I have a JSON file with some info about inventory items (id, description, rarity, name, is stackable or not) and a png file which contains a pixel map (128x32) of the level I want to load after a first scene (this is from Quill18's tutorial: https://www.youtube.com/watch?v=5RzziXSwSsg , basically a specific color corresponds to a specific prefab. An object reads through all the pixels and then spawns the level). The fact is that I have issues with *both these elements when the game is built* (everything works perfectly in the game window in Unity): the inventory items don't collide with the player and the level is not loaded.

This is the code that gets the image name

```
public string levelFileName;
string filePath = Application.dataPath + "/StreamingAssets/" + levelFileName;
byte[] bytes = System.IO.File.ReadAllBytes (filePath);
Texture2D levelMap = new Texture2D (2, 2);
levelMap.LoadImage (bytes);

```

And the pickable objects basically have a collision detection script and have a specific ID, so that when they collide with the player, the inventory adds in a free slot an image with the specs correspondant to that ID (i.e. ID=1 then it's an health potion, is stackable, it's not rare and so on). Everything else works fine in the game. Do you think that the issue is linked to the StreamingAssets folder (first time using it) or is it just a coincidence? And also could you help me solve the problem? Thank you in advance for any kind of help.

Edit: my Player logs:

# Answer
> 1 votes
To me it looks like part of the code was simply not executed due to an error. You should get the logs for your build and check if you do not have any error.

You should not assume that because you do not have errors in the editor you will not have any in the build.

You can find the info here : unity logs

EDIT :

The streaming asset path might change depending on the platform you are building to or on the version of Unity you are Using you should use

```
Application.streamingAssetsPath

```

instead. All info here : Streaming assets path

---
Tags: unity, c#, streaming-assets
---


title: Implementing "Fix Your Time Step"

text:
# Question
Title: Implementing "Fix Your Time Step"
So far I have this implementation of "FYTS".

However I am facing several problems.

```
    final int TICKS_PER_S = 60;
    double accumulator = 0.0;
    //The timestep
    final double dt = 1/(double)TICKS_PER_S;
    long previousTime = System.currentTimeMillis();

    //State previous;
    //State current;
    while(running){

        long currentTime = System.currentTimeMillis();
        double frameTime = (currentTime - previousTime)/1000;

        if(frameTime > 0.25){
            frameTime = 0.25;
        }
        previousTime = currentTime;
        accumulator += frameTime;

        while(accumulator >= dt){

            //previousState = currentState;
            this.gamePanel.update(dt);
            accumulator -= dt;
        }

        //Interpolation
        // final double alpha = currentState * alpha +
        //               previousState * (1.0 - alpha);

        //This is the draw call. Not yet using interpolation
        this.gamePanel.postInvalidate();
    }

```

**Problem 1:**

frameTime is always 0 meaning that the game is never updating. It seems obvious: In the beginning it is 0, but that should change, shouldn't it?

**Problem 2:**

Let's assume that Problem 1 wouldn't exist. I understand that you take an arbitrary frameTime and split it up into discrete timesteps and then update the game. But what's the point of updating in a separate nested loop anyways? Most of the time you are left with a little remainder at the end of finishing the inner update loop. That remainder is how much of the simulation is left to complete until the running loop starts again and takes a new frameTime on which a part of the simulation has to be performed on. But what does the interpolation do that's worth to even consider doing it Isn't the inner update loop just a waste of time?

**Problem 3:**

The outer loop is running without any limitations at max speed. Isn't that just wasting clock cycles (and draining the battery life on mobile devices)? Is there anything I could do to counteract that?

# Answer
I'll only deal with **Problem 1** here since the rest should be clear to your from experimentation, once this bug is fixed.

It's Java: I think you need to convert `long <-> double` correctly. That would be why you're getting zero. Set up a very simple example where you just cast a `double` to a `long` and do vice versa with two separate variables, and see what happens. You should quickly see the problem. I believe the value is being truncated or somesuch. You can alternatively try using `long` for everything.

You are also involving an integer literal (`1000`) in that expression, further complicating type concerns. I suggest explicitly casting each term to double, and making `1000.0` i.e. a double.
> 1 votes

# Answer
**Problem 1**

The `frameTime` shouldn't be zero. That would mean your CPU is cycling through the operations in the loop within a millisecond of the system time. Does printing the `frameTime` value at the end of the loop always show it to be zero? If so, make sure your timing function provides you with the resolution you need to successfully determine the frame time.

**Problem 2**

The point of the nested update loop is to let the `update()` call catch up to missed frames. Physics simulations work best when the time step is fixed. If, for example, frames are dropped at some point during the simulation, the time step would usually change drastically leading to unpredictable simulation results. It is not possible to write reliable tests in such an environment.

Using an accumulator for the frame time makes it possible to re-update the game or simulation state for as many frames as were missed, keeping the update result consistent, predictable, and testable.

**Problem 3**

The impact of the outer run loop on performance depends on the operations it is performing. If you're only updating the accumulator during this time, the cost of the outer loop is negligible in comparison to the update loop. However, if you're drawing at the end of the outer loop, then you could have something to worry about.

In that case, you can run the draw call at a different rate, or only run it when the state is updated with changes that will be reflected by drawing.
> 0 votes

---
Tags: java, game-loop, interpolation, fixed-timestep
---


title: The best way to make collisions

text:
# Question
Title: The best way to make collisions
I'm making a 2d game, all is working, I have the characters and the map. The player have 6 different weapons and now I'm trying to make the collisions and the life / destruction system.

I have a character that follows the player. I made two triggers for this character and one for the player. When the player approaches, begins to haunt him, and when are near this character stop walking. To do this I programmed a "OntriggerEnter2d" and all is good, but now, I need to do anything similar with the bullets (or not). I tried OntriggerEnter2d and not works as expected, this detects the enter on the first zone of the bigger trigger, and I only need to detect the collision with the "body" of the characters.

Well, the question is, what is the best way to do the collisions between bullets and characters / objects??

Sorry if I explained bad the situation.

# Answer
> 0 votes
Well, finally I found the solution (thank you DarkDestry!). The mistake was assign the bullets to the player.

Now, I have the bullets separated from the character and I used layers to separate the colisions for the characters and the bullets.

Working perfect now.

# Answer
> 0 votes
You can probably solve this using tag comparison. Tag the player as `Player` and inside your bullet code,

```
void OnTriggerEnter2D(Collider2D other) {
    if (!other.CompareTag("Player")) return;

    //Your code here
}

```

This makes it that the bullet ignore any trigger that is not tagged as the player.

---
Tags: unity
---