# Question
Title: Generating face normals with the geometry shader
I'm trying to visualize the face normals for a mesh, using the geometry shader to generate lines represeting the normal vectors. My intention was to draw that line from the triangles centroid, extenting a certain amount in the normal's direction.

This is the vertex shader's code :

```
#version 450 core

layout (location = 0) in vec3 vs_in_pos;
layout (location = 1) in vec3 vs_in_normal;
layout (location = 2) in vec2 vs_in_texc;

out VS_OUT_GS_IN {
    layout (location = 0) vec3 pos;
    layout (location = 1) vec3 normal;
    layout (location = 2) vec2 texc;
} vs_out;

void main() {
    gl_Position = vec4(vs_in_pos, 1.0f);
    vs_out.pos = vs_in_pos;
    vs_out.normal = vs_in_normal;
    vs_out.texc = vs_in_texc;
}

```

This is the geometry shader's code :

```
#version 450 core

layout (row_major) uniform;
layout (triangles) in;
layout (line_strip, max_vertices = 2) out;

in VS_OUT_GS_IN {
    layout (location = 0) vec3 pos;
    layout (location = 1) vec3 normal;
    layout (location = 2) vec2 texc;
} gs_in[];

out GS_OUT_PS_IN {
    layout (location = 0) vec4 color;
    layout (location = 1) vec3 pos;
} gs_out;

layout (binding = 0) uniform transform_pack {
    mat4 model_view_projection;
};

uniform float normal_length;
uniform vec4 start_point_color;
uniform vec4 end_point_color;

void main() {

    const vec3 avg_normal = normalize(
        gs_in[0].normal + gs_in[1].normal + gs_in[2].normal);

    const vec3 triangle_centroid =
        (gs_in[0].pos + gs_in[1].pos + gs_in[2].pos) / 3.0f;

    {
        gl_Position = model_view_projection * vec4(triangle_centroid, 1.0f);
        gs_out.color = start_point_color;
        gs_out.pos = triangle_centroid;
        EmitVertex();
    }

    {
        const vec3 end_pt = triangle_centroid + avg_normal * normal_length;
        gl_Position = model_view_projection * vec4(end_pt, 1.0f);
        gs_out.pos = end_pt;
        gs_out.color = end_point_color;
        EmitVertex();
    }

    EndPrimitive();
}

```

My problem is that the line representing the face normal has the origin at one of the triangle's vertices (not the centroid).

If, however, I change this line

```
const vec3 triangle_centroid =
    (gs_in[0].pos + gs_in[1].pos + gs_in[2].pos) / 3.0f;

```

with this line

```
const vec3 triangle_centroid =
    (gl_in[0].gl_Position.xyz + gl_in[1].gl_Position.xyz
    + gl_in[2].gl_Position.xyz) / 3.0f;

```

the line representing the normal has the origin at the centroid (as it should).

But I really have no ideea why the first approach does not produce the correct result.

Some screenshots :

first method (wrong):

second method (correct):

# Answer
Ok so I've discovered that if I remove the layout qualifiers from the input/output blocks, like this

```
out VS_OUT_GS_IN {
     vec3 pos;
     vec3 normal;
     vec2 texc;
} vs_out;

```

and like this in the geometry shader

```
in VS_OUT_GS_IN {
     vec3 pos;
     vec3 normal;
     vec2 texc;
} gs_in[];

```

it produces the expected results.

But why does it not work when the explicit layout qualifier is used for the individual members of the block ?
> 1 votes

# Answer
Although according to the OpenGL standard you should be allowed to specify whichever location you want, some drivers have specific locations for legacy uses.

Specifying locations may cause conflicts with those.

For example: https://www.opengl.org/sdk/docs/tutorials/ClockworkCoders/attributes.php

> NVidia hardware indices are reserved for built-in attributes:
>
> gl\_Vertex 0
>
> gl\_Normal 2
>
> gl\_Color 3
>
> gl\_SecondaryColor 4
>
> gl\_FogCoord 5
>
> gl\_MultiTexCoord0 8
>
> gl\_MultiTexCoord1 9
>
> gl\_MultiTexCoord2 10
>
> gl\_MultiTexCoord3 11
>
> gl\_MultiTexCoord4 12
>
> gl\_MultiTexCoord5 13
>
> gl\_MultiTexCoord6 14
>
> gl\_MultiTexCoord7 15
> 1 votes

# Answer
With a triangle with 3 vertices, I was able to get the normal pretty easily in the geometry shader using this formula:

```
vec3 normal = cross(
    normalize(vec3(gl_in[1].gl_Position) - vec3(gl_in[0].gl_Position)),
    normalize(vec3(gl_in[2].gl_Position) - vec3(gl_in[0].gl_Position))
);

```

each `gl_in[].gl_Position` is a point on the triangle. You may have to make it negative if the points are in a different order.
> 0 votes

---
Tags: glsl, normals, geometry-shader
---


title: Slowing down mouse movement in Unity

text:
# Question
Title: Slowing down mouse movement in Unity
I'm using the game to control electronics. I use the following code to determine the location of an object (the location is used to perform calculations that are sent to the electronics)

```
int centerX = Screen.width/2;
int centerY = Screen.height/2;
Vector3 centerVec = new Vector3(centerX, centerY);
Vector3 diffFromCenter = Input.mousePosition - centerVec;
Ray ray = Camera.main.ScreenPointToRay(centerVec + 0.5F*diffFromCenter);

```

This is used (along with a raycast to determine the appropriate `y` value) to determine the location of the object.

The reason I use `0.5*diffFromCenter` is because of the sensitivity of the movement (as seen in the reaction of the electronics)

The problem with this approach is that it when the (real) cursor reaches the edge of the screen and can't move further, the in-game object won't be able reach the edge of the game window.

The only idea I could come up with to solve this problem is to use code to change settings on the speed of the mouse's movement.

I can't come up with a better solution (and this one would require that I also detect when the cursor leaves the game window to restore the mouse movement speed, because we'll be running experiments and someone might need to tweak things during the experiment...)

# Answer
> 1 votes
1. Make the regular hardware mouse cursor disappear with `Cursor.visible = false;` in the Start method of some script.
2. Create a new game object called "Mouse Cursor". I recommend using an image on a screen-space canvas for this purpose, but in a 2d game you could use a sprite in world-space as well. Give it a pointy-looking sprite asset which goes well with the aesthetics of your game UI.
3. Create a script on it which uses `Input.GetAxis("Vertical")` and `Input.GetAxis("Horizontal")` to measure the vertical and horizontal mouse movement since the last update. Multiply that value with `Time.deltaTime` and your desired speed multiplier, and change the position of the mouse cursor object accordingly.
4. You might notice that it is now possible for your new custom mouse cursor to move outside of the screen. So you need to make sure to keep it within the screen boundary. You can do that with:

```
    transform.position = new Vector3(
         Mathf.clamp(transform.position.x, 0f, Screen.width),
         Mathf.clamp(transform.position.y, 0f, Screen.height),
         0f
    );

```
5. Now you might want to know how to find out if and which collider the mouse pointer is pointing at.

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


# Question
Title: Clarification of functionality of Vector2.MoveTowards method
In Unity's documentation for Vector2.MoveTowards, they assign a two variables, "speed" and "step".

"step" is simply speed * Time.deltaTime.

Why is this step variable assigned? What function does this serve that means the speed variable isn't used in place of step? What is this variable controlling when used in these parameters?

# Answer
This variable is the maximum distance the object is allowed to move on this method-call.

You usually call MoveTowards in Update in order to move an object one step closer to its destination. But the frequency of Update calls depends on the current framerate. So on lower framerates you need to move the object further per update than on higher framerates. Which is what Time.deltaTime is for. It represents the time since the last update.
> 1 votes

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


# Question
Title: What is the easiest way to make pixelated maps with obstacles in pygame?
So I have been trying to create a game with a small map that moves with the player. If the player goes to a wall, the camera also stops. No scrolling. If you want to discover an area, you go to it. And there are many obstacles. the map should be sort of the cafeteria from among us. I tried using tiled, but… It is not beginner friendly. Making a separate file is okay with me. Thanks in advance.

Full code:

