# Question
Title: Parallel Storylines - Underused Francise Characters
**One Hero Rule:** Video games have only one protagonist. Example: in an rpg, party members are not seen in a field map, or they just follow you. Their role is "cannon fodder" tier, meaning who the hell cares if it dies. I never added it to my party anyway, following the min max gamefaq guide telling me to remove all its equipment beforehand. You end up with a video game that has only a single actor that plays 1000 tropes, in real life each person plays ~5 tropes at most. This is a bug caused by a single protagonist rule, i want to eliminate this rule through smart game design.

The problem is, in movies you can depict unlimited different characters and the story continuity never breaks, but in a video game leads to loss of context, can it be done? conclusion: video games are an inferior mean of screenplay.

In Suikoden / Breath of fire 4, each chapter is devoted to a specific protagonist view, this is nice concept however it can get ankward...

**Loss of context:** You would end up progressing their individual character storylines a little bit, but since you "switched context" to another protagonist, you lost track of what the other protagonist did, you no longer remember the progression of the story. This will never work... Especially if switch happens very frequently and the battles last too long.

**Game Balance: Extra party members do not add to battle effectiveness:** in suikoden by endgame you have 200 party members but they are irrelevant since random encounters use only 4 party members. It is better to keep the same cast throughout the game and become overleveled than spread xp to never used party members.

Android "Pimp your money" games fixes this by adding a 30 min cooldown to each party member. This is nice, but they don't have story... Also this mechanic enforces a "play everyone a little bit", disables free choice of which party member to pick, amplifying your loss of context.

Why i want this? imagine a game like kingdom hearts where each party member gets its own storyline.

Questions:

1) Need Story-Telling Methods that avoid loss of context.

2) Need Battle Game Balance Rules.

# Answer
> 8 votes
The reason why there always seems to be only room for one protagonist in a game's story is because it is inherit in the medium that there is just one "real" protagonist: The player. The player will always feel that they are the main character in the story, no matter how well-developed the personality of the actual player-character is. You can tell by the way players describe their experiences in games. They never say something like "I walked *protagonist* to the dungeon and had him kill the boss" they say "**I** went to the dungeon and killed the boss". This is why changing the viewpoint character feels so weird in games. You used to be one person and now you are suddenly a completely different person.

However, when you want a plot where multiple characters share equal amounts of attention, then there is a frequently used technique for that: Make the protagonist as unimportant and bland as possible so they don't steal the spotlight from the characters you actually want to focus on. Acknowledge that the player-character exists by having characters talk to them (which means having them talk directly to the player), but don't show them on-screen, don't have them talk and don't give them any characterization and most importantly don't give them any personal story-arcs. You might not even have them participate in the game mechanics. You could, for example, make the player the team commander who makes all the decisions (as players tend to do in RPGs), but doesn't get involved in combat directly.

Now with the PC out of the way, you can make the secondary characters as colorful and interesting as you want without them getting overshadowed. But don't overdo the number of plot-relevant characters in your game. The amount of characters the player can keep track of in a game will always be lower than in non-interactive media. The reason is that in non-interactive media, the reader/viewer/listener pays 100% attention to the story. In a game, the player's attention is divided between story and mechanics. (good game designers try to blur the lines between story and mechanics so there is no longer a competition between the two, but it isn't always possible to do this, especially if you don't want to leave the confines of a well-established classic genre like JRPGs)

So when you have over about a dozen playable characters, no player will be able to bond with all of them and in the end they will end up bonding with none of them. That means the budget you spent on the individual storylines will be wasted. So either keep the number of characters low, or have a clear distinction between a few "A list" characters who get detailed backgrounds and personal plots and a large pool of "B list" characters who don't.

Regarding creating a combat system which allows a large number of characters to get screentime:

The easiest would be simply to design a combat system which supports a very large player-party. Instead of the typical JRPG combat system with two parties on opposite sides exchanging attacks you might want to go for a Strategy-RPG combat system with grid-based movement and complex terrain (Disgaea, Final Fantasy Tactics, Fire Emblem...).

But if you want to stick to the JRPG combat system with just about 4 characters at once, then you need to encourage the player to switch their party members frequently.

* Add a fatigue mechanic. The most common fatigue mechanic are MP points. Force the player to spend MP even in trivial battles and give very few opportunities to recover MP points between battles. That will force the player to replace characters when they run out of MP. Fatigue mechanics can appear in different ways than just MP points. Common examples are ammo count, Vancian magic systems or literal fatigue represented with temporary stat decreases.
* Make characters highly specialized and add a lot of battles specifically tailored for specific characters. When even the most balanced 4 character party can not win every battle in the game, then players will have to change their party composition regularly.
* Encourage switching party members even while in combat. An easy way to do this is by making in-combat healing and reviving expensive and in-combat party switching cheap. Players get encouraged to replace casualties with less used characters. That way a hard boss battle won't be won by burning through almost all healing items but rather by burning through the whole party roster. Allowing to switch party composition easily during combat is also important to avoid frustration when you follow the previous point (highly specialized battles).

But even when you encourage party rotation a lot, it might still occur that one or two characters slip past the player's attention, fall so far behind that getting them back to the average level of the party becomes a chore (or even mechanically impossible) and they end up getting ignored for the rest of the game. Possible workarounds are:

* Keep the progression curve relatively flat, so characters who fall a few levels behind are still effective.
* Whenever the main party gains exp, also give xx% of those exp points to the unused characters so they don't fall behind.
* Encourage players to backtrack and revisit older locations with easier battles. This presents a good opportunity to level up weaker characters.

---
Tags: game-design, game-mechanics, rpg
---


# Question
Title: Screen not rendering after restarting game
Game works fine on the initial launch on Android, but after that restarting game does not render the graphics on the screen properly.

It is a copy of the question Sprites not being rendered on screen change - Android Libgdx

but there is no solution yet for the question

# Answer
> 2 votes
Most probably that's because of the loss of OpenGL context and the way Android handles Activity finish (process/task of the app may not be destroyed when main activity is closed).

Check out this Stackoverflow answer for more details:

https://stackoverflow.com/questions/12508769/libgdx-app-exit-on-android-not-closing-application

Quote:

> You have rediscovered the mismatch between the lifetime of Java objects (tied to the life of the application process) and the lifetime of texture objects (tied to the life of the OpenGL context which is tied to the visibility of the Activity).
>
> On app "exit", just the Activity is exited, and Android is caching the process in the background. When you "restart" the app Android just starts a new Activity in the same process. In this case the Activity is finding a valid Java Texture object, but the underlying bytes it "points to" in the OpenGL context are gone (since the OpenGL context is invalidated when the Activity is no longer visible).
>
> The fix is to re-load textures on activity creation. You must make sure all your objects that contain textures (and objects that contain objects that contain textures, etc) are tied to the Activity lifecycle. Generally this means avoiding static variables (which are part of the application lifecycle), but you can jump through hoops to invalidate and re-initialize globals if you want.

# Answer
> 0 votes
You can make a very simple fix for this problem. If the application process after its closure is unnecessary, you can simply kill it. In this case, when you restart the application, it will have to re-initialize the static variables.

```
public class AndroidLauncher extends AndroidApplication {

    //... some code ...

    @Override
    protected void onDestroy() {
        android.os.Process.killProcess(android.os.Process.myPid()); // this line will kill process
        super.onDestroy();
    }
}

```

---
Tags: android, libgdx
---


title: Where to put rigidbody on a car model ?

text:
# Question
Title: Where to put rigidbody on a car model ?
I have a GameObject car like this:

* MyCar
    + Body with mesh collider
    + Wheel Left with wheel collider
    + Wheel Right with wheel collider
    + ... and so on

Where I have to put rigidbody ?

Thanks

# Answer
The Rigidbody should go at or above the level of all colliders you want to include in the car.

So this:

* Car (has Rigidbody)
    + Body (has MeshCollider for the car's frame)
    + Wheel (has WheelCollider)
    + etc.

Or this

* CarBody (has Rigidbody and MeshCollider for the car's frame)
    + Wheel (has WheelCollider)
    + etc.

Or even this

* Car (has Rigidbody)
    + CarContainer
        - NestedContainer
            * Body (has MeshCollider for the car's frame)
        - FrontWheelsContainer
            * Wheel (has WheelCollider)
        - Rear WheelsContainer
            * Wheel (has WheelCollider) -etc.

Are all valid options.

I usually put the Rigidbody at the topmost level of the hierarchy for the object, since only content at or below the Rigidbody's level will move with it according to physics inputs - this keeps everything I think of as related to the same unit/object moving together.
> 5 votes

---
Tags: unity
---


# Question
Title: How to determine whether the direction of rotating a 2D vector to another one is counter-clockwise or clockwise using the cross product?
```
Vec2 a, b; // some random vector
Vec2 cross = a.Cross(b);
RelativeDirection(a,b,cross); // return true if the direction of
                              // rotating a to b is counter-clockwise

```

How do I implement the function `RelativeDirection()`?

I got some suedo code from the textbook:

```
if a.Cross(b) > 0 then ... else ...

```

but the cross product is a vector right? how do you compare it with an integer?

# Answer
> 4 votes
I think the book means

```
if a.Cross(b).z > 0 then ... else ...

```

which translates to

```
if (a.x * b.y - a.y * b.x > 0)

```

(depending on coordinate system, you may need to replace `>` with `<`)

---

Essentially this works in the same way as dot product trick from the second part of Stephane Hockenhull answer, just rewritten in a short way. Contrary to what that answer says, you don't need to normalize your vectors beforehand.

# Answer
> 1 votes
You check the angular 2D direction of both vectors and see if the difference (modulo a full circle) is positive or negative (or 0 or 180 degrees).

```
double diff = (atan2(a.y, a.x) - atan2(b.y, b.x));
if(diff < -M_PI){
   diff += M_PI * 2;
}
if(diff > M_PI){
   diff -= M_PI * 2;
}

return (diff > 0);

```

Which ever return value (true or false) means clock-wise or counter-clockwise depends on your Cartesian system (positive Y going up or down, positive X going left or right).

Anything close to zero (both vectors pointing in the same direction) or 180 degrees (pointing opposite) will give a result depending on rounding-errors so you'll probably want to add a check for \[almost 0 degrees\] and \[almost 180 degrees\].

You may need to check for these cases before checking for CW/CCW:

```
// a and b need to be normalised for this error-margin check to work
// the other two code samples to check CW/CCW don't need normalised vectors but this check does
double dot = DotProduct(a, b);
double margin = cos(error_margin_as_angle_in_radiant);
if(dot > margin){
   return SAME_DIRECTION;
}
if(dot < -margin){
   return OPPOSITE_DIRECTION; // we can't tell if CW or CCW
}

//... continue with the above CW/CCW check here ...

```

Alternatively you can use the dot product of one of the normalised vectors rotated by 90 degrees and the other one as-is:

```
Vec2 rotated_a(a.y, -a.x);
return DotProduct(rotated_a, b) > 0;

```

---
Tags: c++, vector, linear-algebra
---


# Question
Title: Tile based game. Fixing surface issue for attack
So far I've loaded the images and can move the sprite around. When I hit the spacebar to cycle through the attack sprites within the `attack_front` list. The image becomes compressed, because the sword is now extending outwards. How would I go about keeping the image in the same location and only extending the surface I print it on for these images? I've tried just adjusting the surface in my get\_image method, but the image skips around on the screen when you move.

I've made a gist and uploaded the spritesheet I'm utilizing to imgur and the links are below.

```
#!/usr/bin/python
import pygame as pg
from settings import *

class Spritesheet:

def __init__(self, filename):
    self.spritesheet = pg.image.load(filename).convert()

def get_image(self, x, y, width, height):
    image = pg.Surface((width, height)) #tried resizing this to specifc w & h, but made image skip around
    image.blit(self.spritesheet, (0,0), (x, y, width, height))

    image = pg.transform.scale(image, (150,150))
    return image

class Player(pg.sprite.Sprite):

    def __init__(self, game):
        pg.sprite.Sprite.__init__(self)
        self.game = game
        self.walking = False
        self.standing = False
        self.current_frame = 0
        self.last_update = 0
        self.image = self.game.spritesheet.get_image(9, 108, 18, 23)
        self.load_images()
        self.rect = self.image.get_rect()
        self.rect.center = (WIDTH / 2, HEIGHT / 2)
        self.x = 0
        self.y = 0

    def update(self):
        self.animate()
        self.x = 0
        self.y = 0
        keys = pg.key.get_pressed()
        if keys[pg.K_LEFT]:
            self.x = -3
        if keys[pg.K_RIGHT]:
            self.x = 3
        if keys[pg.K_UP]:
            self.y = -3
        if keys[pg.K_DOWN]:
            self.y = 3

        self.rect.x += self.x
        self.rect.y += self.y

    def load_images(self):
        self.standing = {'front': self.game.spritesheet.get_image(9, 108, 18, 23),
                         'back': self.game.spritesheet.get_image(79, 10, 17, 21),
                         'right': self.game.spritesheet.get_image(8, 190, 18, 21)}

        self.standing_left = []

        self.walking_bck = [self.game.spritesheet.get_image(106, 108, 18, 23),
                            self.game.spritesheet.get_image(138, 109, 18, 22),
                            self.game.spritesheet.get_image(170, 107, 18, 24),
                            self.game.spritesheet.get_image(200, 107, 18, 24),
                            self.game.spritesheet.get_image(232, 107, 18, 24),
                            self.game.spritesheet.get_image(263, 108, 18, 23),
                            self.game.spritesheet.get_image(296, 109, 18, 22),
                            self.game.spritesheet.get_image(328, 107, 18, 24),
                            self.game.spritesheet.get_image(360, 107, 18, 24),
                            self.game.spritesheet.get_image(391, 107, 18, 24)]

        self.walking_fwd = [self.game.spritesheet.get_image(103, 189, 18, 22),
                            self.game.spritesheet.get_image(136, 189, 18, 22),
                            self.game.spritesheet.get_image(168, 187, 18, 24),
                            self.game.spritesheet.get_image(200, 186, 18, 25),
                            self.game.spritesheet.get_image(230, 187, 18, 24),
                            self.game.spritesheet.get_image(262, 189, 18, 22),
                            self.game.spritesheet.get_image(293, 189, 18, 22),
                            self.game.spritesheet.get_image(326, 187, 18, 24),
                            self.game.spritesheet.get_image(360, 186, 18, 25),
                            self.game.spritesheet.get_image(390, 187, 18, 24)]

        self.walking_right = [self.game.spritesheet.get_image(100, 151, 23, 22),
                             self.game.spritesheet.get_image(134, 152, 20, 21),
                             self.game.spritesheet.get_image(168, 152, 20, 21),
                             self.game.spritesheet.get_image(199, 151, 20, 22),
                             self.game.spritesheet.get_image(229, 151, 20, 22),
                             self.game.spritesheet.get_image(258, 151, 23, 22),
                             self.game.spritesheet.get_image(292, 151, 19, 22),
                             self.game.spritesheet.get_image(327, 151, 19, 22),
                             self.game.spritesheet.get_image(360, 151, 19, 22),
                             self.game.spritesheet.get_image(389, 151, 20, 22),]

        self.walking_left = []
        for frame in self.walking_right:
            self.walking_left.append(pg.transform.flip(frame, True, False))

        self.attack_front = [self.game.spritesheet.get_image(0, 229, 28, 22),
                             self.game.spritesheet.get_image(38, 228, 25, 25),
                             self.game.spritesheet.get_image(80, 227, 19, 33),
                             self.game.spritesheet.get_image(114, 227, 19, 34),
                             self.game.spritesheet.get_image(151, 228, 25, 33),
                             self.game.spritesheet.get_image(193, 227, 29, 32),
                             self.game.spritesheet.get_image(238, 227, 31, 24),
                             self.game.spritesheet.get_image(285, 228, 32, 23),]

    def animate(self):
        now = pg.time.get_ticks()
        keys = pg.key.get_pressed()
        if self.x or self.y != 0:
            self.walking = True
        else:
            self.walking = False

        if self.walking:
            if now - self.last_update > 100:
                self.last_update = now
                #bottom = self.rect.bottom
                if keys[pg.K_DOWN]:
                    self.current_frame = (self.current_frame + 1) % len(self.walking_bck)
                    self.image = self.walking_bck[self.current_frame]

                if keys[pg.K_UP]:
                    self.current_frame = (self.current_frame + 1) % len(self.walking_fwd)
                    self.image = self.walking_fwd[self.current_frame]

                if keys[pg.K_LEFT]:
                    self.current_frame = (self.current_frame + 1) % len(self.walking_left)
                    self.image = self.walking_left[self.current_frame]

                if keys[pg.K_RIGHT]:
                    self.current_frame = (self.current_frame + 1) % len(self.walking_right)
                    self.image = self.walking_right[self.current_frame]

        if keys[pg.K_SPACE]:
            self.current_frame = (self.current_frame + 1) % len(self.attack_front)
            self.image = self.attack_front[self.current_frame]

```

Code: https://gist.github.com/crushedhat/95ab270d723a8d7fb45721f1cad93ee4
Spritesheet: https://i.stack.imgur.com/eMKLQ.jpg

# Answer
My advice is to normalize all your animation frames so that they are the same size. That way, your player's rect never changes and in your game's `draw()` method you can always just render the player's image at the player's `rect` without having to worry about variable sizes. Use a rect size that can accommodate the largest animation frame you have. This is what I do when I use Pygame.

If you're worried about such a large rect giving you problems with collision and so on—don't. You can define a `bounding_rect` object for your player with which to calculate collisions. The bounding rect should be significantly smaller than the rect and should sit inside it.

I would also suggest creating a position attribute, `pos`, for your `Player` class. This is what you should change when you do input processing. It's your `pos` attribute which changes when you press a direction key. Your `bounding_rect` will simply follow your position, and the larger `rect` you're using for blitting images will simply follow your bounding rect.

Here's an image:

And here's some example code:

```
if keys[pg.K_LEFT]:
        self.pos.x = -3 .                                   # update position
        self.bounding_rect.centerx = self.pos.x             # the bounding rect is centered at your position
        self.rect.midbottom = self.bounding_rect.midbottom  # the rect you use to blit the image simply follows along

```
> 1 votes

---
Tags: python, pygame
---


# Question
Title: Can you access the vertices passed into GLSL as an array?
So in the vertex shader I receive my vertex data as:

```
layout(location = 0) in vec3 position; //(x,y,z) coordinates of a vertex
layout(location = 1) in vec3 norm; //a 3D vertex representing the normal to the vertex
layout(location = 2) in vec2 texture_coordinate; // texture coordinates

```

In particular I would like to access the first 2 fields as if they were arrays (Imagine an SSBO).

The reasoning for this is because I need the mesh information not only to render the mesh itself but also to shade (shadows). An obvious solution is to simply pass the mesh data as well as an SSBO, but this means that now I have passed twice the same information into the GPU once as vertices for rendering and once as mesh data.

I would like to be able to access all the vertex data as if it was an array, is this possible?

# Answer
The obvious answer is to pass the data once: as a storage buffer. Period.

Nobody's *forcing* you to use vertex attributes, after all. You can use `gl_VertexID` and `gl_InstanceID` to (mostly) access the right vertex data for what you're rendering.

Of course, this means that you now need to have tight coupling between the vertex format and the shader that reads it. And if you want to compress your vertex data in any way (using normalized integers or 16-bit floats or whatever), you'll have to uncompress it manually in the shader.

But otherwise no, you cannot simply pretend that a vertex attribute is an array.
> 2 votes

---
Tags: opengl, rendering, glsl, shadows
---


title: Algorithm for a rain effect (Shaders)

text:
# Question
Title: Algorithm for a rain effect (Shaders)
I'm trying to implement a rain effect using shader, I use godot 3-alpha, which uses a simplified GLSL 3.0 language. But I'm just finding very complex examples for me, I understand little about shaders, I wanted to achieve something very basic even to be able to walk. I thought of doing the following, moving the texture with just a few painted pixels. Yet I still do not know where to start.

I found this code, I really wanted to understand what is done in it:

http://www.glslsandbox.com/e#36547.0

I managed to translate the code for godot 3, but it does not work very well, I believe this line is to blame:

```
p=0.5+0.35*sin(11.0*fract(sin((s+p+scale)*mat2(vec2(7,3),vec2(6,5)))*5.0))-f;

```

What really is done that line? I can not understand what he does.

I did so:

```
shader_type canvas_item;

uniform float direction;
uniform float velocity = 1.0;
uniform float intensity;

float snow(vec2 uv, float scale, float time)
{
    float w = smoothstep(1.0,0.0,-uv.y*(scale/10.0));
    if(w<0.1){return 0.0;}
    uv+=time/scale;
    uv.y-=time*velocity/scale; //VELOCITY
    uv.x+=sin(uv.y+time*0.5)/scale;
    uv*=scale;
    vec2 s=floor(uv);
    vec2 f=fract(uv);
    vec2 p;
    float k=3.0;
    float d;
    vec2 t = (s*p*vec2(scale))*mat2(vec2(7.0, 3.0), vec2(6.0,5.0));
    p.y=-(0.5+0.35*sin(11.0*fract(sin((s.y+p.y+scale)*t.y)*5.0))-f.y);
    p.x = f.x;

    d=length(p);
    k=min(d,k);
    k=smoothstep(0.0,k,sin(f.x+f.y)*0.01);
    return k*w;
}

void fragment(){
    vec2 uv=(COLOR.xy*2.0-SCREEN_UV.xy)/min(SCREEN_UV.x,SCREEN_UV.y);
    float c=smoothstep(1.0,0.3,clamp(uv.y*0.3+0.8,0.0,0.75));
    c+=snow(uv, 30.0, TIME)*0.3;
    c+=snow(uv, 20.0, TIME)*0.5;
    c+=snow(uv, 15.0, TIME)*0.8;
    c+=snow(uv, 10.0, TIME);
    c+=snow(uv, 8.0, TIME);
    c+=snow(uv, 6.0, TIME);
    c+=snow(uv, 5.0, TIME);
    c+=snow(uv, 2.0, TIME);
    COLOR = vec4(vec3(c),0.5);

}

```

and this happens:

I have discovered that by decreasing the value I am passing to the scale, it increases the "particles", I mean how octaves in a noise, the smaller the number last, the greater the peaos generated. But my screen seems to be divided in two, cut by a diagonal line, I do not understand much because. I realize that here is the problem:

```
vec2 uv=(COLOR.xy*2.0-SCREEN_UV.xy)/min(SCREEN_UV.x,SCREEN_UV.y);

```

> **Up 1:**

I managed to improve with this:

```
vec2 uv= UV;

```

now it's like this:

but what he wanted was to be able to pass three uniforms, ***direction***, ***velocity*** and ***intensity***, and to be able to control the direction (right equer), the speed with which they fall, the intensity (higher or lower particles, more or less drops). But I still do not understand how well it is done to do that. Even more that what I will do is rain, I have to understand what is done with the colors to get the idea of rain and not snow.

> **Up 2:**

I was stirring here and the ***velocity***, ***intensity*** and ***direction*** I was able to configure passing a uniform. But I can not change the color of the drops, it always comes out black and white. How would you put a blue color for example?

I try to change the color to red for example using the **mix()** function:

```
vec3 col2 = vec3(1.0, 0.0, 0.0);
vec3 resultColor= mix(vec3(c), col2, 0.7);
COLOR = vec4(vec3(resultColor),0.3);

```

and I get this:

I wanted to change only the color of the drops?

**R=** I got it like this:

```
 COLOR = vec4(vec3(0.3, 0.3, c),0.5);

```

but I'm not very fond of the result, it's very bright, and my breasts are too big, I'll fix it.

# Answer
Changing the colour of the snowflakes isn't very hard, here's what you need to do:

```
void fragment(){
  vec2 uv=(COLOR.xy*2.0-SCREEN_UV.xy)/min(SCREEN_UV.x,SCREEN_UV.y);
  float c=smoothstep(1.0,0.3,clamp(uv.y*0.3+0.8,0.0,0.75));

  //Put the snow into a separate vec3 so we can colour it separately
  vec3 s = vec3(0.);
  s+=snow(uv, 30.0, TIME)*0.3;
  s+=snow(uv, 20.0, TIME)*0.5;
  s+=snow(uv, 15.0, TIME)*0.8;
  s+=snow(uv, 10.0, TIME);
  s+=snow(uv, 8.0, TIME);
  s+=snow(uv, 6.0, TIME);
  s+=snow(uv, 5.0, TIME);
  s+=snow(uv, 2.0, TIME);

  //Change this value here to whatever colour you want the snow to be
  s *= vec3(1.0,0.1,0.4);

  //Add the snow back with the background (stored in c) after it's coloured
  COLOR = vec4(vec3(c) + s,0.5);
}

```

In this code we separate the snow into a separate variable (which uses a negligible amount of memory) so that we can tint it any colour we like after all the snow is added with it affecting the rest of the scene by multiplying (which is really fast on a GPU) it by a colour.
> 2 votes

# Answer
I see multiple problems with your code.

1. The line `vec2 uv=(COLOR.xy*2.0-SCREEN_UV.xy)/min(SCREEN_UV.x,SCREEN_UV.y)` doesn't match the original code you've linked at all. Try `vec2 uv=(FRAGCOORD.xy*2.0-resolution.xy)/min(resolution.x,resolution.y)` instead, and pass `resolution` as a `uniform vec2`.
2. Both the original code and your Godot port of it have an uninitialized variable `p`. You could initialize `p` to `vec2(0.0)`, but the better solution in this case would be to just remove it from the right-hand side of the equations that set `p`. Even the original shader code doesn't work on my Mac in Safari because of this bug, although it works in Chrome on the same computer (that's the nature of uninitialized variables). With `p` properly initialized before use or removed from the right hand side of the equations that set it, the code works fine in Safari too.
3. Your decomposed equations for `p` don't seem to match the original code. A direct port would be: `p=.5+.35*sin(11.0*fract(sin((s+p+scale)*mat2(vec2(7.0,3.0),vec2(6.0,5.0)))*5.0))-f`
4. You define `direction` and `intensity`, but I don't see any references to them later in your code.
5. You have the sign of the equation for `uv.y` flipped.
6. You've removed the original author's name. Although you do provide a link to the original work, considering people may copy the code directly from here, one should always make sure the code gives proper credit to the original author.

After all these corrections, I get proper snow effect in Godot 3.0 that matches the original at glslsandbox.com. Here's a final working code:

```
shader_type canvas_item;

//--- hatsuyuki ---
// by Catzpaw 2016
//
// Modified for Godot; original code can be found at http://www.glslsandbox.com/e#36547.0

//#extension GL_OES_standard_derivatives : enable

uniform vec2 resolution;

float snow(vec2 uv, float scale, float time)
{
    float w=smoothstep(1.0,0.0,-uv.y*(scale/10.0));if(w<.1)return 0.0;
    uv+=time/scale;uv.y+=time*2.0/scale;uv.x+=sin(uv.y+time*.5)/scale;
    uv*=scale;vec2 s=floor(uv),f=fract(uv),p;float k=3.0,d;
    p=.5+.35*sin(11.0*fract(sin((s+scale)*mat2(vec2(7,3),vec2(6,5)))*5.0))-f;d=length(p);k=min(d,k);
    k=smoothstep(0.0,k,sin(f.x+f.y)*0.01);
    return k*w;
}

void fragment( )
{
    vec2 uv=(FRAGCOORD.xy*2.0-resolution.xy)/min(resolution.x,resolution.y);
    vec3 finalColor=vec3(0);
    float c=smoothstep(1.0,0.3,clamp(uv.y*.3+.8,0.0,.75));
    c+=snow(uv,30.0,TIME)*.3;
    c+=snow(uv,20.0,TIME)*.5;
    c+=snow(uv,15.0,TIME)*.8;
    c+=snow(uv,10.0,TIME);
    c+=snow(uv,8.0,TIME);
    c+=snow(uv,6.0,TIME);
    c+=snow(uv,5.0,TIME);
    finalColor=(vec3(c));
    COLOR = vec4(finalColor,1.0);
}

```

The code above will create a parameter named `resolution` under the Shader Material settings in Godot. Be sure to set it to a reasonable value; otherwise the code won't work.

P.S. I've left the original author's formatting as is. As unreadable as their coding style is, this should allow the code to be compared to the original easily.
> 0 votes

---
Tags: shaders, glsl, fragment-shader, godot
---


title: How to optimize this code (C#)

text:
# Question
Title: How to optimize this code (C#)
Could someone help me optimize my code below . I'm not satisfied with this though it gets what i want and execute what i want.

```
[SerializeField]
GameObject CameraScriptsAir_1,CameraScripstAir_2;

[SerializeField]
GameObject[] CameraScriptsTV;

[SerializeField]
GameObject[] TwoScript;

[SerializeField]
GameObject[] Tests;

[SerializeField]
GameObject FogEffect;

void Update()
{
    if (tzPlayInfo.Instance.BLOCK_GAME_FLOW == false)
    {
        CameraScriptsAir_1 = this.transform.GetChild(0).GetChild(1).GetChild(0).GetChild(2).GetChild(0).gameObject;

        CameraScripstAir_2 = this.transform.GetChild(0).GetChild(1).GetChild(1).GetChild(2).gameObject;

        CameraScriptsTV[0] = this.transform.GetChild(0).GetChild(1).GetChild(5).GetChild(0).GetChild(0).gameObject;
        CameraScriptsTV[1] = this.transform.GetChild(0).GetChild(1).GetChild(6).GetChild(0).GetChild(0).gameObject;
        CameraScriptsTV[2] = this.transform.GetChild(0).GetChild(1).GetChild(7).GetChild(0).GetChild(0).gameObject;

        TwoScript[0] = this.transform.GetChild(0).GetChild(1).GetChild(8).GetChild(0).GetChild(1).gameObject;
        TwoScript[1] = this.transform.GetChild(0).GetChild(1).GetChild(38).GetChild(0).GetChild(0).gameObject;

        //29
        Tests[0] = this.transform.GetChild(0).GetChild(1).GetChild(9).GetChild(0).GetChild(0).gameObject;
        Tests[1] = this.transform.GetChild(0).GetChild(1).GetChild(10).GetChild(0).GetChild(0).gameObject;
        Tests[2] = this.transform.GetChild(0).GetChild(1).GetChild(11).GetChild(0).GetChild(0).gameObject;
        Tests[3] = this.transform.GetChild(0).GetChild(1).GetChild(12).GetChild(0).GetChild(0).gameObject;
        Tests[4] = this.transform.GetChild(0).GetChild(1).GetChild(13).GetChild(0).GetChild(0).gameObject;
        Tests[5] = this.transform.GetChild(0).GetChild(1).GetChild(14).GetChild(0).GetChild(0).gameObject;
        Tests[6] = this.transform.GetChild(0).GetChild(1).GetChild(15).GetChild(0).GetChild(0).gameObject;
        Tests[7] = this.transform.GetChild(0).GetChild(1).GetChild(16).GetChild(0).GetChild(0).gameObject;
        Tests[8] = this.transform.GetChild(0).GetChild(1).GetChild(17).GetChild(0).GetChild(0).gameObject;
        Tests[9] = this.transform.GetChild(0).GetChild(1).GetChild(18).GetChild(0).GetChild(0).gameObject;
        Tests[10] = this.transform.GetChild(0).GetChild(1).GetChild(19).GetChild(0).GetChild(0).gameObject;
        Tests[11] = this.transform.GetChild(0).GetChild(1).GetChild(20).GetChild(0).GetChild(0).gameObject;
        Tests[12] = this.transform.GetChild(0).GetChild(1).GetChild(21).GetChild(0).GetChild(0).gameObject;
        Tests[13] = this.transform.GetChild(0).GetChild(1).GetChild(22).GetChild(0).GetChild(0).gameObject;
        Tests[14] = this.transform.GetChild(0).GetChild(1).GetChild(23).GetChild(0).GetChild(0).gameObject;
        Tests[15] = this.transform.GetChild(0).GetChild(1).GetChild(24).GetChild(0).GetChild(0).gameObject;
        Tests[16] = this.transform.GetChild(0).GetChild(1).GetChild(25).GetChild(0).GetChild(0).gameObject;
        Tests[17] = this.transform.GetChild(0).GetChild(1).GetChild(26).GetChild(0).GetChild(0).gameObject;
        Tests[18] = this.transform.GetChild(0).GetChild(1).GetChild(27).GetChild(0).GetChild(0).gameObject;
        Tests[19] = this.transform.GetChild(0).GetChild(1).GetChild(28).GetChild(0).GetChild(0).gameObject;
        Tests[20] = this.transform.GetChild(0).GetChild(1).GetChild(29).GetChild(0).GetChild(0).gameObject;
        Tests[21] = this.transform.GetChild(0).GetChild(1).GetChild(30).GetChild(0).GetChild(0).gameObject;
        Tests[22] = this.transform.GetChild(0).GetChild(1).GetChild(31).GetChild(0).GetChild(0).gameObject;
        Tests[23] = this.transform.GetChild(0).GetChild(1).GetChild(32).GetChild(0).GetChild(0).gameObject;
        Tests[24] = this.transform.GetChild(0).GetChild(1).GetChild(33).GetChild(0).GetChild(0).gameObject;
        Tests[25] = this.transform.GetChild(0).GetChild(1).GetChild(34).GetChild(0).GetChild(0).gameObject;
        Tests[26] = this.transform.GetChild(0).GetChild(1).GetChild(35).GetChild(0).GetChild(0).gameObject;
        Tests[27] = this.transform.GetChild(0).GetChild(1).GetChild(36).GetChild(0).GetChild(0).gameObject;
        Tests[28] = this.transform.GetChild(0).GetChild(1).GetChild(37).GetChild(0).GetChild(0).gameObject;

        //fog
        FogEffect = this.gameObject.transform.GetChild(0).GetChild(2).GetChild(0).GetChild(2).gameObject;
    }
}

```

# Answer
You could (and should) use a for loop, for example this:

```
    Tests[0] = this.transform.GetChild(0).GetChild(1).GetChild(9).GetChild(0).GetChild(0).gameObject;
    Tests[1] = this.transform.GetChild(0).GetChild(1).GetChild(10).GetChild(0).GetChild(0).gameObject;
    Tests[2] = this.transform.GetChild(0).GetChild(1).GetChild(11).GetChild(0).GetChild(0).gameObject;
    Tests[3] = this.transform.GetChild(0).GetChild(1).GetChild(12).GetChild(0).GetChild(0).gameObject;
    Tests[4] = this.transform.GetChild(0).GetChild(1).GetChild(13).GetChild(0).GetChild(0).gameObject;
    Tests[5] = this.transform.GetChild(0).GetChild(1).GetChild(14).GetChild(0).GetChild(0).gameObject;
    Tests[6] = this.transform.GetChild(0).GetChild(1).GetChild(15).GetChild(0).GetChild(0).gameObject;
    Tests[7] = this.transform.GetChild(0).GetChild(1).GetChild(16).GetChild(0).GetChild(0).gameObject;
    Tests[8] = this.transform.GetChild(0).GetChild(1).GetChild(17).GetChild(0).GetChild(0).gameObject;
    Tests[9] = this.transform.GetChild(0).GetChild(1).GetChild(18).GetChild(0).GetChild(0).gameObject;
    Tests[10] = this.transform.GetChild(0).GetChild(1).GetChild(19).GetChild(0).GetChild(0).gameObject;
    Tests[11] = this.transform.GetChild(0).GetChild(1).GetChild(20).GetChild(0).GetChild(0).gameObject;
    Tests[12] = this.transform.GetChild(0).GetChild(1).GetChild(21).GetChild(0).GetChild(0).gameObject;
    Tests[13] = this.transform.GetChild(0).GetChild(1).GetChild(22).GetChild(0).GetChild(0).gameObject;
    Tests[14] = this.transform.GetChild(0).GetChild(1).GetChild(23).GetChild(0).GetChild(0).gameObject;
    Tests[15] = this.transform.GetChild(0).GetChild(1).GetChild(24).GetChild(0).GetChild(0).gameObject;
    Tests[16] = this.transform.GetChild(0).GetChild(1).GetChild(25).GetChild(0).GetChild(0).gameObject;
    Tests[17] = this.transform.GetChild(0).GetChild(1).GetChild(26).GetChild(0).GetChild(0).gameObject;
    Tests[18] = this.transform.GetChild(0).GetChild(1).GetChild(27).GetChild(0).GetChild(0).gameObject;
    Tests[19] = this.transform.GetChild(0).GetChild(1).GetChild(28).GetChild(0).GetChild(0).gameObject;
    Tests[20] = this.transform.GetChild(0).GetChild(1).GetChild(29).GetChild(0).GetChild(0).gameObject;
    Tests[21] = this.transform.GetChild(0).GetChild(1).GetChild(30).GetChild(0).GetChild(0).gameObject;
    Tests[22] = this.transform.GetChild(0).GetChild(1).GetChild(31).GetChild(0).GetChild(0).gameObject;
    Tests[23] = this.transform.GetChild(0).GetChild(1).GetChild(32).GetChild(0).GetChild(0).gameObject;
    Tests[24] = this.transform.GetChild(0).GetChild(1).GetChild(33).GetChild(0).GetChild(0).gameObject;
    Tests[25] = this.transform.GetChild(0).GetChild(1).GetChild(34).GetChild(0).GetChild(0).gameObject;
    Tests[26] = this.transform.GetChild(0).GetChild(1).GetChild(35).GetChild(0).GetChild(0).gameObject;
    Tests[27] = this.transform.GetChild(0).GetChild(1).GetChild(36).GetChild(0).GetChild(0).gameObject;
    Tests[28] = this.transform.GetChild(0).GetChild(1).GetChild(37).GetChild(0).GetChild(0).gameObject;

```

could be simplified to this:

```
for(int i=0; i<29; i++)
{
    Tests[i]= this. transform.GetChild(0).GetChild(1).GetChild(i+9).GetChild(0).GetChild(0).gameObject; //what are you trying to get here???? this still is not right!
}

```
> 2 votes

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


# Question
Title: Check whether object is looking in between a minimum and maximum angle in 3d Space
**What I want to accomplish is to check whether an object is looking in between a minimum and maximum angle in 3D space**

---

for example if a Helicopter is looking to the right...

it would have to check whether its rotation vector is within a cone like shape

when, the heli's rotation vector is inside, the method returns true, but false otherwise. So in the scenario above, the method would return false.

The answer is fairly simple in 2D as all I have to do is check whether `minAngle < heli rot angle < maxAngle` or use dot product to check, but in 3D I have to look at 2 dimensions against the Y axis to start.

---

I could define a cone class and check whether a vector is projected from the origin, but it seemed too excessive as I dont need variables like cone length, start radius, & end radius. I feel like I'm missing something simple that involves a bit of playing around from xz to xz-\>y. Is it possible to accomplish something similar just by checking heli's rot orientation?

# Answer
You'll need to get the current direction vector of the object (you can get this with `transform.forward` in Unity), vectors that point in the directions you care for and the angle between the cone's side and center.

You then simply need to take the dot product of the forward vector and one of the directions, and if it's larger than the cosine of the angle, then the forward vector is in the cone.
> 1 votes

# Answer
It sounds like the `Physics.SphereCast()` could do the job for you. It cast a sphere in the direction and with the radius that you choose.

Here is a sample script:

```
public class SphereCast : MonoBehaviour {

public float Distance;
public float distanceToObstacle;
public float sphereRadious;
public string Tag;

void Update()
{
    RaycastHit hit;

    Vector3 p1 = transform.position;

    if (Physics.SphereCast(p1, sphereRadious, Vector3.down, out hit, Distance))
    {
        distanceToObstacle = hit.distance;

        if (hit.collider.tag == "Enemy")
        Destroy(hit.collider.gameObject);

        Debug.DrawLine(transform.position, hit.point, Color.red, 10);
    }
}}

```

Here is a GIF with what it looks like:
> 0 votes

---
Tags: unity, 3d, mathematics, angles
---


# Question
Title: Is copying UI and layout of other apps legal?
I would like to develop an Android App for Google Play and I am going to use Facebook and Whatsapp UI as background of the game (as a back-story). I will use icons without copyright to emulate/duplicate the style of Facebook and Whatsapp (they are not part of original drawable of the external app). I will inform the user about the objective of the game. I won't include any direct references to the emulated apps such as the title "Facebook" or "Messenger". The user is free to interpret what he is seeing. I will add the text

> "any name and reference is fictitious".

However I have some great doubts:

1. After the development, will I be able to upload the app on an app store such as Google Play?
2. Is copying UI and layout of other external apps legal?
3. Does it break any law or rule?

# Answer
Presently, here's what the Google Play Developer Policy Center states about impersonation:

> We don’t allow apps that use another app or entity’s brand, title, logo, or name in a manner that may result in misleading users. Don’t try to imply an endorsement or relationship with another entity where none exists. Impersonation can occur even if there isn’t an intent to deceive, so please be careful when referencing any brands that do not belong to you. This applies even if that brand doesn’t yet have a presence on Google Play.

Thus, it depends on:

* if they initially believe that you are misleading users
* if the other entities (Facebook, etc) file a complaint
    + if Google sides with them
    + results on any legal proceedings that follow

As to breaking the law, if you copy someone else's artistic design, knowingly or otherwise, you may be at risk for copyright or patent infringement. If you need legal advice, consult with a legal expert. Generally speaking, bigger companies have more brand identity to risk & more resources to litigate.

I can't recall specific titles at the moment, but I have played games which feature simulated social network or chat clients. To the best of my knowledge all of them made some effort to display themselves as a parody.
> 2 votes

---
Tags: android, copyright, ui-design
---


# Question
Title: How can i load a level in my gameengine wich is larger than 2GB? C#
i were asking myself how could i load a large Level? My gameengine is written in C# and is rendering with Direct3D11. I just have my class called "Scenery" and the class is able to store all objects in a level (sceneryObject) with their components and features. My engine loads the serialized scenery, but i know that the maximal size of a .net object is 2gb. So how could my Scenery class load bigger levels? The .Scenery class contains a List with all the objects, and the Assets are included within the sceneryClass. Do you thinkthe Scenery class should not include the Assets, and they should be stored extern?

Maybe somebody have a suggestion :)

Best Regards and thanks in advance!

# Answer
> 2 votes
Break the level into smaller chunks and load *those* instead.

This will give you a number of extra benefits, decreasing overall memory usage and enabling you to stream levels in and out to decrease perceived load times.

A basic approach to subdividing a level is to do it based on a fixed-size grid, where each chunk is a grid cell. To start with, you could *just* do the chunking piece: break everything up into chunks however you need to (including splitting your source map assets, if necessary) and load them all, assuming you have the memory. Once that works, worry about figuring out how to load only the parts that are immediately needed and stream the rest in and out.

---
Tags: assets, loading, levels
---


# Question
Title: What is the meaning of this line algorithm?
I have been looking at codes of several open source 2d games and I have found this function.

```
GetLineCollisionHit(Vector2 Position1, int Width1, int Height1, Vector2 Position2, int Width2, int Height2)
    {
      int tile1X= Position1.X + Width1 / 16.0);
      int tile1Y= Position1.Y + Height1 / 16.0);
      int tile2X= Position2.X + Width2 / 16.0);
      int tile2Y= Position2.Y + Height2 / 16.0);
        do
        {
          int dx= Math.Abs(tile1X- tile2X);
          int dy= Math.Abs(tile1Y- tile2Y);
          if (tile1X== tile2X && tile2Y== tile1Y)
            return true;
          if (dx> dy)
          {
            if (tile1X< tile2X)
              ++tile1X;
            else
              --tile1X;
            (check collision)
          }
          else
          {
            if (tile1Y< tile2Y)
              ++tile1Y;
            else
              --tile1Y;
            (return true if collision)
          }
        }
        while (true);
        return false;
    }

```

What is really checking is if there is any collision of solid tiles between two points, for this look for the line between the two tiles. But I do not know if it is a coding problem since it is not implementing neither **Bresenham's line algorithm** nor **DDA** or similar. So what are you trying to find in this line **dx\>dy**? What sense does it have to advance x while x \> y since that way a line is not correctly created.

# Answer
> 1 votes
This looks to me like a version of DDA. The naming of variables is absolutely atrocious, making it really hard to understand.

The check for whether absolute value of `dx` or `dy` is greater is so that it can march 1 pixel at a time along the line. If `dx` is greater, the slope is between -1 and 1, so the "run" is greater than the "rise". Every time we increment our horizontal position, the vertical position will change by less than or equal to 1. So we're guaranteed to hit every pixel on the line. But if `dy` is greater, then the slope is between 1 and infinity (or -1 and -infinity). So you want to increment the vertical component by one and the horizontal component will always vary by less than or equal to 1, but greater than -1, meaning you'll still hit every pixel on the line.

---
Tags: collision-detection, mathematics
---


title: My trigger does not detect my player

text:
# Question
Title: My trigger does not detect my player
My trigger does not detect my player.
My **Trigger.cs** file:

```
using UnityEngine;

public class Trigger : MonoBehaviour {

public Camera camera1;
public Camera camera2;
public GameObject panel;

 void OnTriggerEnter(Collider other)
{
    camera1.enabled = false;
    camera2.enabled = true;
    panel.SetActive(true);
    Debug.Log ("Entered-");
}

 void OnTriggerExit(Collider other)
{
    camera2.enabled = false;
    camera1.enabled = true;
    panel.SetActive(false);

}
private void Update()
{
    if(Input.GetKeyDown(KeyCode.DownArrow) || Input.GetKeyDown(KeyCode.S))
    {
        panel.SetActive(false);

    }
            }

}

```

Where I can start troubleshooting te issue?
Object on which the trigger script is sitting on.
**The solution:**
-- I created two colliders, and assigned one as a collider, the other (bigger) is a trigger.
-- I also had problems with the small triggers in the scene. The triggers were to small to be detected by my main player, althought they detected my "sphere" player object

# Answer
You have to set `IsTrigger` to `true` on the `BoxCollider`. If this isn't set, it indicated that the box collider is only used for physics.

If you are trying to fire code when two objects collide, you need to use `OnCollisionEnter`, `OnCollisionExit`, `OnCollisionStay`

See the following documentation for more information:

Collider

IsTrigger
> 5 votes

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


# Question
Title: Looking for a tournament system for the group of semi-anonymous players some of which may ignore specific matches. How can I do that?
I need to implement a tournament system for a one-time tournaments between a finite sets of anonymous players.

Single-elimination or a Groups-system tournament (for a bigger number of players) would have been enough, but there is a twist.

When the match is assigned, the participants are free to organize it in a place or time they agree on.

If the game was assigned to be played by two participants and it didn't happen in a predefined amount of time (say, a week), than we need to expire it and move on to the next round so as to not to delay the tournament overall.

But with our implementation of getting the match results (external API), we can't tell if one of the supposed players of this game ignored the challenge while another was looking for him to play the match. And if one did, which one of the two did it. So just writing the game off as a draw seems extremely unfair for the player who was looking to play the game, since in a non-anonymous tournament with the set dates of matches and attendance control, he would have been judged a winner due to opponent's absence.

So we are looking into round-robin systems giving points for matches (3 for win, 1 for draws, and so on), considering the possibility of giving a variable amount of points for the "expired" matches depending on their quantity.

Like, if you only missed one match, while your opponent for that match have missed three others, than chances are high that it was you who showed up, so you get 2 points while he gets 0. But even that approach seems questionable and open for abuse.

I am looking for the algorithm that will allow me to implement the tournament system like that without sacrificing too much fairness. Maybe it is a known solved problem so I won't need to invent a mathematical bicycle here?

# Answer
> 1 votes
## Announce a predetermined time of the meeting if they fail to determine it themselves

I appreciate the effort made by @realUser404, but "making the decision as a human being and not a computer" is generally a bad idea for your tournament's routine. You need to reduce human factor to a value as low as possible.

A good idea for your scenario is to have a set time at which the participants have to meet if they didn't make an agreement. Let's imagine that one round takes one week to complete. You announce the pairings on Monday, and tell that if they do not agree about the time, thay have to start their play at 18:00 GMT+N Saturday (always designate the time zone, but choose it wisely).

You need to somehow reliably and (ideally) automatically register:

* If the play happened during the week, so no player can lose and then claim that they didn't meet at all yet.
    + In this case you have a clear winner and loser according to your rules, or a clear draw.
* If any of the players comes at the pre-set time (18:00 GMT+N Saturday).
    + If both players come and have a valid play, the same applies. Ideally, the play should start automatically once both players hit the button called along the lines of "I am here and ready".
    + If none of the players come on time, it is not a draw (1 point for each of them), it is a loss (0 points). They have just ignored the match and delayed the tournament.
    + If only one player comes, he has a technical win, registered as a normal win for all means and purposes (3 points), and the other player loses (0 points).
* Sometimes the power difference is so big that there is no need to play the round at all. None of the players wants to show up, but the stronger one needs their 3 points and the weaker one will often get an additional punishment if not showing up at all. So if one of the players announces giving up during the week, take this as a result.

# Answer
> 0 votes
As you say, it is difficult to find a fair algorithm. It is because in my humble opinion the principle of having an algorithm for this is opening the door for abuses.

For example with the solution you came with, in a group of 4 people with one insanely strong guy inside, if the other 3 make a draw on purpose with him, he will end up disqualified. That goes for any algorithm you will come up with.

I believe the solution to this is to **act yourself as a referee** in the case of people not playing their match.

1. Inform players that they need to send you a mail if they cannot find an agreement with the other player.
2. Inform them that if they do not send you a mail and then do not play, they will be out of the tournament.
3. If both sent you an email saying they cannot find an agreement with the other player, **you** then need to decide who won or if it is a draw.

It is really important that you make the decision as a human being and not a computer, as it is the only way people cannot hack the system to get free wins or free draws.

---
Tags: tournament
---


# Question
Title: How do I set up an SFML .NET dll reference in Visual Studio Code
How do I set up SFML .NET library dll files as references in Visual studio code using dotnet core SDK? I want to ditch visual studio as it's large and clunky and am wondering how to add "third party" .dll's as references like I can in visual studio by right clicking the references tab in the project explorer and selecting the dll.

# Answer
I added these references manually to .csproj file as item group. e.g. https://github.com/kubagdynia/Spacetris/blob/master/Spacetris/Spacetris.csproj
> 1 votes

---
Tags: c#, sfml, .net, dll, visual-studio-code
---


# Question
Title: How can I make the droid object to act like a mouse cursor?
I'm using the droid (Called it NAVI) to be like helper in the game. By default the droid is position a bit far from the player and act like a mouse cursor. When I move the player around the droid is moving with him. When the droid is getting over interactable objects he start rotating.

Then when the droid is on interactable object I can click and get information about the object. When i move to none interactable objects the droid stop rotating. When i press on F key the droid is rotating smooth getting closer to the player and back like a mouse cursor.

The problem is when I'm trying to move in or out doors for example since the droid position is a bit far from the player the droid is stuck in the door. The droid is outside the door but the player is not so the door keep closing and open over again.

What I'm trying to do is some how to make the droid to act like a mouse cursor but I'm not sure how to use it with doors for example.

I recorded a small short video clip showing the problem. First problem is when the droid small far from the player like a cursor it's not detecting the door and the door will not open.

Only if I press F and the droid is now bigger and close to me when I'm moving to the door the door will open.

Second problem is when the door is open and I'm moving forward the droid is outside but the player is not yet outside so the door get confusing and start closing.

Video clip

This is a screenshot of the player and it's inspector on the right. And the script Detect Interactable attached to it:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class DetectInteractable : MonoBehaviour
{
    public Camera cam;
    public float distanceToSee;
    public string objectHit;
    public bool interactableObject = false;
    public Transform parentToSearch;
    public static bool detected = false;

    private RaycastHit whatObjectHit;
    private bool clickForDescription = false;
    private int layerMask = 1 << 8;

    private void Start()
    {

    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            clickForDescription = true;
        }

        Debug.DrawRay(cam.transform.position, cam.transform.forward * distanceToSee, Color.magenta);
        if (Physics.Raycast(cam.transform.position, cam.transform.forward, out whatObjectHit, distanceToSee, layerMask))
        {
            detected = true;
            objectHit = whatObjectHit.collider.gameObject.name;
            interactableObject = true;
            print("Hit ! " + whatObjectHit.collider.gameObject.name);
        }
        else
        {
            detected = false;
            clickForDescription = false;
            print("Not Hit !");
        }
    }

    private void OnGUI()
    {
        if (clickForDescription == true)
        {
            ProcessOnGUI(parentToSearch);
        }
    }

    void ProcessOnGUI(Transform parent, int level = 0)
    {
        foreach (Transform child in parent)
        {
            if (child.GetComponent<ItemInformation>() != null)
            {
                ItemInformation iteminformation = child.GetComponent<ItemInformation>();
                if (child.name == objectHit)
                {
                    var centeredStyle = GUI.skin.GetStyle("Label");
                    centeredStyle.alignment = TextAnchor.UpperCenter;
                    GUI.Box(new Rect(
                          Screen.width / 2 - 50 + 20 * level, // <== INDENTATION
                          Screen.height / 2 - 25, 100, 50),
                        iteminformation.description, centeredStyle);
                }
            }

            // Process next deeper level
            ProcessOnGUI(child, level + 1);
        }
    }

    public class ViewableObject : MonoBehaviour
    {
        public string displayText;
        public bool isInteractable;
    }
}

```

Screenshot of the Main Camera and it's inspector:

Screenshot of the NAVI (The droid) and it's inspector:

And last screenshot of the Objects Manipulation gameobject and it's inspector:

And the Objects Manipulation script:

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

public class ObjectsManipulation : MonoBehaviour
{
    //Scaling
    private Scaling scaling;

    //Lights
    public DimLights dimlights;
    private Coroutine lightCoroutine;

    //Colors
    private Colors colors;

    //Rotating
    private Rotating rotating;

    private void Start()
    {
        scaling = GetComponent<Scaling>();
        scaling.Inits();

        colors = GetComponent<Colors>();
        colors.Start();

        rotating = GetComponent<Rotating>();
    }

    // Use this for initialization
    void Update()
    {
        //Scaling
        if (Input.GetKeyDown(KeyCode.F))
        {
            //Flip the scale direction when F key is pressed
            scaling.scaleUp = !scaling.scaleUp;

            //Stop old coroutine
            if (scaling.scaleCoroutine != null)
                StopCoroutine(scaling.scaleCoroutine);

            if (lightCoroutine != null)
                StopCoroutine(lightCoroutine);

            //Scale  up
            if (scaling.scaleUp)
            {
                //Start new coroutine and scale up within 5 seconds and return the coroutine reference
                rotating.rotateBack = false;
                scaling.scaleCoroutine = StartCoroutine(scaling.scaleOverTime(scaling.objectToScale, scaling.maxSize, scaling.duration));
                lightCoroutine = StartCoroutine(dimlights.dimLightOverTime(1, scaling.duration));
            }

            //Scale Down
            else
            {
                //Start new coroutine and scale up within 5 seconds and return the coroutine reference
                rotating.rotateBack = true;
                scaling.scaleCoroutine = StartCoroutine(scaling.scaleOverTime(scaling.objectToScale, scaling.minSize, scaling.duration));
                lightCoroutine = StartCoroutine(dimlights.dimLightOverTime(0, scaling.duration)); ;
            }
        }
        //Rotate
        if (Input.GetKey(KeyCode.R) && !scaling.scaleUp)
        {
            rotating.x += Time.deltaTime * rotating.rotationSpeed;
            scaling.objectToScale.transform.localRotation = Quaternion.Euler(0, 0, rotating.x);
            rotating.keyPressed = true;
        }
        if (Input.GetKeyUp(KeyCode.R))
        {
            rotating.keyPressed = false;
        }

        if (!rotating.keyPressed && !scaling.scaleUp && rotating.rotateBack == false
            && DetectInteractable.detected == false)
        {
            scaling.objectToScale.transform.rotation = Quaternion.LookRotation(Camera.main.transform.forward);
        }

        if (DetectInteractable.detected == true && !scaling.scaleUp)
        {
            rotating.x += Time.deltaTime * rotating.rotationSpeed;
            scaling.objectToScale.transform.localRotation = Quaternion.Euler(0, 0, rotating.x);
        }
    }
}

```

The rotating script:

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

public class Rotating : MonoBehaviour
{
    public float rotationSpeed;
    public float rotationDuration;
    public float x;
    public bool keyPressed = false;
    public bool rotateBack = false;
}

```

The scaling script:

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

public class Scaling : MonoBehaviour
{
    public GameObject objectToScale;
    public GameObject lookAtTarget;
    public float duration = 1f;
    public Vector3 minSize;
    public Vector3 maxSize;
    public bool scaleUp = false;
    public Coroutine scaleCoroutine;

    public void Inits()
    {
     objectToScale.transform.localScale = minSize;
    }

    public IEnumerator scaleOverTime(GameObject targetObj, Vector3 toScale, float duration)
    {
        float counter = 0;
        Vector3 startScaleSize = targetObj.transform.localScale;

        while (counter < duration)
        {
            counter += Time.deltaTime;
            targetObj.transform.localScale = Vector3.Lerp(startScaleSize, toScale, counter / duration);
            if (scaleUp)
            {
                var lookPos = lookAtTarget.transform.position - objectToScale.transform.position;
                lookPos.y = 0;
                var rotation = Quaternion.LookRotation(lookPos);
                objectToScale.transform.rotation = Quaternion.Slerp(objectToScale.transform.rotation, rotation, counter / duration);
            }
            else
            {
                var lookPos = lookAtTarget.transform.position - objectToScale.transform.position;
                lookPos.y = 0;
                var rotation = Quaternion.LookRotation(Camera.main.transform.forward);
                objectToScale.transform.rotation = Quaternion.Slerp(objectToScale.transform.rotation, rotation, counter / duration);
            }

            yield return null;
        }
    }
}

```

The main problem is when moving for example between doors since the NAVI droid is not like the mouse cursor but it's object that positioned close/far from the player the doors get confuse. I can't pass smooth through the doors.

This is a screenshot of one of the doors and it's inspector:

And the script attached to the door:

```
using UnityEngine;
using System.Collections;

public class DoorVert : MonoBehaviour {

    public float translateValue;
    public float easeTime;
    public OTween.EaseType ease;
    public float waitTime;
    public Light[] lt;
    public Renderer[] renderers;
    public bool doorLocked = false;
    public bool locked = false;

    private Vector3 StartlocalPos;
    private Vector3 endlocalPos;

    private void Start(){
        StartlocalPos = transform.localPosition;
        gameObject.isStatic = false;

        if (doorLocked == true)
        {
            for (int i = 0; i < lt.Length; i++)
            {
                lt[i].color = Color.red;
                renderers[i].material.color = Color.red;
            }
        }
    }

    public void OpenDoor(){
        if (doorLocked == false)
        {
            OTween.ValueTo(gameObject, ease, 0.0f, -translateValue, easeTime, 0.0f, "StartOpen", "UpdateOpenDoor", "EndOpen");
            GetComponent<AudioSource>().Play();
        }
    }

    private void UpdateOpenDoor(float f){
        if (doorLocked == false)
        {
            Vector3 pos = transform.TransformDirection(new Vector3(0, 1, 0));
            transform.localPosition = StartlocalPos + pos * f;
        }

    }

    private void UpdateCloseDoor(float f){
        if (doorLocked == false)
        {
            Vector3 pos = transform.TransformDirection(new Vector3(0, -f, 0));
            transform.localPosition = endlocalPos - pos;
        }

    }

    private void EndOpen(){
        if (doorLocked == false)
        {
            endlocalPos = transform.localPosition;
            StartCoroutine(WaitToClose());
        }
    }

    private IEnumerator WaitToClose(){

        yield return new WaitForSeconds(waitTime);
        OTween.ValueTo( gameObject,ease,0.0f,translateValue,easeTime,0.0f,"StartClose","UpdateCloseDoor","EndClose");
        GetComponent<AudioSource>().Play();
    }

    private void Update()
    {
        if (locked == true)
        {
            doorLocked = true;
            for (int i = 0; i < lt.Length; i++)
            {
                lt[i].color = Color.red;
                renderers[i].material.color = Color.red;
            }
        }
        else
        {
            doorLocked = false;
            for (int i = 0; i < lt.Length; i++)
            {
                lt[i].color = Color.green;
                renderers[i].material.color = Color.green;
            }
        }
    }
}

```

This script is calling OpenDoor():

```
using UnityEngine;
using System.Collections;

public class VertDoorManager : MonoBehaviour {

    public DoorVert door1;

    void OnTriggerEnter(){
        if (door1!=null){
            door1.OpenDoor();
        }

    }
}

```

# Answer
This does not directly answer the mouse cursor question, but may provide an alternative.

You could check both the player and NAVI for the trigger to open the door, then she could open if it closed behind the player.

Or, in the case some doors may lock:

Each time the player exits the door's collider teleport NAVI to a location next to the player.
> 2 votes

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


title: Deferred Shading 2D Texture Issue

text:
# Question
Title: Deferred Shading 2D Texture Issue
I've been following the Rastertek tutorial on deferred shading (http://www.rastertek.com/dx11tut50.html). I have implemented it in my own architectural way but have ended up with the same issue as the tutorial; if you get the source and take a look, it appears to be working fine - but if you move the camera around you can see that only the front 2 faces are being rendered, and its like as if the cube is only being rendered to some kind of invisible pane - viewing from behind it is completely invisible. In my image you can see that the model is being completely cut off. Is my 2D render texture possibly floating out in that space?

To provide the amount of code I have would be very dodgy. If you can help me out conceptually or take a look at the downloadable source code I would very much appreciate it.

Please see my attached image.

This image is from about 45 degrees to the side - it appears to be getting cut off along the red lines I've drawn (ignore the missing topside - thats just the light only going down the z plane):

# Answer
> 1 votes
Turns out I needed to set the camera back 1 unit so the view matrix wouldn't trim my screen down when I changed the camera yaw.

---
Tags: rendering, directx11
---


title: Mute sound in editor in Unity

text:
# Question
Title: Mute sound in editor in Unity
Is it possible to mute sound in editor in Unity? I mean not in the game, but in the editor, so that when I am debugging there would be no sound whatsoever.

# Answer
In the `Scene` view, you will find a little toggle, near the `2D` toggle, at the right of the lightning toggle (with a little sun icon).

Try to uncheck it to mute the sound in the scene.

---

Otherwise, in the Game window, you have a toggle called "Mute Audio", between "Maximize on play" and "Stats" toggles, just check it!

If you want this toggle to be turned on each time you start Unity, create a script called `EditorAudioManager` and put the following script in it.

```
using UnityEditor;

[InitializeOnLoad]
public class EditorAudioManager
{
    static EditorAudioManager()
    {
        EditorUtility.audioMasterMute = EditorPrefs.GetBool( "AudioMasterMute" );
    }

    [MenuItem( "Edit/Save editor audio preferences" )]
    static void SaveEditorAudioPreferences()
    {
        EditorPrefs.SetBool( "AudioMasterMute", EditorUtility.audioMasterMute );
    }
}

```

Then, make sure the "Mute Audio" toggle is on, and click on "Edit/Save editor audio preferences" so as to save the toggle state.

---

Other possibility :

Mute the sound of the Unity Editor from your computer using the volume mixer. On Windows 10, right click on the speaker icon in the bottom right corner of your screen and click on "Volume mixer".
> 9 votes

---
Tags: unity, sound, debugging, editors, ide
---


# Question
Title: How can I make a custom memory allocation for classes with virtual methods?
I want to create a custom allocator that stores objects to the heap sequentially. The allocator itself is very simple. It just allocates a big chunk of memory and moves an offset as `Allocate()` calls happen.

The problem comes when allocating memory for custom types, especially classes with virtual functions.

```
SomeClassWithVirtualFunctions * address = array_allocator->Allocate(sizeof(SomeClassWithVirtualFunctions));
SomeClassWithVirtualFunctions->Init(...);

```

It throws a seg fault when the virtual function is called, since as i am given to understand, stuff that are initialized through the constructor (vtable for example) are now ignored.

However, if i do the following,

```
SomeClassWithVirtualFunctions * the_new_object = new SomeClassWithVirtualFunctions();
char * memory = array_allocator->Allocate(sizeof(*the_new_object));
memcpy(memory, the_new_object, sizeof(*the_new_object));
SomeClassWithVirtualFunctions->Init();

```

then the code works fine. I believe though that the above is a dangerous work-around trick.

The intend is to have a base class with virtual functions like `Step()` for example, that game classes like `Player, Grass, Wall` override to have unique behavior.

What is the best way to implement this? Do i use the custom allocator to store only primitive class members stuff, and classes are allocated normally?

Will overriding the `new` operator for `SomeClassWithVirtualFunctions` work?

```
void * operator new(size_t size) {
    char * address = array_allocator->Allocate(size);

    return address;
}

```

# Answer
> 3 votes
Take a look at std::allocator\_traits that will allow you to use your allocator and construct objects in allocated space.

If you don't want to use that you can use placement new: `new(the_new_object) SomeClassWithVirtualFunctions(...)` keep in mind that you will need to use `the_new_object->~SomeClassWithVirtualFunctions()` to deconstruct it before you can return it to the allocator for reuse.

You can also pass other parameters to the new overload

```
void * operator new(size_t size, array_allocator_t array_allocator) {
    char * address = array_allocator->Allocate(size);

    return address;
}

```

call with `new(array_allocator) SomeClassWithVirtualFunctions(...)`

---
Tags: c++, design-patterns, memory-efficiency, memory
---


# Question
Title: Stencil pass in deferred rendering - far plane
For a long time I was occuring issue with lights which use light volume to reduce fragment shaders run (point, spot).

First I use stencil pass to mark pixels which should be processed by fragment shader by drawing a sphere. Then in light pass I render the same sphere again.

Everything works ok until light volume cuts with far plane. Back faces of that volume aren't rendered so stencil buffer contain 0 value.

Because of that final image has big black circle instead of lightened area. I searched how to overcome that issue and I realized that one of the solution to this problem is to enable GL\_DEPTH\_CLAMP which ignores near and far plane. I enabled it for both passes. The problem dissapeared.

My question are:

* Is that correct solution used by people and does it decrease performance?
* Why all tutorials doesn't mention about that issue? I'm curious if I have something wrong in my implementation.

I am aware that there are other methods such as screen-aligned quads or tile based deferred rendering but I want to understand this method as well.

# Answer
Depth clipping can be disabled in other graphics APIs as well, this is a normal feature, so this is one way to solve the problem.

You can draw front faces of light geometries when you are outside of the volume, this should resolve clipping issues because lights will be clipped when geometries are too. When you are inside, and still clip away the backfaces, you must extend the far plane I'm afraid or disable depth clipping.

An other way, is do not draw lights which would intersect the farplane or be completely behind it. Now this would result in light popping out as they get farther away from you. I would make a fog to hide them. If there is an area completely fogged between you and the farplane, that would be a safe area where lights can pop out unnoticed. The fog should occlude any lighting of the scene too to have lights pop out unnoticed.
> 2 votes

---
Tags: opengl, deferred-rendering, stencil
---


# Question
Title: draw a box with transparent background (outline) in unity
I am trying to draw an outline (a transparent box with colored border essentially)

I have the following code adapted from here

```
void OnGUI(){
    GUI.Box (new Rect (10,10,200,30), "Object", InitStyles(new Color( 0f, 0f, 0f, 0.0f )));
}
private GUIStyle InitStyles(Color color){
    GUIStyle currentStyle = null;
    if( currentStyle == null ){
        currentStyle = new GUIStyle (GUI.skin.box );
        currentStyle.normal.background = MakeTex( 2, 2, color );
    }
    return currentStyle;
}

private Texture2D MakeTex( int width, int height, Color col ){
    Color[] pix = new Color[width * height];
    for( int i = 0; i < pix.Length; ++i ){
        pix[ i ] = col;
    }
    Texture2D result = new Texture2D( width, height );
    result.SetPixels( pix );
    result.Apply();
    return result;
}

```

This is getting rid of the border along with the background color.

Is there a better way to do this?

# Answer
> 4 votes
You could use the "9-slicing sprites" technique to cut up a fairly basic sprite texture and use that to draw the borders.

Start by creating a fairly simple sprite - this one is 16x16, but it could easily be smaller, with a white border and transparent centre:

Import this into Unity, and on the import settings set the Texture Type to "Sprite (2D and UI)" and the Mesh Type to "Full Rect", Apply and then open the Sprite Editor:

In the Sprite Editor, drag the green handles inside your border and Apply:

You can then apply this texture to a UI Image as the Source Image, making sure you set the Image Type to "Sliced" and clear the "Fill Center" option:

This results in a nicely scaled, outlined box in game:

By using a white border you can then apply tints via the Color parameter:

---
Tags: unity, gui, color
---


# Question
Title: What is FRotationMatrix in Unreal engine 4?
I am working on FPS shooter example in Unreal engine 4 documentation.

One of the lines for forward movement of pawn is

```
FVector Direction = FRotationMatrix(Controller->GetControlRotation()).GetScaledAxis(EAxis::X);

```

This line gets the forward facing direction of the pawn in world coordinates. I understand that part.

I would like to know what is it mathematically and how does FRotationMatrix get values it gets? How does simple 3 valued vector like rotation get converted to a 4x4 matrix?

Can some one please help me understand.

# Answer
> 5 votes
Rotations are linear transformations, and linear transformations can be represented by matrices. The basic rotations about the X, Y and Z axes are considered well-known (although you can derive them if you want to understand them). "Well-known" in this case means we as game programmers mostly just accept them to be what they are as far as our code is concerned, and write functions that directly produce them for a given angle about a given axes.

To that end, `FRotationMatrix` is a `FMatrix` subclass that exists to facilitate constructing a matrix that represents a pure rotation with no translation or scale (which are also operations that can be encoded into a matrix).

It is constructed using an `FRotator` (in this case, the one from the player controller actor, `Controller`), which stores pitch, roll and yaw values. It uses those, ultimately, to construct a rotation matrix.

You could do the same thing yourself; pitch, roll and yaw just represent rotations around the Y, X and Z axes (in Unreal's coordinate system). You can build the three equivalent basic rotation matrices and then concatenate them to arrive at a result equivalent to what `FRotationMatrix` is computing.

---
Tags: rotation, matrix, transformation, unreal-4, linear-algebra
---


# Question
Title: Incorrect texture being drawn in LWJGL (OPENGL)
I'm learning openGl shaders and textures, and im running into a bit of a problem.

I made a VAO with vertices , tex coords and indices as :

```
    float[] vertices = {  // left is 10f and ratio is 16/9
            -10f,  10f * 9f / 16f, 0f, // TOP LEFT
             10f,  10f * 9f / 16f, 0f, // TOP RIGHT
             10f, -10f * 9f / 16f, 0f, // BOTTOM RIGHT
            -10f, -10f * 9f / 16f, 0f // BOTTOM LEFT
    };

    byte[] indices = {
            0, 1, 2,
            2, 3, 0
    };

    float[] texCoords = {
            0, 0,
            1, 0,
            1, 1,
            0, 1
    };

```

But the texture i want is not being rendered properly.

My shaders are :

Vertex shader:

```
#version 330 core

layout (location = 0) in vec4 position;
layout (location = 1) in vec2 tc;

uniform mat4 pr_matrix;

out DATA {
    vec2 tc;
} vs_out;

void main() {

    gl_Position = pr_matrix * position;
    vs_out.tc = tc;
}

```

Fragment Shader :

```
#version 330 core

layout (location = 0) out vec4 color;

uniform sampler2D tex; // the value is 1 for current active texture

in DATA {
    vec2 tc;
} fs_in;

void main() {

    color = texture(tex , fs_in.tc);

}

```

glUniform call :

```
Shader.BASIC.setUnifrom1i("tex", 1);

public void setUnifrom1i(String name , int val) {
    if(!enabled) enable();
    glUniform1i(getUniform(name) , val);
}

```

Texture creation :

```
public int load(String path) {
    int[] pixels = null;

    try {
        BufferedImage img = ImageIO.read(new FileInputStream(path));
        width = img.getWidth();
        height = img.getHeight();
        pixels = new int[width * height];
        img.getRGB(0, 0, width, height, pixels, 0, width);
    } catch (IOException e) {
        e.printStackTrace();
    }

    int[] data = new int[width * height];
    for (int i = 0; i < width * height; i++) {
        int a = (pixels[i] & 0xff000000) >> 24;
        int r = (pixels[i] & 0xff0000) >> 16;
        int g = (pixels[i] & 0xff00) >> 8;
        int b = (pixels[i] & 0xff);

        data[i] = a << 24 | b << 16 | g << 8 | r;
    }

    int tex = glGenTextures();
    glBindTexture(GL_TEXTURE_2D, tex);

    glTexParameterf(GL_TEXTURE_2D , GL_TEXTURE_MIN_FILTER , GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D , GL_TEXTURE_MAG_FILTER , GL_NEAREST);

    glTexImage2D(GL_TEXTURE_2D , 0 , GL_RGBA , width , height ,  0 , GL_RGBA , GL_UNSIGNED_BYTE , BufferUtils.createIntBuffer(data));

    glBindTexture(GL_TEXTURE_2D, 0);

    return tex;
}

```

EDIT 2 :

Shader class :

```
public class Shader {

private int id;

public static final int VERTEX_ATTRIB = 0 , TCOORD_ATTRIB = 1;

public static Shader BASIC;

private boolean enabled = false;

private Map<String , Integer> locationCache = new HashMap<String , Integer>();

private Shader(String vert , String frag) {
    id = ShaderUtils.load(vert, frag);
}

public static void loadAll() {
    BASIC = new Shader("shaders/shader.vs", "shaders/shader.fs");
}

public void enable() {
    glUseProgram(id);
    enabled = true;
}

public void disable() {
    glUseProgram(0);
    enabled = false;
}

public int getUniform(String name){

    if(locationCache.containsKey(name)){
        return locationCache.get(name);
    }

    int result = glGetUniformLocation(id, name);

    if(result == -1){
        System.err.println("Unable to find uniform : "+ name);
        System.exit(1);
    }

    locationCache.put(name, result);

    return result;
}

public void setUnifrom1i(String name , int val) {
    if(!enabled) enable();
    glUniform1i(getUniform(name) , val);
}

public void setUnifrom1f(String name , float val) {
    if(!enabled) enable();
    glUniform1f(getUniform(name) , val);
}

public void setUnifrom2f(String name , float x , float y) {
    glUniform2f(getUniform(name) , x , y);
}

public void setUnifrom3f(String name , Vector3f vector) {
    if(!enabled) enable();
    glUniform3f(getUniform(name) , vector.x , vector.y , vector.z);
}

public void setUnifromMat4f(String name , Matrix4f val) {
    if(!enabled) enable();
    glUniformMatrix4(getUniform(name) , false , val.toFloatBuffer());
}

}

```

Texture class :

```
public class Texture {

private int width, height;
private int texture;

public Texture(String path) {
    texture = load(path);
}

private int load(String path) {
    int[] pixels = null;
    try {
        BufferedImage image = ImageIO.read(new FileInputStream(path));
        width = image.getWidth();
        height = image.getHeight();
        pixels = new int[width * height];
        image.getRGB(0, 0, width, height, pixels, 0, width);
    } catch (IOException e) {
        e.printStackTrace();
    }

    int[] data = new int[width * height];
    for (int i = 0; i < width * height; i++) {
        int a = (pixels[i] & 0xff000000) >> 24;
        int r = (pixels[i] & 0xff0000) >> 16;
        int g = (pixels[i] & 0xff00) >> 8;
        int b = (pixels[i] & 0xff);

        data[i] = a << 24 | b << 16 | g << 8 | r;
    }

    int result = glGenTextures();
    glBindTexture(GL_TEXTURE_2D, result);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, BufferUtils.createIntBuffer(data));
    glBindTexture(GL_TEXTURE_2D, 0);
    return result;
}

public void bind() {
    glBindTexture(GL_TEXTURE_2D, texture);
}

public void unbind() {
    glBindTexture(GL_TEXTURE_2D, 0);
}

}

```

VertexArray class :

```
public class VertexArray {

private int vao , vbo , tbo , ibo;

private int count;

public VertexArray(float[] vertices , float[] texCoords , byte[] indices) {

    count = indices.length;

    vao = glGenVertexArrays();
    glBindVertexArray(vao);

    vbo = glGenBuffers();
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, BufferUtils.createFloatBuffer(vertices), GL_STATIC_DRAW);
    glVertexAttribPointer(Shader.VERTEX_ATTRIB, 3, GL_FLOAT, false, 0, 0);
    glEnableVertexAttribArray(Shader.VERTEX_ATTRIB);

    tbo = glGenBuffers();
    glBindBuffer(GL_ARRAY_BUFFER, tbo);
    glBufferData(GL_ARRAY_BUFFER, BufferUtils.createFloatBuffer(texCoords), GL_STATIC_DRAW);
    glVertexAttribPointer(Shader.TCOORD_ATTRIB, 3, GL_FLOAT, false, 0, 0);
    glEnableVertexAttribArray(Shader.TCOORD_ATTRIB);

    ibo = glGenBuffers();
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, BufferUtils.createByteBuffer(indices), GL_STATIC_DRAW);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    glBindVertexArray(0);
}

public void bind() {
    glBindVertexArray(vao);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
}

public void unbind() {
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    glBindVertexArray(0);
}

public void draw() {
    glDrawElements(GL_TRIANGLES, count , GL_UNSIGNED_BYTE , 0);
}

public void render() {
    bind();
    draw();
}

}

```

Can someone please explain what went wrong? Thank you!

# Answer
The "size" argument to glVertexAttribPointer() is being set to 3 for texture coords, but there are 2 texture coordinates. Setting it to 2, corrects the error.

Thanks to @user1118321 I realised the mistake !
> 1 votes

---
Tags: opengl, java
---


# Question
Title: How to un-publish a game with minimum impact?
I released a game about 5 years ago across multiple mobile platforms. I spent a couple of years supporting it, following user feedback and trying to improve its revenue unsuccessfully. In the end, I just patched all the holes I could and left it be.

Recently, I started getting a bunch of support requests for android. I don't know if it's an OS update clashing, or what, but I'm unable to do anything about it. I switched version control and backups a while (2 years or so) ago, and the earliest version of the code I have access to is from part way into a major overhaul and work on a sequel that I decided wasn't sustainable. In order to issue fixes I would need to finish the overhaul and there's no way I can afford to do that.

So... what is the best way to handle this? I was thinking of issuing refunds to the people with support requests and un-publishing from the store fronts. However, I don't want people who've just bought it to see it suddenly vanish. That's only an issue for Google Play (I don't really get any sales anywhere else now). I'm not sure if making the game unlisted would still allow players to access it from the "My Apps & Games" section in Google Play, or if any would realise if they could. Is there a better way?

Cheers

# Answer
> 2 votes
You're admitting there is really no way for you to provide the support you want, so I think the solution is simply that you shut down the game, and you shut down your business. It didn't work out, and that is OK. You learned from it, and next time you do better. So really, unless you are able to find money, time, and other resources, it's time to just move on. Let it go.

There is one thing you can do though to "keep the dream alive" - you can open source your game and code. Perhaps push out one more update where you announce this, along with the GitHub link to the code. Maybe someone else will take it on and keep it going.

---
Tags: android, google-play
---


# Question
Title: Frame rate independent gameplay implementation in pure Java
I've been looking up on FPS independent movement recently, and I somewhat understand the concept. But I'm having trouble implementing it in pure Java.

Any one have any idea of how I could implement is as well as abstract it in its own class such as "Time" class?

So, I tried implementing the suggestions in my game loop. but even though i am getting steady 60 FPS, my "deltaTime" has values of around 0.6 - 0.9, but for 60 FPS it should be 0.01 !

What is going wrong here? Should I calculate "deltaTime" at 1 or 2?

Code :

```
long lastTime = System.nanoTime();
    double delta = 0.0;
    double ns = 1000000000.0 / 60.0;
    long timer = System.currentTimeMillis();
    int updates = 0;
    int frames = 0;
    while (running) {
        long now = System.nanoTime();
        delta += (now - lastTime) / ns;

        // 1

        deltaTime = ((now - lastTime) / 1000000d);

        lastTime = now;

        if (delta >= 1.0) {

            // 2 :
            System.out.println(deltaTime);

            update();
            updates++;
            delta--;
        }
        render();
        frames++;
        if (System.currentTimeMillis() - timer > 1000) {
            timer += 1000;
            //System.out.println(updates + " ups, " + frames + " fps");
            updates = 0;
            frames = 0;
        }
        if (glfwWindowShouldClose(window))
            running = false;
    }

```

# Answer
> 0 votes
I recommend reading Glenn Fiedler article on that topic, it's very old but useful. At the end of the article, he shares a solid implementation of a fixed time-step, though not in java language. If you have a problem with the syntax, please point to the part which you can't implement in Java, so we might help.

Regarding your delta time problem, try setting a value for your fixed delta time, say 0.01, then in each update loop, add the delta time (without dividing by 1000...)to a temp variable, then check if this variable is greater than or equal to your fixed delta time, if it's, run your update function, then decrease that temp variable by the delta time, this is the same implementation in the provided link.

---
Tags: java, timing
---


# Question
Title: Ridiculous Error on Unity 5.6.4p4 Method Name doesn't exists
I am facing a strange issue on Unity version 5.6.4p4 The code compiles and runs just perfectly fine in editor but when I build it for android I see an error message saying that my method doesn't exists. I have checked many times but there is no such issue. I am not doing anything wrong. Can anyone suggest what could be wrong ?

# Answer
As mentioned by @Hellium The issue was that I generated my method through Visual studio tool which placed my method in editor only region of my class. That's why it wasn't compiling when I built for android. Lesson Learnt: Don't rely on auto code generation always :D They put your code anywhere ! Even in places that aren't always correct.
> 2 votes

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


title: Calibration using quaternion

text:
# Question
Title: Calibration using quaternion
I have an external hardware which gives me quaternion values. Now I would like to calibrate the device at a certain position and show tilt variations from that position on the UI. For example, I have a small 3D plane model. Whatever position the device maybe, after calibration the model's back should be facing the user with the tail up and from that position the rotation should be relative to the device's rotation. How to do that? Simply recording the quaternion values at the calibration position and using that to subtract from the current quaternion values from the device and setting to the 3D model is not working.

Below is the code where I apply the calibrated values:

```
imu.xAxis = (Style.qX + (imuData.quatX - Style.bX))
imu.yAxis = (Style.qY + (imuData.quatY - Style.bY))
imu.zAxis = (Style.qZ + (imuData.quatZ - Style.bZ))
imu.wAxis = (Style.qW + (imuData.quatW - Style.bW))

```

where **qX,qY,qZ and qW** are the **initail postion** of the model, **quatX, quatY, quatZ and quatW** are the **current quaternion values** from the device and **bX, bY, bZ and bW** are the quaternion values at the **calibration position**.

# Answer
That's not how you concatenate rotations represented by quaternions. I suggest using a quaternion math library so you can avoid any typos when transcribing formulas.

The inverse of a quaternion is the conjugate. The operation to concatenate 2 rotation is the multiplication.

You should end up with:

```
imu.axis = Style.calibration * imuData.quat;

```

Where `Style.calibration` is the `calibration_position * inverse(initial_position)`
> 1 votes

---
Tags: 3d, rotation, quaternion
---


title: Parsing link in Unity

text:
# Question
Title: Parsing link in Unity
Getting some JSON with a string link to images(on the server) and want to save them on device.
To save them I have to name them, so the name of the file on the server would be perfect.
Example: I have this link `https://pbs.twimg.com/profile_images/882558757531791360/CGKUrcD9.jpg`
How can I get **CGKUrcD9.jpg** part of it using C# and Unity?

# Answer
> 1 votes
Use LastIndexOf to get the position of the last antislash and use Substring to "cut" your string after the antislash:

```
string GetFileName(string link)
{
    return link.Substring( link.LastIndexOf('/') + 1 ) ;
}

```

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


# Question
Title: Unity: Is it possible to copy a rig from one model to another
Lets say I have a model with a ready humanoid rig and a humanoid model with no rig. Can I somehow copy the bones from the rig to the model with no rig in unity?

# Answer
> 1 votes
Things I did with legacy were to copy the animations of another model to my humanoid model, but the rigging must be correct.

To add bones to a model you need another tool, it is not unity work.

# Answer
> 0 votes
This is possible, but only if the model has it's vertex groups defined, with the same bones as the original. you could do this pretty fast in blender by just parenting the model to the rig. select the original model, and shift select the new model, go into weight paint mode, and click transfer weights. But i don't think unity itself can automatically assign weights to the mesh.

---
Tags: unity, rigging
---


# Question
Title: In Unity, how do I use the extra time in every frame to do some extra processing?
Let's say, for example, that my target framerate is 60 frames per second.

Now, I know that I have a maximum of 16.6 milliseconds to "do everything" every frame in order to maintain that framerate.

Let's say that I also have a background task that I wish to run. It will return some results. I don't need them urgently; I just wish to run it and have its results when it's done.

Here's my point. I know when I'm done rendering everything; `WaitForEndOfFrame()` in a coroutine tells me so. Let's say my last frame took only 13 milliseconds to render instead of 16.6, so I know I have 3.6 milliseconds to spare during which I would like to run my task for ***exactly*** those 3.6 miliseconds ***or less***, never going over my 16.6 milliseconds maximum total, and then continue with the next frame, on which I will do the same if I get some spare time.

Could I achieve this using Unity's coroutines (or some other way)? If so, how?

# Answer
This (general) approach is used in several AAA engines, but isn't very compatible with the way current Unity (2017) works.

To do what you've described, you'd have to build your own task system that doesn't immediately conflict with Unity's own process. Doing so is generally ineffective as the extra overhead negates the benefits of extra time.

For further knowledge, I suggest reading up on the fiber architecture. There are several great GDC talks on it, though they are currently locked behind the vault.

Here are the slides for Christian Gyrlin's GDC presentation on Naughty Dog's engine architecture. It can get a little low level, but it goes over how this kind of process can be achieved.

---

**That's all well and good, but what if you still want to build it?**

While there's no good way to do exactly what you want (specifically, timed processing in unity), there are plenty of ways to split your tasks into chunks, assuming the right data architecture.

So how do you build that data architecture? Well you need these metrics (Not comprehensive, hopefully a good start)

* **Task Intensity** : You need to know how much time / resources will the task requires.
* **Order of Operations** : Clearly defined task prerequisites and dependencies. These help you determine how to allocate your current resources. Small tasks with lots of dependencies should get high priorities.
* **Pausing** : Similar to above, when and where can a task sleep to free processing power for critical elements
* **Granularity** : The more granular your process, the easier it will be to take advantage of any left over resources.

Once you have these, it's pretty easy to grab something applicable using a job queue or query.

---

**What's my preferred alternative?**

Rather than intentionally calling tasks to use up leftover time, I recommend filling up that time with background processes / coroutines.

Coroutines are wonderful for dispatching tasks that don't need to be done same frame and are easy enough to split / pause. While not exactly the same context, I explain how to use them to split a task across multiple frames here

In general, if I'm at or above my target frame rate, I don't worry about squeezing out even more performance. Leave the buffer there for when future you wants to do something cool.

As DMGregory mentioned, Unity has plans to implement a proper Job System in the near future. If this is a feature you require, There is a unite talk on how it will work.
> 2 votes

---
Tags: unity, multithreading, frame-rate, coroutines
---