```
'''
Imports
'''
import os
import random
import sys

import pygame
import pygame_textinput
from pygame.locals import *

os.chdir(os.path.dirname(os.path.abspath(__file__)))

'''
Basic Stuff for Pygame
'''
pygame.init()
display_surface = pygame.display.set_mode((800, 640))
pygame.display.set_caption("AMOGUS")
gameIcon = pygame.image.load('icon_of_the_game.png')
pygame.display.set_icon(gameIcon)

'''
Variables
'''
fps =600
ai_move_speed = 2
player_changeable_name = pygame_textinput.TextInputVisualizer()
clock = pygame.time.Clock()
white = (255, 255, 255)
WINDOWHEIGHT = 580
WINDOWWIDTH = 740

'''
Game State Variable
'''
menu = "menu"
game = "game"
ending_ani = "ending_ani"

'''
Functions
'''

def menu():
    print("In Proggress")

def game():
    print("In Proggress")

def ending_ani():
    print("In Proggress")

'''
Images
'''
special_character = random.randint(1, 5)
if special_character == 1:
    imposter = pygame.image.load('sus1.png')
    chooseable_var = random.randint(1, 4)
    if chooseable_var == 1:
        sussie1 = pygame.image.load('sus2.png')
        sussie2 = pygame.image.load('sus3.png')
        sussie3 = pygame.image.load('sus4.png')
        sussie4 = pygame.image.load('sus5.png')

    if chooseable_var == 2:
        sussie1 = pygame.image.load('sus5.png')
        sussie2 = pygame.image.load('sus2.png')
        sussie3 = pygame.image.load('sus3.png')
        sussie4 = pygame.image.load('sus4.png')

    if chooseable_var == 3:
        sussie1 = pygame.image.load('sus4.png')
        sussie2 = pygame.image.load('sus5.png')
        sussie3 = pygame.image.load('sus2.png')
        sussie4 = pygame.image.load('sus3.png')

    if chooseable_var == 4:
        sussie1 = pygame.image.load('sus3.png')
        sussie2 = pygame.image.load('sus4.png')
        sussie3 = pygame.image.load('sus5.png')
        sussie4 = pygame.image.load('sus2.png')

elif special_character == 2:
    imposter = pygame.image.load('sus2.png')
    chooseable_var = random.randint(1, 4)
    if chooseable_var == 1:
        sussie1 = pygame.image.load('sus1.png')
        sussie2 = pygame.image.load('sus3.png')
        sussie3 = pygame.image.load('sus4.png')
        sussie4 = pygame.image.load('sus5.png')

    if chooseable_var == 2:
        sussie1 = pygame.image.load('sus5.png')
        sussie2 = pygame.image.load('sus1.png')
        sussie3 = pygame.image.load('sus3.png')
        sussie4 = pygame.image.load('sus4.png')

    if chooseable_var == 3:
        sussie1 = pygame.image.load('sus4.png')
        sussie2 = pygame.image.load('sus5.png')
        sussie3 = pygame.image.load('sus1.png')
        sussie4 = pygame.image.load('sus3.png')

    if chooseable_var == 4:
        sussie1 = pygame.image.load('sus3.png')
        sussie2 = pygame.image.load('sus4.png')
        sussie3 = pygame.image.load('sus5.png')
        sussie4 = pygame.image.load('sus1.png')
elif special_character == 3:
    imposter = pygame.image.load('sus3.png')
    chooseable_var = random.randint(1, 4)
    if chooseable_var == 1:
        sussie1 = pygame.image.load('sus2.png')
        sussie2 = pygame.image.load('sus1.png')
        sussie3 = pygame.image.load('sus4.png')
        sussie4 = pygame.image.load('sus5.png')

    if chooseable_var == 2:
        sussie1 = pygame.image.load('sus5.png')
        sussie2 = pygame.image.load('sus2.png')
        sussie3 = pygame.image.load('sus1.png')
        sussie4 = pygame.image.load('sus4.png')

    if chooseable_var == 3:
        sussie1 = pygame.image.load('sus4.png')
        sussie2 = pygame.image.load('sus5.png')
        sussie3 = pygame.image.load('sus2.png')
        sussie4 = pygame.image.load('sus1.png')

    if chooseable_var == 4:
        sussie1 = pygame.image.load('sus1.png')
        sussie2 = pygame.image.load('sus4.png')
        sussie3 = pygame.image.load('sus5.png')
        sussie4 = pygame.image.load('sus2.png')
elif special_character == 4:
    imposter = pygame.image.load('sus4.png')
    chooseable_var = random.randint(1, 4)
    if chooseable_var == 1:
        sussie1 = pygame.image.load('sus2.png')
        sussie2 = pygame.image.load('sus3.png')
        sussie3 = pygame.image.load('sus1.png')
        sussie4 = pygame.image.load('sus5.png')

    if chooseable_var == 2:
        sussie1 = pygame.image.load('sus5.png')
        sussie2 = pygame.image.load('sus2.png')
        sussie3 = pygame.image.load('sus3.png')
        sussie4 = pygame.image.load('sus1.png')

    if chooseable_var == 3:
        sussie1 = pygame.image.load('sus1.png')
        sussie2 = pygame.image.load('sus5.png')
        sussie3 = pygame.image.load('sus2.png')
        sussie4 = pygame.image.load('sus3.png')

    if chooseable_var == 4:
        sussie1 = pygame.image.load('sus3.png')
        sussie2 = pygame.image.load('sus1.png')
        sussie3 = pygame.image.load('sus5.png')
        sussie4 = pygame.image.load('sus2.png')
else:
    imposter = pygame.image.load('sus5.png')
    chooseable_var = random.randint(1, 4)
    if chooseable_var == 1:
        sussie1 = pygame.image.load('sus2.png')
        sussie2 = pygame.image.load('sus3.png')
        sussie3 = pygame.image.load('sus4.png')
        sussie4 = pygame.image.load('sus1.png')

    if chooseable_var == 2:
        sussie1 = pygame.image.load('sus1.png')
        sussie2 = pygame.image.load('sus2.png')
        sussie3 = pygame.image.load('sus3.png')
        sussie4 = pygame.image.load('sus4.png')

    if chooseable_var == 3:
        sussie1 = pygame.image.load('sus4.png')
        sussie2 = pygame.image.load('sus1.png')
        sussie3 = pygame.image.load('sus2.png')
        sussie4 = pygame.image.load('sus3.png')

    if chooseable_var == 4:
        sussie1 = pygame.image.load('sus3.png')
        sussie2 = pygame.image.load('sus4.png')
        sussie3 = pygame.image.load('sus1.png')
        sussie4 = pygame.image.load('sus2.png')
hero = pygame.image.load('hero.png')

'''
Hero
'''
heroX = 100
heroY = 100
MOVESPEED = 2
moveRight = False
moveLeft = False
moveUp = False
moveDown = False
'''
Imposter
'''
ImpX = 50
ImpY = 500
imp_left = False
imp_right = True
down_val = 64
up_val = -64
default_mover = down_val
'''
Sussies
'''
Sussie1X = 0
Sussie1Y = 0
Sussie2X = 50
Sussie2Y = 50
Sussie3X = 100
Sussie3Y = 100
Sussie4X = 250
Sussie4Y = 250

'''
Main Script
'''
game_state = menu
while game_state == menu:

    display_surface.fill(white)
    display_surface.blit(imposter, (ImpX, ImpY))
    display_surface.blit(sussie1, (Sussie1X, Sussie1Y))
    display_surface.blit(sussie2, (Sussie2X, Sussie2Y))
    display_surface.blit(sussie3, (Sussie3X, Sussie3Y))
    display_surface.blit(sussie4, (Sussie4X, Sussie4Y))
    display_surface.blit(hero, (heroX, heroY))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        if event.type == pygame.KEYDOWN:
            # Change the keyboard variables.
            if event.key == K_LEFT or event.key == K_a:
                moveRight = False
                moveLeft = True
            if event.key == K_RIGHT or event.key == K_d:
                moveLeft = False
                moveRight = True
            if event.key == K_UP or event.key == K_w:
                moveDown = False
                moveUp = True
            if event.key == K_DOWN or event.key == K_s:
                moveUp = False
                moveDown = True
        if event.type == pygame.KEYUP:
            if event.key == K_LEFT or event.key == K_a:
                moveLeft = False
            if event.key == K_RIGHT or event.key == K_d:
                moveRight = False
            if event.key == K_UP or event.key == K_w:
                moveUp = False
            if event.key == K_DOWN or event.key == K_s:
                moveDown = False
        else:
            pass

    if moveDown and heroY < WINDOWHEIGHT:
        heroY += MOVESPEED
    if moveUp and heroY > 0:
        heroY -= MOVESPEED
    if moveLeft and heroX > 0:
        heroX -= MOVESPEED
    if moveRight and heroX < WINDOWWIDTH:
        heroX += MOVESPEED

    if heroY == 0:
        heroY = 0

    if heroX == 0:
        heroX = 0

    if heroX == 740:
        heroX = 740

    if heroY == 580:
        heroY = 580

    if imp_right:
        ImpX += ai_move_speed
        if ImpX == WINDOWWIDTH or ImpX > WINDOWWIDTH:
            imp_right = False
            imp_left = True
            ImpY += default_mover
        if ImpY == 0 or ImpY > WINDOWHEIGHT:
            default_mover = up_val
            imp_left = True
            imp_right = False

        if ImpY == 0 or ImpY < 0:
            default_mover = down_val
            imp_left = True
            imp_right = False

    if imp_left:
        ImpX -= ai_move_speed
        if ImpX == 0 or ImpX < 0:
            imp_left = False
            imp_right = True
            ImpY += default_mover
        if ImpY == WINDOWHEIGHT or ImpY > WINDOWHEIGHT:
            default_mover = up_val
            imp_left = False
            imp_right = True

        if ImpY == 0 or ImpY < 0:
            default_mover = down_val
            imp_left = False
            imp_right = True

    clock.tick(fps)
    pygame.display.update()

```

Cafeteria: https://among-us.fandom.com/wiki/Cafeteria

# Answer
If you are okay with using separate files to use as your map : just write down all the obstacles rectangular shape which is INSIDE that map and use that information to whatever collision detection action You need.

However, if you are a beginner I suggest making games with static Viewport (exploring the map only moves the character), they're a lot easier.

*Share your code*, so we can help you.
> 0 votes

---
Tags: pygame
---


# Question
Title: How to make objects move continuously while a key is pressed in pygame?
So I made a new game in pygame and after hours of debugging, I got to a stage where all of my objects get blitted onto the screen. Well, that's great but now I want movement for a particular object. I achieved that task easily enough, but I was wondering is there a way to make movement continuous while a key is pressed. For example, while the down key is pressed down, the character will smoothly glide 5 steps down instead of jerking repeatedly. This won't be good in a runner game where the player chooses when to start running and when to stop. I thought that this would work:

```
if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_DOWN:
                heroY += 10

```

but unfortunately, this is the same as removing the second line and fixing the code indentation. I am very new to pygame and am making test projects to practice. Thanks in advance.

Full Code :

'''
Imports
'''
import pygame_textinput
import pygame
import sys
import random
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))

'''
Basic Stuff for Pygame
'''
pygame.init()
display_surface = pygame.display.set_mode((800, 640))
pygame.display.set_caption("AMOGUS")
gameIcon = pygame.image.load('icon_of_the_game.png')
pygame.display.set_icon(gameIcon)

'''
Variables
'''

player_changeable_name = pygame_textinput.TextInputVisualizer()
clock = pygame.time.Clock()
white = (255, 255, 255)

'''
Game State Variable
'''
menu = "menu"
game = "game"
ending_ani = "ending_ani"

'''
Functions
'''
def menu():
    print("In Proggress")

def game():
    print("In Proggress")

def ending_ani():
    print("In Proggress")

'''
Images
'''
special_character = random.randint(1, 5)
if special_character == 1:
    imposter = pygame.image.load('sus1.png')
    sussie1 = pygame.image.load('sus2.png')
    sussie2 = pygame.image.load('sus3.png')
    sussie3 = pygame.image.load('sus4.png')
    sussie4 = pygame.image.load('sus5.png')
elif special_character == 2:
    imposter = pygame.image.load('sus2.png')
    sussie1 = pygame.image.load('sus1.png')
    sussie2 = pygame.image.load('sus3.png')
    sussie3 = pygame.image.load('sus4.png')
    sussie4 = pygame.image.load('sus5.png')
elif special_character == 3:
    imposter = pygame.image.load('sus3.png')
    sussie1 = pygame.image.load('sus1.png')
    sussie2 = pygame.image.load('sus2.png')
    sussie3 = pygame.image.load('sus4.png')
    sussie4 = pygame.image.load('sus5.png')
elif special_character == 4:
    imposter = pygame.image.load('sus4.png')
    sussie1 = pygame.image.load('sus1.png')
    sussie2 = pygame.image.load('sus2.png')
    sussie3 = pygame.image.load('sus3.png')
    sussie4 = pygame.image.load('sus5.png')
else:
    imposter = pygame.image.load('sus5.png')
    sussie1 = pygame.image.load('sus1.png')
    sussie2 = pygame.image.load('sus2.png')
    sussie3 = pygame.image.load('sus3.png')
    sussie4 = pygame.image.load('sus4.png')
hero = pygame.image.load('hero.png')

'''
Hero
'''
heroX = 100
heroY = 100

'''
Imposter
'''
ImpX = 0
ImpY = 0

'''
Sussies
'''
Sussie1X = 0
Sussie1Y = 0
Sussie2X = 500
Sussie2Y = 500
Sussie3X = 250
Sussie3Y = 250
Sussie4X = 100
Sussie4Y = 500

'''
Main Script
'''
game_state = menu
while game_state == menu:

    display_surface.fill(white)
    display_surface.blit(imposter, (ImpX, ImpY))
    display_surface.blit(hero, (heroX,heroY))
    display_surface.blit(sussie1, (Sussie1X,Sussie1Y))
    display_surface.blit(sussie2, (Sussie2X,Sussie2Y))
    display_surface.blit(sussie3, (Sussie3X,Sussie3Y))
    display_surface.blit(sussie4, (Sussie4X,Sussie4Y))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_DOWN:
                heroY += 10

        if event.type == pygame.KEYUP:
            pass
    pygame.display.update()

```
</code></pre>

# Answer
> 2 votes
Your problem is nothing related to Pygame. It's about Python.

`pygame.event.get()` is a function that reports **CURRENT EVENTS** received from the user.

It means when you press a key, an event is sent to this function, which type is `pygame.KEYDOWN`. And when you release that key, another event is being sent: `pygame.KEYUP`.

Note that when you are **holding** a specific key, **no** event is being sent to `pygame.event.get()`.

So, basically, all you need to do is track held-down keys using `pygame.KEYDOWN` and `pygame.KEYUP`.

### Method 1: creating a medium list

With this method, whenever a key is pressed, you `append` it to a list. Whenever you release that key, you `remove` it from the list. Then, all you need to do is check that list in your game loop.

*Use this if you want to track down many held keys.*

```
heldKeys=[]

def getEvents():
    global heldKeys
    for i in pg.event.get():
        if i.event==pygame.KEYDOWN:#Track down key presses here

            if i.key==pygame.K_DOWN:
                heldKeys.append('Down')

        elif i.event==pygame.KEYUP:#Track down key releases here

            if i.key==pygame.K_DOWN:
                heldKeys.remove('Down')

def checkHeldKeys():#use this in you'r game loop to move you'r character
    global heroY;
    for i in heldKeys:
        if 'Down' in heldKeys:
            heroY+=10;

```

### Method 2: creating a medium boolean variable

In here, all You need is a boolean:

* Whenever the `pygame.KEYDOWN` signal is sent, set this boolean to `True`.
* whenever the `pygame.KEYUP` signal is sent, set this boolean to `False`.

*Use this method **only** if you need to check 1 or 2 held keys.*

<pre><code>isMoving=False

def getEvents():
    global heldKeys
    for i in pg.event.get():
        if i.event==pygame.KEYDOWN:#Track down key presses here

            if i.key==pygame.K_DOWN:
                isMoving=True

        elif i.event==pygame.KEYUP:#Track down key releases here

            if i.key==pygame.K_DOWN:
                isMoving=False

def checkIsMoving():#use this in you'r game loop to move you'r character
    global heroY;

    if isMoving==True:
        heroY+=10
```

# Answer
> 1 votes
Answering for movement in all 4 directions.

1. Create some variables for movements. For example: `moveLeft` and `moveRight` and set them to false (this should be out of the game loop).
2. Add this to after the `for event in pygame.event.get():` loop.

```
        if event.type == pygame.KEYDOWN:
            # Change the keyboard variables.
            if event.key == K_LEFT or event.key == K_a:
                moveRight = False
                moveLeft = True
            if event.key == K_RIGHT or event.key == K_d:
                moveLeft = False
                moveRight = True
            if event.key == K_UP or event.key == K_w:
                moveDown = False
                moveUp = True
            if event.key == K_DOWN or event.key == K_s:
                moveUp = False
                moveDown = True
        if event.type == pygame.KEYUP:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()
            if event.key == K_LEFT or event.key == K_a:
                moveLeft = False
            if event.key == K_RIGHT or event.key == K_d:
                moveRight = False
            if event.key == K_UP or event.key == K_w:
                moveUp = False
            if event.key == K_DOWN or event.key == K_s:
                moveDown = False
        else:
            pass

```
3. Now the image I want to move is in the hero variable. Before the game loop, I would add `heroX = "X coordinate of hero"` and `heroY = "Y coordinate of hero.` and put these in the `screen.blit()` of the hero image.
4. Now finally add this section to the main loop before `pygame.Display.update()`:

```
if moveDown and heroY < WINDOWHEIGHT:
    heroY += MOVESPEED
if moveUp and heroY > 10:
    heroY -= MOVESPEED
if moveLeft and heroX > 10:
    heroX -= MOVESPEED
if moveRight and heroX < WINDOWWIDTH:
    heroX += MOVESPEED

```

P.S: `WINDOWHEIGHT` and `WINDOWWIDTH` are my display's height and width and `MOVESPEED` is an integer of movement speed.

Hope this easy fix helped!

---
Tags: pygame
---


title: How to add delay to the moving objects?

text:
# Question
Title: How to add delay to the moving objects?
Now all the moving objects are moving like a group to the same target. I need them to move to the same target but with a delay between them.

The first object start moving to the target after X seconds the second object start moving to the target then the third and so on they all should move to the first target but with a delay between the moving start.

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

public class MoveToTarget : MonoBehaviour
{
    public AnimationCurve curve = AnimationCurve.EaseInOut(0.0f, 0.0f, 1.0f, 1.0f);
    public List<Transform> targets = new List<Transform>();
    public List<Transform> objectsToMove = new List<Transform>();
    public float duration;
    public bool moveToSameTarget = false;

    private float t;
    private List<Vector3> originPositions = new List<Vector3>();

    // Start is called before the first frame update
    void Start()
    {
        t = 0.0f;
        curve.postWrapMode = WrapMode.Once;

        for (int i = 0; i < objectsToMove.Count; i++)
        {
            originPositions.Add(objectsToMove[i].transform.position);
        }
    }

    // Update is called once per frame
    void Update()
    {
        t += Time.deltaTime;
        float s = t / duration;

        for (int i = 0; i < objectsToMove.Count; i++)
        {
            objectsToMove[i].position = Vector3.Lerp(originPositions[i], targets[0].position, curve.Evaluate(s));
        }
    }
}

```

# Answer
> 0 votes
Currently your t is evaluated the same for all your objects. If they should arrive at different times at your destination, they need their own t or at least know the delay. Without changing too much of your logic, you could assign a negative startTime to future objects and apply it only once it turns positive.

```
private List<float> startTime = new List<float>();
public float delay = 0.75f;

void Start() {
        t = 0f;
        curve.postWrapMode = WrapMode.Once;
        for (int i = 0; i < objectsToMove.Count; i++) {
            startTime.Add(-1 * i * delay);
            originPositions.Add(objectsToMove[i].transform.position);
        }
    }

    void Update() {
        t += Time.deltaTime;
        for (int i = 0; i < objectsToMove.Count; i++) {
            float s = (t + startTime[i]) / duration;
            if (s > 0) {
                objectsToMove[i].position = Vector3.Lerp(originPositions[i], targets[0].position, curve.Evaluate(s));
            }
        }
    }

```

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


# Question
Title: How can I cache and read fields on non instantiated prefabs?
Let's say I have a very simple 2D square prefab that has a script like this attached to it:

```
public class Square : MonoBehaviour
{
    public GameObject GameObject { get; private set; }
    public Transform Transform { get; private set; }
    public SpriteRenderer SpriteRenderer { get; private set; }

    private void Awake()
    {
        GameObject = gameObject;
        Transform = transform;
        SpriteRenderer = GetComponent<SpriteRenderer>();
    }
}

```

I want to be able to arrange groups of these squares with different positions and sprite colors, saving them as prefabs to be used by a spawner (with object pooling), sort of like this:

```
public class SquareSpawner : MonoBehaviour
{
    [SerializeField]
    private Square[] squares;

    private ObjectPool<Square> pool;

    public void Spawn(Vector2 position)
    {
        foreach (var square in squares)
        {
            /* Get a square prefab from object pool
               (this will instantiate a Square prefab into the scene
               if one does not yet exist) */
            Square pooledSquare = pool.Get();

            /* Set up the squares we got from the pool
               to match the squares given to the squares array */
            pooledSquare.Transform.position = position + square.Transform.localPosition;
            pooledSquare.SpriteRenderer.Color = square.SpriteRenderer.Color;

            // etc.
        }
    }
}

```

Basically, I'm trying to create a spawning system that is easily visualizable using prefabs. Since object pooling is used, I don't know the configuration of the square I'll be getting back, so I always have to set the given squares' properties to match the desired configuration (this could be size, color, position, etc.).

The issue is that I can't read the properties from the `Square` prefabs that are not being instantiated (the ones I'm putting into the `Square[] squares` array) because the `Awake()` method only gets called upon instantiation into the scene.

Perhaps there's a better way for me to set all of this up, but I'm wondering if there's a way for me to cache the properties in the `Square` class so that I can read them whether the script is on a prefab and/or an instantiated `Square` in the scene. It would also be nice if I could use a custom editor to test things in edit mode, which has also been hindered by my inability to cache these fields.

# Answer
Simple: ensure the data you want to access is serialized and available in the saved version of the prefab.

```
[RequireComponent(typeof(SpriteRenderer))]
public class Square : MonoBehaviour
{
    [field:SerializeField, HideInInspector]
    public SpriteRenderer spriteRenderer { get; private set; }

    private void OnValidate()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();
    }
}

```

This will...

1. Ensure the object has a `SpriteRenderer` component when you add the `Square` component, if it didn't already, via the `RequireComponent` attribute.
2. Immediately call `OnValidate` when you edit the prefab in the inspector, caching a reference to that `SpriteRenderer`.

(Technically here you could also use the `Reset` method which is called once when the component is added or manually reset to its defaults in the editor, rather than `OnValidate` which is called after every change or assembly reload in editor, as well as on entering play mode. But `OnValidate` is a bit more flexible if there's other stuff you want to set up that might *not* be available from the first moment the component is added. Note Philipp's caution from he comments that neither of these methods is called in the build, so use this only to set up data that you can serialize and load from disk already in the correct state)
3. Serialize that reference via the `field:SerializeField` attribute, so that it's saved with the prefab and available to read from the saved version without instantiating it.

I did not do this with the `gameObject` or `transform` members because those are already available to us in serialized prefabs through `MonoBehaviour` without needing to write any extra code of our own.

---

Alex Hetherington has created a handy editor script that simplifies this common task of linking-up component references. Now you can just add a `[Resolve]` attribute above the serialized component field you want to populate, and it will add a one-click button to populate the field (even populating an array of references), without you having to write your own initialization in `OnValidate()` or elsewhere. Here's a link to the GitHub repository with this and other utilities you can add to your project.
> 2 votes

---
Tags: unity, prefabs, object-pools
---


# Question
Title: Avoid shaking artifacts in 3D continuous collision detection
I am programming a 3D game physics engine that uses continuous collision detection to avoid my objects from being able to "tunnel" through the geometry.

Here is basically how it works:

1. Execute a swept-object/world collision check
2. Move the object up to the exact point where it collides
3. If no time is remaining, everything is done, just stop
4. Else, update the velocity so that the object "slides" in a direction orthogonal to the collision normal before returning to step 1. This is the formula I use for this sliding (I just remove the component of the motion in the normal direction): `velocity = velocity - (velocity dot normal) * normal`

My problem occurs in this kind of situation:

(Do not take into account faces other than A and B, their only purpose is the emphasize the 3D aspect of the shape)

In the first frame, the object first follows the black arrow, then collides face A. It slides correctly on face A (first red arrow) and then climbs on face B (second red arrow). The problem with this algorithm is precisely the fact that it can climb on the opposite face: after several consecutive frames (here the other frames are the cyan and green ones), the general motion will follow the good path (the intersection line of planes A and B), but with a local left-right shaking artifact that I would appreciate getting rid of.

Any idea to solve this would be greatly appreciated.

# Answer
I had the same problem and I found a solution in the paper "Improving the Numerical Robustness of Sphere Swept Collision Detection" by Jeff Linahan, found here: https://arxiv.org/ftp/arxiv/papers/1211/1211.0059.pdf

In short, your collision response loop should have exactly three iterations:

* If you collide in the first iteration you do the sliding response as usual.
* If you collide in the second iteration you calculate the second sliding plane, but you don't project your velocity vector onto it. Instead, you calculate the crease vector, which is equal to the normalized cross product of the normals of the first and second sliding planes. Now project your velocity onto the crease vector-- that's your velocity for the next and final iteration.
* If you collide in the third iteration, there is no sliding response. Just stop at the point of impact.

The above linked paper contains illustrations and explanations of why this works.

Also caveat, the author notes that while this solves the jitteriness, it also increases instances of getting stuck in geometry. He goes on to explain how to mitigate this by tweaking tolerance values in his implementation, but I'm not sure how that would apply to what you're doing.
> 4 votes

---
Tags: collision-detection, physics, 3d
---


# Question
Title: OpenTK immediate mode on net core doesn't work?
I have some old code that i imported into an OpenTK C# application running on NET 5.0. The rendering uses old fashioned immediate mode and it works on my current computer but nothing renders in the new application. The old application was NET framework 4.7.2 and an older version of OpenTK. When creating the window i request the same OpenGL version as the older application uses.

Did OpenTK remove this functionality in the newer version?

This is code i used to test this:

```
using OpenTK.Graphics.OpenGL;
using OpenTK.Windowing.Common;
using OpenTK.Windowing.Desktop;
using System;
using OpenTK.Mathematics;

namespace tktest2
{
    public class Window : GameWindow
    {
        private float ClipNear = 0.2f;
        private float ClipFar = 10000.0f;
        public Matrix4 ProjectionMatrix;
        public Matrix4 ViewMatrix;

        public Window(GameWindowSettings gameWindowSettings, NativeWindowSettings nativeWindowSettings)
            : base(gameWindowSettings, nativeWindowSettings)
        {
        }

        protected override void OnLoad()
        {
            base.OnLoad();

            Console.WriteLine(GL.GetString(StringName.Vendor));
            Console.WriteLine(GL.GetString(StringName.Renderer));
            Console.WriteLine(GL.GetString(StringName.Version));
            Console.WriteLine(GL.GetString(StringName.ShadingLanguageVersion));

            GL.Enable(EnableCap.DepthTest);
            GL.Disable(EnableCap.Texture2D);
            GL.Disable(EnableCap.CullFace);
            GL.Disable(EnableCap.Blend);

            this.VSync = VSyncMode.On;
        }

        protected override void OnUnload()
        {
            base.OnUnload();
        }

        protected override void OnResize(ResizeEventArgs e)
        {
            base.OnResize(e);

            ProjectionMatrix = Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, (float)Size.X / (float)Size.Y, ClipNear, ClipFar);
            GL.Viewport(0, 0, Size.X, Size.Y);
        }

        protected override void OnUpdateFrame(FrameEventArgs e)
        {
            base.OnUpdateFrame(e);
        }

        protected override void OnRenderFrame(FrameEventArgs e)
        {
            base.OnRenderFrame(e);
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            ViewMatrix = Matrix4.LookAt(new Vector3(0, -5, 0), new Vector3(0, 0, 0), Vector3.UnitZ);
            GL.Color4(1.0f, 1.0f, 1.0f, 1.0f);
            GL.Normal3(Vector3.UnitZ);

            GL.MatrixMode(MatrixMode.Projection);
            GL.LoadMatrix(ref ProjectionMatrix);
            GL.MatrixMode(MatrixMode.Modelview);
            GL.LoadMatrix(ref ViewMatrix);

            GL.PointSize(10);
            GL.Begin(BeginMode.Points);
            for (int x = 0; x < 10; x++)
            {
                GL.Color3(1.0f, 1.0f, x / 10.0f);
                GL.Vertex3(x / 10.0f, 0.0f, 0.0f);
            }
            GL.End();

            SwapBuffers();
        }
    }
}

```

# Answer
OpenTK is discouraging the use of immediate mode. But it is still supported. To use it, you need to set `NativeWindowSettings.Profile` to `ContextProfile.Compatability`. That is, you want an entry point that looks something like this:

```
using OpenTK.Windowing.Common;
using OpenTK.Windowing.Desktop;

namespace tktest2
{
    internal static class Program
    {
        static void Main()
        {
            var gameSettings = GameWindowSettings.Default;
            var nativeSettings = NativeWindowSettings.Default;
            nativeSettings.Profile = ContextProfile.Compatability;
            using (var window = new Window(gameSettings, nativeSettings))
            {
                window.Run();
            }
        }
    }
}

```

I have tested this on Windows 10, .NET 6, with the OpenTK Nuget version 4.6.7, on Visual Studio 2022. This is the output I got with your code:
> 4 votes

---
Tags: c#, opengl, opentk
---


title: posting cards in memory game

text:
# Question
Title: posting cards in memory game
I am making a memory game using opengl and c++. I am able to post playing cards to the screen. I am having a problem posting two identical cards randomly to the screen. I am able to post 10 cards to the screen but the second 10 cards are posted blank. As you can see from my code the vector a creates the sequence of 20 values which is 10 pairs that is outputted randomly.

```
void init()
{
    // Step 1
    int nPairs = 10;
    int nCards = nPairs * 2;
    vector<int> a;

    // Step 2. creates the sequence 0 0 1 1 2 2 3 3 4 4 ...
    for (int i = 0; i < nCards; i++)
    {
        a.push_back(i / 2);     // or v.push_back(i >> 1);
    }

    // Step 3
    random_device rd;
    mt19937 g(rd());
    shuffle(a.begin(), a.end(), g);

    // Step 4
    for (int i = 0; i < nCards; i++)
    {
        cout << a[i] << " ";
    }
        texture[a[0]] = loadTex("C:\\Users\\Owner\\Desktop\\2_of_clubs.png");
        texture[a[1]] = loadTex("C:\\Users\\Owner\\Desktop\\3_of_clubs.png");
        texture[a[2]] = loadTex("C:\\Users\\Owner\\Desktop\\4_of_clubs.png");
        texture[a[3]] = loadTex("C:\\Users\\Owner\\Desktop\\5_of_clubs.png");
        texture[a[4]] = loadTex("C:\\Users\\Owner\\Desktop\\6_of_clubs.png");
        texture[a[5]] = loadTex("C:\\Users\\Owner\\Desktop\\7_of_clubs.png");
        texture[a[6]] = loadTex("C:\\Users\\Owner\\Desktop\\8_of_clubs.png");
        texture[a[7]] = loadTex("C:\\Users\\Owner\\Desktop\\9_of_clubs.png");
        texture[a[8]] = loadTex("C:\\Users\\Owner\\Desktop\\10_of_clubs.png");
        texture[a[9]] = loadTex("C:\\Users\\Owner\\Desktop\\jack_of_clubs2.png");
        texture[a[10]] = loadTex("C:\\Users\\Owner\\Desktop\\queen_of_clubs2.png");
        texture[a[11]] = loadTex("C:\\Users\\Owner\\Desktop\\king_of_clubs2.png");
        texture[a[12]] = loadTex("C:\\Users\\Owner\\Desktop\\ace_of_clubs.png");
        texture[a[13]] = loadTex("C:\\Users\\Owner\\Desktop\\2_of_diamonds.png");
        texture[a[14]] = loadTex("C:\\Users\\Owner\\Desktop\\3_of_diamonds.png");
        texture[a[15]] = loadTex("C:\\Users\\Owner\\Desktop\\4_of_diamonds.png");
        texture[a[16]] = loadTex("C:\\Users\\Owner\\Desktop\\5_of_diamonds.png");
        texture[a[17]] = loadTex("C:\\Users\\Owner\\Desktop\\6_of_diamonds.png");
        texture[a[18]] = loadTex("C:\\Users\\Owner\\Desktop\\7_of_diamonds.png");
        texture[a[19]] = loadTex("C:\\Users\\Owner\\Desktop\\8_of_diamonds.png");
}

```

# Answer
> 1 votes
`a[i]` contains the values `0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9` in some random order.

So when you use that as the index into `texture`, you're only ever loading textures into the first 10 locations in the `texture` array.

To see this more clearly, comment out the code between step 3 & step 4 and then manually step through the code in step 4. What you have is:

```
texture[0] = loadTex("C:\\Users\\Owner\\Desktop\\2_of_clubs.png");
texture[0] = loadTex("C:\\Users\\Owner\\Desktop\\3_of_clubs.png");
texture[1] = loadTex("C:\\Users\\Owner\\Desktop\\4_of_clubs.png");
texture[1] = loadTex("C:\\Users\\Owner\\Desktop\\5_of_clubs.png");
...
texture[9] = loadTex("C:\\Users\\Owner\\Desktop\\7_of_diamonds.png");
texture[9] = loadTex("C:\\Users\\Owner\\Desktop\\8_of_diamonds.png");

```

The array locations `texture[10]` to `texture[19]` never get initialized, which is presumably why the second half of the array gives blank cards.

Here's a possible alternative:

```
void init()
{
    // Step 1, some initializations
    int nPairs = 10;
    int nCards = nPairs * 2;
    vector<int> a;

    // Step 2, creates the sequence 0 0 1 1 2 2 3 3 4 4 ... 8 8 9 9
    for (int i = 0; i < nCards; i++)
    {
        a.push_back(i / 2);
    }

    // Step 3, shuffles a
    random_device rd;
    mt19937 g(rd());
    shuffle(a.begin(), a.end(), g);

    // step 4, initialize textures
    texture[0] = loadTex("C:\\Users\\Owner\\Desktop\\2_of_clubs.png");
    texture[1] = loadTex("C:\\Users\\Owner\\Desktop\\3_of_clubs.png");
    texture[2] = loadTex("C:\\Users\\Owner\\Desktop\\4_of_clubs.png");
    texture[3] = loadTex("C:\\Users\\Owner\\Desktop\\5_of_clubs.png");
    texture[4] = loadTex("C:\\Users\\Owner\\Desktop\\6_of_clubs.png");
    texture[5] = loadTex("C:\\Users\\Owner\\Desktop\\7_of_clubs.png");
    texture[6] = loadTex("C:\\Users\\Owner\\Desktop\\8_of_clubs.png");
    texture[7] = loadTex("C:\\Users\\Owner\\Desktop\\9_of_clubs.png");
    texture[8] = loadTex("C:\\Users\\Owner\\Desktop\\10_of_clubs.png");
    texture[9] = loadTex("C:\\Users\\Owner\\Desktop\\jack_of_clubs2.png");

    // step 5, build selection of cards using randomized sequence
    for(int i=0; i<nCards; i++)
    {
       card[i] = texture[a[i]];
    }
}

```

This will fill the `card` array with a randomized collection of 10 different pairs of cards drawn from `texture`.
Note: wherever you declare `texture`, you'll need to make sure to also add the necessary code to declare the `card` array.

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


# Question
Title: Unity custom editor - nested Property Drawer is getting Enum names for the parent property, instead of the child
I have a class, `EnumMap<TEnum,TValue>`, for associating each member of an enum type with a value of a given type, since I find myself running into situations like that frequently. It acts similarly to a dictionary, but is stored as parallel Lists for serialization.

Since, during design time, I want to edit the contents of the value list but not its structure (and I don't want to edit the enum list at all), I wrote a custom property drawer that renders EnumMaps as if they were basic Serializable C# classes with a named member for each value of the enum. That is, if you have an enum defined like `enum Example { A, B, C }`, and a field with the type `EnumMap<Example, int>`, the field will render as if it's an instance of a class with three `int` fields named `A`, `B`, and `C`:

```
[Serializable]
public class EquivalentClass
{
    public int A, B, C;
}

```

The property drawer works great in every situation I've tested so far except for when an `EnumMap` maps to an `EnumMap` \- ie, `EnumMap<SomeEnumType, EnumMap<SomeOtherEnumType, SomeValueType>>`. In that case, the child EnumMaps display the names of the *parent* enum type, and the property drawer errors out if the child enum has more name values than the parent.

I believe it has to do with how I'm getting the display names of the enums, but the documentation on `SerializedProperty.enumDisplayNames` and `SerializedProperty.enumValueIndex` isn't particularly helpful, and I haven't had any luck with Google. I've also tried `SerializedProperty.enumNames` but that didn't seem to change anything. (Side question - what exactly is the difference between those?) It could also be something to do with how I'm actually accessing the property in the first place, since I'm pretty new to custom editors.

**Question**: what's the idiomatic way to retrieve display names for a given enum value when writing custom editors? And how can you ensure that nested properties are retrieving the right relative values, instead of their parents'?

---

Here's the code for `EnumMap`:

```
[Serializable]
public class EnumMap<TEnum, TValue> : ISerializationCallbackReceiver
    where TEnum : Enum
{
    public TValue this[TEnum e]
    {
        get => m_values[getOrAddEnumPosition(e)];
        set => m_values[getOrAddEnumPosition(e)] = value;
    }

    [SerializeField] List<TEnum> m_enums;
    [SerializeField] List<TValue> m_values;

    public void OnBeforeSerialize ()
    {
        createAndResizeLists();
    }

    public void OnAfterDeserialize ()
    {
        createAndResizeLists();
    }

    void createAndResizeLists ()
    {
        if (m_enums == null) m_enums = new List<TEnum>();
        if (m_values == null) m_values = new List<TValue>();

        foreach (var e in EnumUtil.AllValues<TEnum>())
        {
            getOrAddEnumPosition(e);
        }
    }

    int getOrAddEnumPosition (TEnum e)
    {
        int position = m_enums.IndexOf(e);

        if (position != -1)
        {
            return position;
        }
        else
        {
            m_enums.Add(e);
            m_values.Add(default);
            return m_enums.Count - 1;
        }
    }
}

```

And here's its property drawer:

```
[CustomPropertyDrawer(typeof(EnumMap<,>))]
public class EnumMapDrawer : PropertyDrawer
{
    public override void OnGUI (Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.BeginProperty(position, label, property);

        Rect foldoutPosition = position;
        foldoutPosition.height = foldoutLabelHeight(label);
        property.isExpanded = EditorGUI.Foldout(foldoutPosition, property.isExpanded, label, true);

        if (property.isExpanded)
        {
            EditorGUI.indentLevel++;
            Rect fieldPosition = EditorGUI.IndentedRect(position);
            fieldPosition.y += foldoutLabelHeight(label) + EditorGUIUtility.standardVerticalSpacing; // ensure fields start below the label

            var enums = property.FindPropertyRelative("m_enums");
            var values = property.FindPropertyRelative("m_values");

            for (int i = 0; i < enums.arraySize; i++)
            {
                var value = values.GetArrayElementAtIndex(i);

                var currentEnum = enums.GetArrayElementAtIndex(i);
                string enumLabel = currentEnum.enumNames[currentEnum.enumValueIndex];

                fieldPosition.height = EditorGUI.GetPropertyHeight(value);
                EditorGUI.PropertyField(fieldPosition, value, new GUIContent(enumLabel), true);
                fieldPosition.y += fieldPosition.height + EditorGUIUtility.standardVerticalSpacing;
            }

            EditorGUI.indentLevel--;
        }

        EditorGUI.EndProperty();
    }

    public override float GetPropertyHeight (SerializedProperty property, GUIContent label)
    {
        if (!property.isExpanded) return base.GetPropertyHeight(property, label);

        var values = property.FindPropertyRelative("m_values");

        float height = foldoutLabelHeight(label) + EditorGUIUtility.standardVerticalSpacing; // include the label and some space
        for (int i = 0; i < values.arraySize; i++)
        {
            height += EditorGUI.GetPropertyHeight(values.GetArrayElementAtIndex(i), true) + EditorGUIUtility.standardVerticalSpacing;
        }

        return height;
    }

    float foldoutLabelHeight (GUIContent label)
    {
        return EditorGUI.GetPropertyHeight(SerializedPropertyType.String, label);
    }
}

```

Here's some minimal code to reproduce the property drawer issue:

```
public enum LongerEnum
{
    A, B, C, D
}

public enum ShorterEnum
{
    One, Two, Three
}

public class EnumMapTester : MonoBehaviour
{
    public EnumMap<ShorterEnum, EnumMap<LongerEnum, int>> Test;
}

```

# Answer
Seem like a bug in Unity serialization, `enumNames` and `enumValueIndex` are unreliable for the inner enumeration type.

But there is a good news that Unity provides fieldInfo property for PropertyDrawer, so we can get the type information.

Here is the code and comments:

```
if (property.isExpanded)
{
    EditorGUI.indentLevel++;
    Rect fieldPosition = EditorGUI.IndentedRect(position);
    fieldPosition.y += foldoutLabelHeight(label) + EditorGUIUtility.standardVerticalSpacing; // ensure fields start below the label

    var enums = property.FindPropertyRelative("m_enums");
    var values = property.FindPropertyRelative("m_values");

    // Get the type information from fieldInfo
    var fieldType = fieldInfo.FieldType;
    var genericTypeDefinition = fieldType.GetGenericTypeDefinition();
    var enumNames = enums.enumNames;
    if (genericTypeDefinition == typeof(EnumMap<,>)) // EnumMap as a field
    {
        enumNames = System.Enum.GetNames(fieldType.GenericTypeArguments[0]);
    }
    else if(genericTypeDefinition == typeof(List<>)) // EnumMap inside another EnumMap
    {
        enumNames = System.Enum.GetNames(fieldType.GenericTypeArguments[0].GenericTypeArguments[0]);
    }

    for (int i = 0; i < enums.arraySize; i++)
    {
        var value = values.GetArrayElementAtIndex(i);

        // 'enumValueIndex' is unreliable.
        // but because you add all the values of an enum type into 'm_enums',
        // so we can use just 'i' instead.
        var enumLabel = enumNames[i];

        fieldPosition.height = EditorGUI.GetPropertyHeight(value);
        EditorGUI.PropertyField(fieldPosition, value, new GUIContent(enumLabel), true);
        fieldPosition.y += fieldPosition.height + EditorGUIUtility.standardVerticalSpacing;
    }

    EditorGUI.indentLevel--;
}

```
> 1 votes

---
Tags: unity, gui, serialization
---


# Question
Title: How to calculate distance for A* when searching a path on navmesh?
I've read a couple of articles on Navmesh+A\* navigation. So, I'm trying to implement a pathfinding for an RTS type of game. However, it seems I don't understand how to calculate a distance for A\* when searching a path on navmesh.

I cannot really calculate distance between centers of navmeshes because in that case I don't get the best path.

**Example:**

Here I have three navmeshes interconnected with each other. If I need to move a unit as illustrated in the picture the optimal path is obviously the green one.

However, if I calculate the distance between centers of navmeshes when I use A\*, the path would be calculated as red in the picture.

So, how do I account for entry and exit point in navmeshes when calculating the distance for A\*?

# Answer
> 2 votes
When you say you want to calculate the "distance for A\*", you mean the heuristic, right? The heuristic is an *estimate* of the distance. And you want to avoid *overestimating* it. See Admissible heuristic.

Unless we are dealing with teleportation, or some not euclidean geometry, there is no way that units will reach the destination via a shorter path than a straight line. Thus, the distance on straight line never overestimates the distance. Therefore the distance on straight line is an admissible heuristic. Which means A\* should work correctly using it.

I mean, something like this:

```
distance_estimate = (dst - src).length()

```

---

> However, if I calculate the distance between centers of navmeshes when I use A\*, the path would be calculated as red in the picture.

This could happen if you *overestimated* the distance. The distance from the centers of the navmeshes can be longer than the actual distance, so that can happen. *Although you still got a valid path.*

By the way, I imagine you are doing something like this:

```
var src_area = get_area(src)
var dst_area = get_area(dst)
distance_estimate = (dst_area.center - src_area.center).length()

```

---

> So, how do I account for entry and exit point in navmeshes when calculating the distance for A\*?

You can pick the exit that is closer to the other point. Closer as measured in a straight line. That might not be the correct exit, but it would avoid overestimating the distance (assuming you have convex areas, which is how these systems work). Which makes it an admissible heuristic.

I mean, something like this:

```
var src_area = get_area(src)
var src_exit = get_min(src_area.exits, exit => (exit - dst).length())

var dst_area = get_area(dst)
var dst_exit = get_min(dst_area.exits, exit => (exit - src).length())

distance_estimate += (dst_exit - src_exit).length()

```

However, it is not necessarily a better heuristic. *We want to make sure we don't overestimate, but we want to underestimate as little as possible.* We can make it better if we add the distance from the point to the exit we picked.

So, you would do something like this:

```
var src_area = get_area(src)
var src_exit = get_min(src_area.exits, exit => (exit - dst).length())

var dst_area = get_area(dst)
var dst_exit = get_min(dst_area.exits, exit => (exit - src).length())

distance_estimate = (src_exit - src).length()
                  + (dst_exit - dst).length()
                  + (dst_exit - src_exit).length()

```

---
Tags: path-finding, rts, navmesh
---


# Question
Title: Online game persistent player data security
I'm currently working on the backend to my game, which is an MMO RPG-*style* game. I have my game client build, game server build, authentication server and player data server set up (albeit, locally currently - servers are expensive O.O) and I'm mostly happy with the current implementation, but I can't figure out a way to **exclusively** allow my game server write access to the player data server.

Currently, the player data server (API) once authenticated via the auth server will serve (read-access) a players current data, such as; level, gold, inventory content etc. basically game-state for that player character. That's all good and working.

During a game session, the players state is going to change, and I'm going to need to update the player data server at the end of a game session, to persist the data for next time they log on. I'm just having a total mental block on how to securely implement this... Currently, I have a 'Game Server' authorisation level to my API which gives write access to a specific player on the player data server in conjunction with a session token for a specific player - but this method involves me having the email + password for this 'Game Server' level access account hard coded on my game server so that it can connect with this level, which (and I'm not a security expert by any means...) seems like a really bad idea!

Any and all advise appreciated! If I missed anything pertinent / you need more info, just ask :)

# Answer
> 1 votes
First of all, most hard-coded credentials vulnerabilities are about a "master password" or similar, that anybody could use to log-in. In other words: a backdoor. I don't think that is not what we are talking about here.

And about the issue of third parties that may attempt a connection, you want a firewall solution. For example, have a firewall configured to only let through connection to the relevant network port from the MAC/domain/IP range of the game servers.

*If the above answer is not satisfactory, keep reading.*

---

Storing server credentials on the server is the way it is often done. It is common practice. It makes sense.

*Before we go on, I want to point out that if the credentials are hard-coded, it also means you would need to build the game server software again if you need to change the credentials, which is an issue by itself.*

Why is this considered OK to store credentials on the server? After all, if the hosting of the game server is compromised, the attackers could get the stored credentials (hard-coded or not). It is considered OK because if the server is compromised, then it is compromised. The attackers are already on the other side of security. We don't want the situation to get to that.

Instead of trying to figure out how to have the server run in a hostile environment, we should be trying to figure out how to prevent it.

---

However, if the concern is a data breach. Can we take further measures? Yes. The way to not have credentials for the data server on the game server at all, is to derive them for each player. That is, you will be creating accounts for each player on the data server. *No, no, pay attention.*

When the player logs into the game server, it will attempt to log-in to the data server with that password (or a key derived from it). *The game server should not store the password nor the derived key, and also should not do any verification on the password.* Then the data server can do authentication and return a session ID to the game server.

In other words, the data server will be both an storage server and an authentication server (or it will further delegate to the authentication server). *From here on, I'll talk about the authentication server.*

Done this way, if there is a data breach, malicious users won't find there any player passwords there, nor credentials for the data server or authentication server (except - perhaps - credential for minimal read only access, if that is something you need).

On top of that, you can have a password for the game server, stored on it. Then code authentication to require both the game server password and a player password. *Which sounds like what you are doing.* If the game server password is stolen, it will be useless without the player passwords.

---

However, one thing is a data breach, and another thing is a hosting under the control of attackers. For example, if the server is compromised, the attackers could add code to the hosting to intercept attempts to log-in from the players, and store the passwords.

So, can we take further measures? Yes, with the goal to protect passwords even in this situation, yes. This is my proposal: Implement PGP on the client. You are going to generate a public-private key pair for your authentication server. The public key - as the name suggest - will be public, and deployed with the client.

Then the client can generate a random symmetric key, use it to cipher the password, and also cipher the symmetric key with the public key. That way, to get the password we need the private key, which - as the name suggest - should remain private, to get the symmetric key to get the password.

And only the authentication server will be able to do that. If the game server is compromised and the attacker intercepts the communication on it, they will not be able to open them. However, we need to invalidate them, so the attackers cannot reuse them. Solution: add a nonce.

To log-in, the client will first request a nonce (some cryptographic random sequence), generated by the authentication server. And the client must include the same nonce under the cipher with the password to log-in. And - of course - the nonce should only be valid once, so the authentication server must keep track of which has been issued and not yet received (and yes, you can have them expire too).

Now, if the attackers intercepted a log-in attempt, it won't be useful for any subsequent log-in because it won't match a valid nonce. If the attackers got a nonce from the authentication server, they won't be able to make the package again because they don't know the client password.

---

Ah, but a compromised server is a compromised server. Perhaps the attackers cannot get the passwords, but they can intercept the session IDs, and hijack the sessions. We could prevent them form inserting requests (e.g. using single use tokens), but they could still intercept and modify the ones the game server makes. So they could, for example, sell double resources to players.

*By the way, most site that claim to give you extra rewards in such and such are fake. They are after gullible people.*

For tamper protection we would use a hash. But the attackers can recalculate the hash on the modified request. So we upgrade to a signature with a private key. But the private key would be stored with the game server, so the attackers would be able to mimic that too. And for whatever other measures, the attackers could reverse engineer the game server and work around that too. Perhaps you want to use some obfuscation to make it harder. But there are no guarantees.

At least players are not sharing their password with the attackers… Or are they? If the attackers compromised the game server, and somebody gave them their password, they could modify that player data. Perhaps add some rewards to their account. And this might be enough to convince a fraction of the player base to share their passwords. There is no solution for people giving their password willingly.

I want to get across that even if we managed to protect user passwords in the case of the game server being compromised without being detected. It is not normal operation. You want to be able to detect the problem (be it from regular audits, from monitoring activity, from logs, from automated alerts, or whatever), and you want to be able to fix it (which requires a plan and preparations for that plan).

# Answer
> 0 votes
Servers talking to servers need to authenticate themselves to each other. And in order to do that, they need a secret (password or certificate). That's a pretty normal IT problem not limited to game servers.

The usual solution is not to hardcode the credentials in the sourcecode, but to **put them into a separate configuration file** read by the server at runtime.

If it is not too much work to implement on your technology stack, then I would recommend to use **certificate-based authentication** instead of password-authentication for server-server communication. It has the advantage that the database only needs the public key of the gameserver, while the private key remains on the gameserver. The less copies of the login credentials are around, the better.

Firewall rules which prevent any other IP address except the server IP from connecting to the write-enabled IP can be an additional measure as part of a defense-in-depth strategy, but I would not rely on that. The reason is that when the authentication system breaks, you will notice immediately. But when the firewall rules get deactivated for some reason, you might not notice anything until someone successfully connects to the database who shouldn't.

---
Tags: security
---


# Question
Title: How to calculate player damage in a game
I'm developing an RPG and I want to do the damage calculation in my game.

I have for example the following situation:

Player 1 Stats:

```
{
    "hp": 160,
    "attack": 22,
    "defense": 27,
    "speed": 19,
    "luck": 11
}

```

Player 2 Stats:

```
{
    "hp": 160,
    "attack": 16,
    "defense": 23,
    "speed": 17,
    "luck": 14
}

```
1. Let's assume that Player 1 will give a physical attack. What calculation would I use to get the attack value?
2. Let's assume that Player 1 will use a skill that has an attack strength of 70, that is, how would I calculate it based on attack + skill?
3. Using the attribute "luck", how could I also calculate a probability of giving +5% attack depending on "luck"?

# Answer
Very close to be **"more suited for a forum"** but still answerable.

When designing **damage formulas** and related mechanics, there are well tested approaches. As we have now an entire universe of games to analyze.

First: I have seen `Attack + Skill` but mostly on RTE games or top down action RPGs. While `Character.Strength + Weapon.Attack` is more common for **RPGs/JRPGs**. We are still missing target's `defenses/resistances/armors`.

It is better to **multiply/scale** `Character.Attack/Strength` rather than add `Skill.Power` to it. Otherwise your skill will became obsolete in late game, and you will need a growth system that gives your Character more powerful skills with time, so player stop using obsolete skill in favor of the newer ones.

And this **damage skills going obsolete** is very common in `JRPGs`. They do this to give the player a sense of progression. In those games, you need the leveling, but also the skills. Raw stats alone won't be enough. You need both.

A notable example of this are most 2D Final Fantasy titles.

Add the weapon power to the Character attack/strength is more acceptable, as weapons are OK to became obsolete in late game, forcing the playing to buy more expensive weapons.

Western RPGs are more tactical, in average. A damage skill may have a stronger version, but this doesn't have to mean the previous one is obsolete. It may still be useful because it costs less MP or whatever.

There is also the possibility of leveling skills rather than learning new ones. The idea here is that different skills must do different things. If you just want more damage, but same effect, then just level the same skill, don't learn new ones. Think **Diablo**/**Torchlight**.

---

This is what happens when you use the + operator.

Skill:

```
{
  Name: "Slash",
  Power: 10,
  Stat: "Attack",
  DamageType: "Physical",
  Cost: 32
}

```

Damage Formula:

```
if DamageType == "Physical":
   Damage = Character.Attack + Skill.Power - Target.Defense
else if DamateType == "Magical":
   Damage = Skill.Power - Target.MDefense

```

Leveling Formula: `final_stat = base_stat * level`

HP also levels by this formula.

***Note: this is for simplicity. But nobody does this kind of leveling. Notes on this at the end.***

Let's take some time to wonder why magical damage is raw. Because we don't have a stat for magic casting. In our worldbuilding, magic doesn't depend on a Character' stat. Who knows the most powerful spells wins. And yes, this was done before, in Earthbound, PSI (magic) abilities do raw damage, with a random variance between a minimum and a maximum, and magic defense doesn't exist.

We will introduce `variance` based on `Character.Luck` latter.

Then let's look how the damage becomes obsolete with leveling. Assuming same Character and Enemy level. Let's look at the turns requiring to kill a foe. Note: if your game is real time, it's possible to extrapolate `damage per turn` to `damage per second`.

The same foe, as long as levels match, takes more turns to be killed by the same skill in late game.

Your game may or may not be OK with this.

If not OK, then you have some options: allow skills to gain levels too. There are real world examples of this system. Think in Skill Trees of most MMORPGs out there, where you can expend skill points in skills you already learned, to make them stronger.

Doing this you can compensate for the **numeric effect** shown in the graph.

---

Now let's hack the damage formula. We can make `Defense` a division, but for simplicity, let's change one thing at a time.

Damage Formula:

```
if DamageType == "Physical":
   Damage = Character.Attack * Skill.Power - Target.Defense

```

Ignore that a level 1 it takes 4 turns to kill the foe. That's a rounding artifact. I forced all damages to round down, and all turns to round up.

What that graph shows is that, as long as there aren't other factors like equipment (armor/weapons) at play, the same foe, as long as levels match, will die in the same amount of turns.

I think that is a lot more "elegant" from a mathematical point of view. I like more this damage formula.

There are room for improvement. Try this: do your spreadsheet, but use this damage formula: `Character.Attack * Skill.Power / Target.Defense`

Also watch for the **negative damage** artifact. With the **subtract defense** formula, you may heal the target, in place of damaging it, if defense is too high. In this case, just code an extra `if` at the end of damage calculation, and round to 0 if value is negative.

While **a division will never change the sign of damage**. But watch for other parts of your final damage formula that may.

You still may add skill leveling to your design, but it will be to match lore, or because you think it gives player something extra to do. But not because you need to fight your math.

---

**Damage formula expanded**

There is room for improvement.

Most games also have the concepts of elemental attacks. Imbue weapons. Etc.

---

**Variance**

In PokeMon there isn't variance in damage calculation except a **move** has a unique mechanic. There are such moves.

But in most RPGs out there there is variance as a way to add uncertainty to action outcomes.

Example: `Damage = Damage + Damage * Math.random(-0.10, 0.10)`

Where `Math.random` is your favorite runtime random function. And Damage is a variable already containing a value as result of your damage formula.

Pay attention to operator priority. Multiplication solves first.

In words: damage plus a random value that goes from -10% of damage to +10% of damage.

This is a good place to give that `Luck` stat a reason to exists.

You can make `luck` affect the variance somehow.

Example: `Damage = Damage + Damage * Math.random(-0.10 + 0.10 * (LUCK/MAX_POSSIBLE_LUCK), 0.10)`

In this case, we use `Luck` to shift the lower limit of variance to the right. You may do the same for the upper limit, if you want.

`MAX_POSSIBLE_LUCK` is a constant. And is must be set to the max allowed `LUCK`, for a legal, non hacked, character in your game. And here is our first problem. This requires you to know your max allowed legal `LUCK` in advance.

---

**Mechanic has implied narrative or must be coherent with lore**

This is an open debate. Some say yes, some say no. I say yes.

What exactly is `Luck`?

Because I understand `Strength`. It implies the Character has big muscles.

And I also may understand `Attack`. It is more general, for better or worse. It implies the Character does more damage with physical attacks but it doesn't tell us exactly how. It may have big muscles, or it may use its martial arts knowledge to compensate the lack of muscles/size and hit as hard as a very tall person.

Now, while I don't really get `Luck`, its use is common. Truth be said.

For Fire Emblem (I don't sure if all of them, but at least the 2D ones). Luck is used in `Critical Hit Chance` calculation:

```
Unit's skill/2 + the weapon critical chance + the support bonus (if any) + the class critical bonus (if any) + character's skills (if any) - the enemy's Luck

```

Source

I think it comes from Tolkien's: **"Luck is also an skill"**. He didn't invented it, its common belief, but I'm sure it got to gamedevs thanks to him.

But... What exactly it is telling us? That universe is more on the side of that character than on the side of others?

---

**Be digital, not analog**

Specially true for `Luck`.

In my experience, players don't notice oscillating values. Think in analog radio signals. They won't notice a stat is affecting something analog. The only way they will notice is if you tell them with a help text in your game gui.

Global variance is OK. But nobody will notice if a stat affect it.

Making luck oscillate between -10% and +10%, or between 0% and +5%, is no good.

The mechanic of Critical hits comes to the rescue.

Refer to the Fire Emblem formula once more. The analog part is hidden in the game code. The player will get a digital, binary, experience. It's critical or not critical. But they will notice that more `Luck` affect the frequency of critical hits.

Said all that, all game is unique. Just do what you feel.

---

**Notes on leveling**

`base_stat * level` isn't good. Nobody does that.

You start with very small numbers at level 1 and you end with very big ones at level 100.

Take inspiration from PokeMon, again.

You can define your character structures as a set of initial and maximum stats. The advantage of this, is that you know, and control, the final shape of your characters. Then level will change a stat from minimum to maximum in steps of 1/100. This, assuming you want to cap at level 100.

In JavaScript:

```
var UniqueCharacterDatabase = {
  Hero: {
     BaseStatsMin: {
       hp: 50,
       mp: 25,
       attack: 21,
       defense: 18,
       luck: 8
     },
     BaseStatsMax: {
       hp: 2000,
       mp: 800,
       attack: 243,
       defense: 204,
       luck: 97
     }
   }
}

```

Formula to calculate current stats:

```
var level_cap = 100;

var any_stat = Math.floor(any_stat_min + (any_stat_max - any_stat_min) / level_cap * (current_level - 1));

```

Example, at level 50, attack would be `129`. And that is a nice number for level 50.

You can tune the "growth formula" to include some form of easing. But I think it's not needed.

**Note**: It's not a good idea redo the numeric simulations shown in graphs with this new proposed leveling system. Because with the simpler `stat * level` formula, a characters is, to other characters, always the same as long as levels match.

But with the new leveling system, depending of how you shape two characters final shape, the distance between them may get smaller or bigger, as they approach to their final shape. This would introduce "noise" in the graphs if we only want to analyze the damage formulae.
> 2 votes

# Answer
It appears that you came up with an array of stats first, and now try to figure out what those stats could be doing.

I think you might be approaching this problem from the wrong direction.

The way I would approach the design of an RPG combat system is:

1. How do I want the core gameplay loop to feel? Do characters attack each other? How many hits does it take to take one down?
2. How varied do I want the experience to be? Should different opponent feel different to fight? Should I perhaps allow the player to use different playstyles to get a different combat experience? What should enemies and players be able to do during combat to provide such a variety?
3. What bells and whistles could I add to that core gameplay loop? A leveling system perhaps? How do I want the core gameplay loop to turn out when two characters with different levels fight each other? Or perhaps some additional mechanics which make the game more interesting by forcing strategic decisions?
4. What formulas do I need to create such a game experience?
5. What stats do I need to feed into those algorithms?

That way I would not end up with the question "I got that luck stat, what could it do?". When I don't have a use-case in mind, then I would not create such a stat in the first place (more ranting from me about the uselessness of a luck stat here).

When you never designed an RPG combat system before, then I would recommend you to start with the most simple possible system and iterate from there:

* Every character got exactly one stat: HP
* Characters take alternating turns
* Characters can do exactly one thing: Attack, which takes away 1 HP from the opponent
* First one with 0 HP loses

When you implement this and try it out, you will realize that it's not a particularly interesting system (although in some cases where the main appeal of the game lies elsewhere, it might actually be enough). Especially because the result is a foregone conclusion: The one with more HP wins, when it's a tie the winner is the one who moves first. How could you iterate on the idea to make it more interesting?

For example:

* You could give the characters another stat: Attack, which starts out as simply the number of HP their attacks take. The battle is *still* a foregone conclusion, but it's not that obvious at first glance who will win (now you at least need to perform a division to predict the winner).
* You could add some randomness to the equation so battles are no longer deterministic. For example:
    + Randomize the damage.
    + Randomize the turn order, so characters might move twice before the opponent gets a chance to act. This might work well with a "speed" stat which decides how often characters get turns.
    + Add a hit/dodge mechanic which creates a random chance to negate attacks (which might or might not warrant a new "dexterity" or "agility" stat)
* You could add different forms of attacks which do different amounts of damage. But in order to prevent players from always using their strongest attack, you might also want to add some kind of a resource mechanic.
* You could add a defense mechanic, which could start out as a simple subtraction (damage = damage - defense), but could get more complicated when you realize flaws in it. The main reason for this stat is to shift which attacks are cost-effective against which enemies (high-def opponents might only be beatable with costly attacks, while low-def opponents could be beat with less resource-intense attacks).
* You could add support for parties of multiple combatants. Now it becomes a strategic decision which enemies to take out first.
* Perhaps attacks with damage types and characters with resistances or vulnerabilities to certain attacks could make the game more interesting?
* You could add a progression system which allows characters to increase their stats. But how stronger do you want characters to get as the game progresses, and how much do you want the gameplay to change through that progression? This is a decision you have to make for your game.

When you go through this iterative process until you have a fun combat system, you are going to end up with more or less stats, but you will have a reason for each one to exist and you will know what it does.
> 38 votes

---
Tags: game-design, algorithm, rpg
---


# Question
Title: How do you quantify a relation between 2 countries?
I am trying to create a computer game similar to that of *Europa Universalis* or *Civilization*. FYI, those are grand strategy games - you select a country and try to guide it through the years in order to create a world superpower.

In these types of games the existing relations between your country and other countries are crucial for making alliances and signing trade agreements. In most games this relationship is usually a number (integer) between -100 and 100, where 0 means neutral, +100 means excellent, -100 means very bead relations.

My game is set at the present time so I need know how to quantify a relation between any 2 countries.

The first idea that came to my mind was to collect different questionnaire data to find out what people from this country think of that country. However this method doesn't always reflect real relations between governments.

# Answer
> 2 votes
The Crusader Kings series simulates relationship scores not just between countries but also between any relevant people in those countries, which can easily get to tens of thousands of characters. While they did quite a lot of historic research, they of course did not go so far as to find out what the Duke of Wessex thought about some minor noble in India in 1066. They modeled the relationship system in a way which scales far better.

The gist is that each character received a bunch of character traits like "Zealous", "Cynic", "Brave", "Craven", "Arbitrary", "Just" etc. Some of them based on how historic evidence described well-known historic people, but most of them randomly assigned. Now the relationship between any two characters is simply a function taking their personality traits into account. "Zealous" vs. people of other religions: -20 opinion. "Brave" vs. "Craven": -10 opinion. "Both Just": +10 opinion, and so on. This allows to calculate a hypothetical relationship score between any two characters anywhere in the world, even if they would probably not even have known of each others existence.

Opinion modifiers between any two characters might also be affected by temporary modifiers resulting from interactions between those characters ("insulted me during a banquet: -20 opinion for 5 years") but those are rather the exception than the norm when it comes to quantifying the relationship between any two characters.

The advantage of this system is that this system scales linearly instead of quadratically. You still need to research and apply properties for `n` entities, but you do not need to do the same for `n * n` relationships.

The same system could be used for countries in your game:

1. Think of some inherent properties countries could have which could affect their relationship with other countries: Political system, culture, language, values, etc.
2. Make up plusses and minuses for opinions based on those properties. Like "Democratic" vs. "Autocratic": -20. "Same official language": +10. "Both socially progressive": +20.
3. Think of any other game systems you have which might feed into the opinion system. For example, when your game simulates exports and imports (a very important factor for real-world political relationships), then you might add opinion penalties for countries which are competitors for the same product or opinion bonuses for countries which trade a lot with each other.

A word of warning, though: When you are trying to model the world of 2022, then you are stepping into a minefield of controversy. Your data and the simulation resulting from it will necessary contain a couple things with the potential to offend a lot of people. So make sure that it is clear that your product is supposed to be first and foremost **a game** and not meant to be a political statement. But even then you can expect that the PR and community management of your game will become a pretty nerve-wracking job. Oh, and if your game is sufficiently successful, then it will probably get banned in a couple countries for contradicting the local government's narrative of world politics. For example: Good luck modeling the middle-east in a way that is not going to offend the censors of *any* authoritarian government in the area.

---
Tags: game-design, simulations
---


# Question
Title: Use of java for game dev, must I pay for it?
I would like to start programming a video game using Java. This will be my first video game. I choose java because of portability, so I develop the game and then it run on every system. But now I read that Java has become paid.

https://java.com/en/download/release\_notice.jsp

I've read the FAQ on the website, but I don't understand. If I develop this videogame using java and then I sell it, for example, in steam, or epic games store, or android store, must I pay for it? and, more important, if someone buy this game, he need to pay java in order to use it?

# Answer
No, you will not have to pay to use Java.

According to the OTN license agreement \- which will apply to Java Runtime and Development Kit - these uses are free:

* Personal Use,
* Development Use,
* Oracle Approved Product Use, and/or
* Oracle Cloud Infrastructure Use.

We are interested in Personal use:

> “Personal Use” refers to an Individual's use of the Programs solely on a desktop or laptop computer under such Individual's control only to run Personal Applications.
>
> “Personal Applications” refers to Applications designed for individual personal use only, such as **games** or personal productivity tools.

Which would cover playing games.

And Development Use:

> “Development Use” refers to Your internal use of the Programs to develop, test, prototype and demonstrate Your Applications. For purposes of clarity, the “to develop” grant includes using the Programs to run profilers, debuggers and Integrated Development Environments (IDE Tools) where the primary purpose of the IDE Tools is profiling, debugging and source code editing Applications.

Which would cover developing games.

---

When you sell a game made with Java, you are not selling the Java Runtime nor the Java Development Kit. Instead, the end user is supposed to get them that on their own.

However, it appears that using the Java Runtime or the Development Kit on a server solution is not free (with exceptions). Please refer to the linked license for details. There is no replacement for reading the actual license.

By the way, OpenJDK would allow you to use Java, and it is under GPL version 2 (The GPL are free software licences according to the Free Software Foundation, and are approved by the Open Source Initiative).
> 3 votes

---
Tags: java, licensing
---


# Question
Title: How can I tint the color of a decal in Unity?
For my game, I want some sort of indicator of if a space is walkable or not. To achieve this I figured I would create a decal projector and have it follow the mouse cursor around, displaying a decal beneath the cursor. I would then color this decal a different color depending on if the surface the cursor is over is walkable or not (e.g. red for not walkable and green for walkable). However, when I change the color of the decal's material the color of the decal does not change! How can I change the color of a decal in Unity using Universal Render Pipeline?

```
[RequireComponent(typeof(DecalProjector))]
public class DecalTinter : MonoBehaviour
{
    [SerializeField] private Color validColor = Color.green;
    [SerializeField] private Color invalidColor = Color.red;

    [SerializeField] private new Camera camera;

    private DecalProjector decalProjector;

    private void Start()
    {
        Assert.IsNotNull(camera);
        decalProjector = GetComponent<DecalProjector>();
    }

    private void Update()
    {
        var ray = camera.ScreenPointToRay(Input.mousePosition);
        if (!Physics.Raycast(ray, out var hitInfo, float.MaxValue, LayerMask.GetMask("Ground")))
        {
            return;
        }

        var material = decalProjector.material;
        // This does not work!
        material.color = NavMesh.SamplePosition(hitInfo.point, out _, 0.1f, NavMesh.AllAreas)
            ? validColor
            : invalidColor;
    }
}

```

# Answer
Unfortunately this does not seem possible with the default decal projector shader. Fortunately creating your own shader that does this is super easy!

1. First create the decal projector and add your script that will tint the material.
2. Then open up the editor for the decal shader:

3. You should now be in the shader graph editor. From here, follow these steps:

* Click the "+" on the blackboard, (1) on your left. If you do not have this window, activate it by clicking "Blackboard" in the top right corner. From this popup menu add a new "Color" attribute, and name it ***exactly*** `Color` (capitalization matters here!). This binds the variable to the `Color` field of your material.
* Right-click anywhere and click "Create node". Add 1 `Multiply` node (2).

4. Now that you have the multiply node and color input, arrange them like so:

* Color input into Multiply (drag from Blackboard list).
* Base Map Sample Texture 2D into Multiply.
* Multiply into Base Color of the Fragment.

5. Now save your shader by clicking "Save as..." in the top left and save it to wherever you like. Do NOT click "Save Asset", since that will override the default shader!
6. Use the shader you just created, by going back to the inspector and selecting your shader in the dropdown.
7. Done! You can now tint your decal by changing the color of the material:

```
var decalProjector = GetComponent<DecalProjector>();
decalProjector.material.color = Color.red; // Whatever color you need

```

Since we used the `Multiply` node, the white parts of your decal will be brighter in color and the black parts will be darker in color. Transparent parts will still be transparent.
> 2 votes

---
Tags: unity, shaders, unity-urp, decal-system
---


# Question
Title: Capturing hard movement from one side to the other on thumbstick
I am trying to implement a hard pivot, like in Mario game, where the character is moving in one direction then you move the stick in a hard 180 to trigger the pivot animation.

My problem is that I calculate my velocities and rotation based on the thumbstick position each frame. Velocity is calculated from the magnitude of the Thumbstick axis, using `Input.GetAxis`. (0-\>0.1 Idle, 0.1-\>0.4 walk, 0.4-\>1 Run). Rotation is calculated from the difference between `transform.forward` and axis direction. See below:

```
float angle = Math.Abs(Vector3.Angle(transform.forward, axisDirection));
if (angle > 175) animator.SetTrigger("turn180");

```

For example:

```
Frame 1: Thumbstick is at Vector2(-1,0) Character facing (-1,0) Angle = 0
Frame 2: Thumbstick is at Vector2(0,0) Character facing (-1,0) Angle = 0
Frame 3: Thumbstick is at Vector2(1,0) Character facing (-1,0) Angle = 180

```

In this example the Animator would be told to play Run animation in Frame 1, Idle in Frame 2 and Run again in Frame 3. What I need to to basically ignore Frame 2 then the Animator will be told to play the Pivot 180 animation. The problem is during the time the `angle == 0` the character is turning in an arc towards the direction of input which is not the desired animation. Obviously this shouldn't be an issue if the player can move the stick quick enough but it is not realistic to expect the player to do that.

What is the best practice to capture such input? I was thinking of implementing a buffer and using the Thumbstick values from a certain time ago, but that has it's own issues. Similarly, I was thinking of detecting the speed of movement of stick and only change movement if it is under a certain threshold. (I.e. in a certain place for a certain amount of time) but that could introduce lag? There must be an accepted way to handle this sort of input.

# Answer
I have come up with a solution that calculates the average speed of the stick movement in the past 0.05s, if it is over a certain threshold the stick is moving fast and the input will revert to the previous input. If it is under the threshold, the stick has slowed to an acceptable level, input is read and animations triggered.

It's a bit of a hack so still interested in other ideas.

Example code:

```
float stickSpeedThreshold = 0.3f;
float timeBuffer = 0.05f;
Vector2 axisDirectionBuffer; //Set 0.05s ago
float speedOfStickMovement = Vector2.Distance(axisDirection, axisDirectionBuffer) / timeBuffer;
if(speedOfStickMovement < stickSpeedThreshold)
{
    //Continue movement processing
}
else
{
    //Skip movement processing for this frame
}

```
> 0 votes

---
Tags: unity, animation, input
---


# Question
Title: Trouble using delta in my movement function
```
this.up = function () {
  this.velocity += this.lift * deltaTime;
};
this.update = function () {
  this.velocity += this.gravity * deltaTime;

  this.velocity *= 0.9;
  this.y += this.velocity;
}

```

Hi, I have a 2d game on canvas using p5 js thats basically like flappy bird . But Im trying to use deltaTime so the movement is the same regardless of fps.

Does anyone know how I'd apply deltaTime to keep the movement consistent across all fps?

I think it has something to do with the velocity being reduced by 0.9 but Im not sure how to apply delta to that part. Help would be appreciated

# Answer
You can apply a time step for constant continuous motion like this:

```
y += velocity * deltaTime

```

This only works where the motion is constant. That is, speed is not changing so distance is just how fast for how long.

When you have acceleration and changing speed, you need to use the equations of motion. This will tell you how to calculate distance over time with changing velocity. You can imagine that if you are applying gravity to the velocity, then the speed at the start of the time step is different to the speed at the end of the time step, so assuming constant motion will lead to errors.

You might consider using the equations of motion to calculate both your velocity and position like this:

```
velocity = old_velocity + gravity * deltaTime [1]
deltaY = 0.5 * (velocity + old_velocity) * deltaTime [3]

```

This is not the only way to apply the equations.

If you do this, even though you are simulating in discrete time steps, the results will converge to actual Newtonian physics.
> 1 votes

---
Tags: javascript, html-canvas
---


# Question
Title: Importing checker texture from blender 2.93 to unity 2020.3
I have a checker texture made in a blender 2.93

which is created in such a way, Material properties - new material - and on that material, using two texture images and adding a checker texture node in between.

while importing this to unity I can't get texture with the material.

I tried path mode to copy and enable embed textures before exporting into .fbx file but it just extracted two separated images and only one of them can be assigned to the material.

Any solution for this much appreciated

# Answer
I just created the node structure as required and then baked the texture

following several guidelines. after that used that image as a texture in the main project.

Baking of texture and using them as png instead of using node structure helps exporting materials and texture from blender to unity
> 0 votes

---
Tags: unity, blender
---


# Question
Title: prefabs not aligned at same horizantal level after instantiating
I have generated a logical grid and trying to place a prefab on top of that grid.

`Piece` is the base class for all pieces

`Pieces[]` is the 2d array holding all the pieces

1. instantiate and spawn prefab

```
private Piece spwanSinglePiece() {

 Piece cp = Instantiate(prefabs[0], transform, false).GetComponent<Piece>();
return cp
}

```
2. Position them

```

  private void PositionSinglePiece(int x, int y, bool force = false)
    {

        Pieces[x, y].transform.position = GetTileCenter(x, y);

    }
    private Vector3 GetTileCenter(int x, int y)
    {
        return  new Vector3(x * tileSize, (float)(yOffSet +0.85), y * tileSize) - bounds + new Vector3(tileSize/2,0,tileSize/2);
    }

```

Scenario

1. only yoffset value is helpful to place them on top of the board
2. but different prefab pieces require different yoffset value. cause after instantiating they are not on the same base
3. board scale is set to 1,1,1 so that parenting doesn't scale the pieces along with it
4. created prefabs scale is also 1.

Problem prefabs are not exactly on the same horizontal alignment. which is resulting in the use of different yoffset values for each piece.

if all the pieces are aligned horizontally same they single yoffset value can work this what I am trying to achieve

More details

original prefabs transform

clone prefab generated after running script. every clone prefab has a y transform of 1.05 after being generated. which is expected but all prefabs are not on same horizontal line.

so they are in different vertical position. I am not sure what really causing a issue

update - using primitive objects, scripts just run fine and produce expected results.

I think its a problem with the pieces that were created in the blender and exported into Unity

```
 1. after creating the mesh, rotating and scale applied
 2. centred origin to geometry and pivot to the median point
 3. normals recalculated
 4. while exporting settings where as follows

```

# Answer
It's possible that the models were not properly aligned in the 3d modeling program used to create them.

The ideal solution would of course be to tell the art department to get back to their 3d modeling program and move the meshes within their model files so that the floor is on height 0. This is usually a standard convention for game-ready 3d assets which are designed to be placed on a horizontal surface.

But when you got the assets from a source you can't make demands to, then you can fix this in Unity.

Create each piece prefab as an empty game-object with the 3d model as a child. You can now edit the prefab and adjust the local position of the child transform relative to the parent transform so that the base is exactly on the 0:0:0 point of the parent.
> 0 votes

# Answer
Your `GetTileCenter()` seems to be taking the mid points (horizontal & vertical), but from the image, it looks like each of the prefab have different height, so even though their midpoint is alligned, because of height, it looks uneven.

For height, you can rather use the top position, `new Vector3(tileSize/2,0,0);`
> 0 votes

---
Tags: unity, prefabs
---