# Question
Title: How to build only specified assets into assetbundle in unity
I have searched through the few results pertaining to this particular question, but haven't found any results that work. A simple rundown of what i am looking for is to be able to make a single asset bundle of specified assets in order to be able to make an automated process for what the mod system i am making for the project i am working on.

there are two ways I can think of that would be able to do this;

1. build specified resources and assets into an assetbundle
2. build everything in a specified folder into an asset bundle

all of what i have been able to find regarding this either wouldn't allow me to make the automated process i need or builds the all of the assetbundles and they have to be defined manually before hand.

Any resources or suggestions to this issue would be greatly appreciated.

# Answer
> 1 votes
After the advent of the Asset Bundle Browser tool many things have become easy. Like you can get the dependency of the asset or you can manually drag and drop the asset in asset bundle.

# Answer
> 0 votes
It looks like it is not possible to exclude individual assets apart from scripts. To exclude a script you can try following this advice: https://support.unity3d.com/hc/en-us/articles/208456906-Excluding-Scripts-and-Assets-from-builds

```
#if (UNITY_EDITOR)
... your class/code ...
#endif

```

To exclude a directory (of scripts) which I assume also works with other assets such as images, you can use a symlink to the directory.

---
Tags: unity, c#, modding, assetbundle
---


# Question
Title: How to place a camera so that it always fits a plane?
I have a plane that can get its scale changed during the game, and I want to make the camera view it completely every time the plane has its scale changed. The only camera is set to perspective projection.

I found this page which tells me how to resize the plane (I do not understand the unity of measure used there) to be viewed by the camera, and I want the reverse.

I found something similar here.

I also found other not-very-relevant answers by googling "unity camera fits a plane", "unity move camera to show an object" (one of the results is this), "unity field of view to fit an object" (one of the results is this).

I think I found the answer here, but it is hard for me to do the maths right now. I also found an answer here but I wish that someone explained me the mathematics (also, I do not know how to get the `bounds`).

My relevant previous question with the same situation is here. There is a link to download a sample project, and a few screenshots.

Thank you.

# Answer
I have found the answer here. Although it is not completely explained mathematically in my opinion, it works well.

The code I use is like this:

```
private void Start()
{
    // ...

    PositionCamera();
}

/// <summary>
/// Source: https://forum.unity.com/threads/dynamic-loaded-object-fit-to-screen-size.349794/
/// </summary>
void PositionCamera()
{
    GameObject ObjectToView = GameObject.Find("Background");
    Camera camera = Camera.main;

    Bounds objectBounds = ObjectToView.GetComponent<Renderer>().bounds;
    Vector3 objectFrontCenter = objectBounds.center - ObjectToView.transform.forward * objectBounds.extents.z;

    //Get the far side of the triangle by going up from the center, at a 90 degree angle of the camera's forward vector.
    Vector3 triangleFarSideUpAxis = Quaternion.AngleAxis(90, ObjectToView.transform.right) * transform.forward;
    //Calculate the up point of the triangle.
    const float MARGIN_MULTIPLIER = 1f;
    Vector3 triangleUpPoint = objectFrontCenter + triangleFarSideUpAxis * objectBounds.extents.y * MARGIN_MULTIPLIER;

    //The angle between the camera and the top point of the triangle is half the field of view.
    //The tangent of this angle equals the length of the opposing triangle side over the desired distance between the camera and the object's front.
    float desiredDistance = Vector3.Distance(triangleUpPoint, objectFrontCenter) / Mathf.Tan(Mathf.Deg2Rad * camera.GetComponent<Camera>().fieldOfView / 2);

    camera.transform.position = -camera.transform.forward * desiredDistance + objectFrontCenter;
}

```
> 1 votes

---
Tags: unity, c#, mathematics, camera, perspective
---


title: setTint() on half image

text:
# Question
Title: setTint() on half image
I'm developing a game where I need to paint half of a image when the user is either wrong or right. To paint the image, I'm using `setTint()` to paint the image the color I need, but it paints the whole image, is there any way I can paint only half, using setTint or another method?

# Answer
I'm unfamiliar with `phaser`, but a general way to achieve this is to create two Image objects, each one having half of the picture, and position the second below the first, so it looks like one complete image.

At the moment the user answers, you can use `setTint()` to change only half of the picture.

This method has its limitations, as you can't dynamically split an image to more parts this way, but it is a simple method that gets the desired result.
> 0 votes

---
Tags: javascript, phaser
---


# Question
Title: How to set root signatures specified in HLSL in my command list?
From Microsoft Docs, I can specify the root signature of my shader in HLSL. How do I use it though?

Since at the beginning of the command list, root signature is undefined. I need to use `ID3D12GraphicsCommandList::SetComputeRootSignature(ID3D12RootSignature*)` or `ID3D12GraphicsCommandList::SetGraphicsRootSignature(ID3D12RootSignature*)` set root signature, but having specified in HLSL instead of C++ code, I do not have a pointer to my root signature objects, how should it be done then?

# Answer
> 1 votes
You can provide any compiled shader blob that contains the desired root signature defined in HLSL when creating the root signature object:

```
Microsoft::WRL::ComPtr<ID3D12RootSignature> m_rootSignature

// Create root signature.
auto vertexShaderBlob = DX::ReadData(L"VertexShader.cso");

DX::ThrowIfFailed(
    device->CreateRootSignature(0, vertexShaderBlob.data(), vertexShaderBlob.size(),
        IID_PPV_ARGS(m_rootSignature.ReleaseAndGetAddressOf())));

…

// Use root signature
commandList->SetGraphicsRootSignature(m_rootSignature.Get());

```

> The `DX::ReadData` function just loads the binary blob from disk (source here). The `DX::ThrowIfFailed` helper is explained here.

If you are using `FXC.EXE` you can also build a shader with the HLSL defined root signature using the `rootsig_1_0` or `rootsig_1_1` profile and the resulting compiled binary object will just have the root signature in it.

---
Tags: c++, hlsl, directx12
---


title: How can I flip a sprite in SFML?

text:
# Question
Title: How can I flip a sprite in SFML?
I am facing the same problem although the sprite flips but only one time after that it does not flips at all.

Here is the code snippet:

```
void Doodle::moveLeft()
{
    if(d_Right)
        d_Sprite.setScale(-1.0f, 1.0f);
    d_Left = true;
}

void Doodle::moveRight()
{
    if(d_Left==false)
        d_Sprite.setScale(-1.0f, 1.0f);
    d_Right = true;
}

void Doodle::stopLeft()
{
    d_Left = false;
}

void Doodle::stopRight()
{
    d_Right = false;
}

```

# Answer
```
void Doodle::moveLeft() { if(d_Right) d_Sprite.setScale(-1.0f, 1.0f); d_Left = true; }

void Doodle::moveRight() { if(d_Left==false) d_Sprite.setScale(-1.0f, 1.0f); d_Right = true; }

```

This code is exactly the same, specifically: d\_Sprite.setScale(-1.0f, 1.0f), this only flips it one way, you have to change this to flip it back.
> 1 votes

# Answer
The setScale function overwrites the previous scale. You just need to set the scale to 1 to get the original sprite.

```
void Doodle::moveLeft()
{
    d_Sprite.setScale(-1.0f, 1.0f);
}

void Doodle::moveRight()
{
    d_Sprite.setScale(1.0f, 1.0f);
}

```
> 1 votes

---
Tags: sprites, sfml
---


# Question
Title: How do I get my scene view back to 0 or whatever it is by default?
All my tiles/sprites have 0 as their position on the Z axis, except my main cam which has -10.

For some reason I suddenly couldn't zoom in without everything disappearing, I switched to 3D view to see where I was and it seemed like I was miles away from my tiles on the z axis. I placed a sprite into my level to check and it placed itself at -57,000 on the z axis.

How do I get my scene view back to 0 or whatever it is by default?

# Answer
Select an object you want to center your view on and press the `F` key to snap your scene view camera to that object, zoomed to fit it in view. "Frame Selected" is the name of this shortcut.
> 1 votes

# Answer
In the top right (I believe that is the default), there is a section called transformation. You can change those numbers to all 0. I believe there is also an option to 'reset' as well in the transform section.
> 0 votes

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


# Question
Title: How to reset an incremental achievement in Googles Android API?
For example the achievement is "Pass 5 levels in a row without failing"

It's incremental and has five steps.

**If a user hits an obstacle, this achievements score should obviously be resetted to 0.**

How to to this? I found no such method or anything in the internet.

# Answer
You don’t. This would need to be simply a single-step achievement.
> 2 votes

---
Tags: unity, android, google-play-services
---


# Question
Title: Multiplatform game, save game state and resume it on other platform
This is for a personal and knowledge acquiring project.

I want to create a little TIC-TAC-TOE multiplatform game, app & web. The choosen technology for the app will be Android or Flutter and for the web Angular.

My doubt is, during a game if the user wants to change from the mobile version to the web version, how to resume or change the game to the web application? What would be the best way to save the game state and load it into the other platform? Having in consideration that the user will play only in one platform at a time, which is the best way to implement this restriction too?

Is this as simple and hard at the same time as implementing all controls in both platforms and storing all the data required in the database?

# Answer
If your game requires a server anyway, then the most platform-independent method is indeed to store savegames server-sided and use accounts with passwords to synchronize savegames between devices owned by the same person. Accessing the savegames on the server could be done via a webservice.
> 1 votes

---
Tags: android, mobile, savegame, cross-platform, web
---


# Question
Title: Opengl - Glsl for loop array iteration bug
I am facing a really weird bug.

On an old copy of my engine, i was doing a loop to render all the lights in my scene:

```
    for(int i = 0; i < numLights; i++){
    finalColor += ApplyLight(lights[i], diffuseColor.rgb, normal, fragPosition, surfaceToCamera,specularColor,shininess);
}

```

Which was working just fine (i had 3 lights and they were all rendering).

But now, in a newer version that includes shadows for my lights, im trying to achieve the same thing:

```
    for(int i = 0; i < numLights; i++){
        color += ApplyLighting(lights[i], frag, normal, tex);
    }

```

But this does not work!

I will explain:

Doing 1 index at a time works just fine (i = 0; i \< 1; i++) will only execute one loop and therefore, will render the single light correctly.

But as soon as there is more than 1 light to be rendered, everything is black (compiler crash i guess).

I've heard about "constant array indexing" restriction but why in the world is it working in my other shader but not on my new one?

Here are both the shaders:

**OLD**

```
#version 430

#define MAX_LIGHTS 15
uniform int numLights;

uniform struct Light{
    vec4 position;
    vec3 intensities;
    float ambientCoefficient;
    float attenuation;
    float coneAngle;
    vec3 coneDirection;
} lights[MAX_LIGHTS];

uniform float materialShininess;
uniform vec3 materialSpecularColor;

uniform vec3 cameraPosition;
uniform mat4 model;

uniform bool specularMapping;
uniform bool normalMapping;
uniform bool glossMapping;
uniform bool ambientOcclusionMapping;

uniform sampler2D diffuseTexture;
uniform sampler2D specularTexture;
uniform sampler2D normalTexture;
uniform sampler2D glossTexture;
uniform sampler2D aoTexture;

in vec2 fragTexcord;
in vec3 fragNormal;
in vec3 fragVert;

out vec4 color;

vec3 ApplyLight(Light light, vec3 diffuseColor, vec3 normal, vec3 fragPosition, vec3 surfaceToCamera, vec4 specularColor, float shininess){
    vec3 surfaceToLight;
    float attenuation = 1.0;
    float pointAttenuation = 1.0f;

    if(light.position.w == 0.0) {
        //directional light
        surfaceToLight = normalize(light.position.xyz);
        attenuation = 1.0; //no attenuation for directional lights
    } else {
        //point light
        surfaceToLight = normalize(light.position.xyz - fragPosition);
        float distanceToLight = length(light.position.xyz - fragPosition);
        attenuation = 1.0 / (1.0 + light.attenuation * pow(distanceToLight, 2));

        //cone restrictions (affects attenuation)
        float lightToSurfaceAngle = degrees(acos(dot(-surfaceToLight, normalize(light.coneDirection))));
        if(lightToSurfaceAngle > light.coneAngle){
            if(lightToSurfaceAngle - light.coneAngle < 2.5f){ //Smooth around the spotlight by 2.5 degree
                pointAttenuation = 1 / lightToSurfaceAngle;
                pointAttenuation = clamp(pointAttenuation, 0, 1);
            }else{
                attenuation = 0.0;
            }
        }else{
            pointAttenuation = (1 + 15) / lightToSurfaceAngle; //Smooth color from center
            pointAttenuation = clamp(pointAttenuation, 0, 1);
        }
    }

    //Ambient
    vec3 ambient = diffuseColor.rgb * light.ambientCoefficient * light.intensities * pointAttenuation;

    //Diffuse
    float brightness = max(0,dot(normal, surfaceToLight));
    vec3 diffuse = brightness * light.intensities * diffuseColor.rgb;

    //specular
    float specularCoefficient = 0.0f;
    float cosAngle = dot(surfaceToCamera, reflect(-surfaceToLight, normal));
    if(shininess < 255){
        if(brightness > 0.0)
            specularCoefficient = pow(max(0.0, cosAngle), shininess);
    }

    vec3 specular = specularCoefficient * materialSpecularColor * light.intensities * specularColor.rgb;

    //Attenuation relative to distance
    float distanceToLight = length(vec3(light.position.xyz) - fragPosition);

    return ambient + attenuation * (diffuse + specular);
}

void main(){
    float shininess = materialShininess;

    vec4 diffuseColor = vec4(1);
    vec4 specularColor = vec4(1);
    vec4 normalColor = vec4(1);

    diffuseColor = texture(diffuseTexture,fragTexcord); //Color on the diffuse texture

    if(ambientOcclusionMapping)
        diffuseColor *= texture(aoTexture, fragTexcord) * 1.2;

    if(specularMapping)
        specularColor = texture(specularTexture,fragTexcord); //Color on the specular texture

    if(glossMapping)
        shininess =  texture(glossTexture, fragTexcord).r;

    mat3 normalMatrix = transpose(inverse(mat3(model)));
    vec3 normal = normalize(normalMatrix * fragNormal);
    vec3 fragPosition = vec3(model * vec4(fragVert,1));

    vec3 surfaceToCamera = normalize(cameraPosition - fragPosition);

    if(normalMapping){
        normal = normalize(normalMatrix * fragNormal);
    }

    //Calculate all the lights
    vec3 finalColor = vec3(0);

    for(int i = 0; i < numLights; i++){
        finalColor += ApplyLight(lights[i], diffuseColor.rgb, normal, fragPosition, surfaceToCamera,specularColor,shininess);
    }

    //HDR (high dynamic range)
    finalColor = vec3(1.0) - exp(-finalColor * 0.8);

    //Gamma correction
    vec3 gamma = vec3(1.0/2.2);

    //Final color calculation

    //Gamma calculation : color = vec4(pow(linearColor,gamma),diffuseColor.a);

    color = vec4(finalColor,diffuseColor.a);

    if(color.a<0.1)
    {
        discard;
    }

}

```

**NEW**

```
#version 430

out vec4 FragColor;

#define MAX_LIGHTS 15
uniform int numLights;

in VS_OUT {
    vec3 FragPos;
    vec3 Normal;
    vec2 TexCoords;
} fs_in;

uniform sampler2D diffuseTexture;

uniform struct Light{
    int lightType;
    vec4 position;
    vec3 intensities;
    float ambientCoefficient;
    float attenuation;
    float coneAngle;
    vec3 coneDirection;
    float far_plane;
    sampler2D shadowMap;
    samplerCube depthMap;
    mat4 lightMatrix;
} lights[MAX_LIGHTS];

uniform vec3 viewPos;

float ShadowCalculation(Light light, vec3 fragPos)
{
    // Get vector between fragment position and light position
    vec3 fragToLight = fragPos - light.position.xyz;

    // Use the light to fragment vector to sample from the depth map
    float closestDepth = texture(light.depthMap, fragToLight).r;

    // It is currently in linear range between [0,1]. Re-transform back to original value
    closestDepth *= light.far_plane;

    // Now get current linear depth as the length between the fragment and light position
    float currentDepth = length(fragToLight);

    // Now test for shadows
    float bias = 0.15;
    float shadow = currentDepth -  bias > closestDepth ? 1.0 : 0.0;

    return shadow;
}

vec3 ApplyLighting(Light light, vec3 FragPosition, vec3 norm, vec2 texCoords){
    vec3 color = texture(diffuseTexture, texCoords).rgb;
    vec3 normal = normalize(norm);
    vec3 lightColor = vec3(1.0);

    // Ambient
    vec3 ambient = 0.1 * color;

    // Diffuse
    vec3 lightDir = normalize(vec3(light.position) - FragPosition);
    float diff = max(dot(lightDir, normal), 0.0);
    vec3 diffuse = diff * lightColor;

    // Specular
    vec3 viewDir = normalize(viewPos - FragPosition);
    vec3 reflectDir = reflect(-lightDir, normal);
    float spec = 0.0;
    vec3 halfwayDir = normalize(lightDir + viewDir);
    spec = pow(max(dot(normal, halfwayDir), 0.0), 64.0);
    vec3 specular = spec * lightColor;

    // Calculate shadow
    float shadow = ShadowCalculation(light, FragPosition);
    //shadow = 0;

    vec3 lighting = (ambient + (1.0 - shadow ) * (diffuse + specular)) * color;

    return lighting;
}

void main()
{
    vec3 color = vec3(0);

    vec3 frag = fs_in.FragPos;
    vec3 normal = fs_in.Normal;
    vec2 tex = fs_in.TexCoords;

    for(int i = 0; i < numLights; i++){
        color += ApplyLighting(lights[i], frag, normal, tex);
    }

    //color = ApplyLighting(lights[0], fs_in.FragPos, fs_in.Normal, fs_in.TexCoords);
    //color += ApplyLighting(lights[1], fs_in.FragPos, fs_in.Normal, fs_in.TexCoords);

    //FragColor = vec4(numLights*0,numLights*255,0,1);

    //else
    FragColor = vec4(color, 1.0f);

}

```

As i said, the old one works perfectly fine (dont know why!).

I also noticed that if i set my MAX\_LIGHTS define (on the new shader) to exactly the amount of light being used (2 in this case), it works!

But as soon as i set the size of define to (numLights+1), it doesnt work!

Any idea?

# Answer
Make sure that you correctly set the "numLights" uniform on the CPU side.

To get further help, you should post your CPU code (glUniforms, glUseProgram, glDraw...).
> 1 votes

# Answer
The problem lies within the shader, a lot of implementations don't allow for dynamic looping in GLSL, therefore numLights, when used in "i \< numLights" is being evaluated as zero, an easy way to fix it would be to use a constant number, another could be to use SSBOs or something like that, not sure if that would work either.
> 0 votes

---
Tags: opengl, shaders, glsl
---


title: Unity: RigidBody2D, Trying to Set rb;

text:
# Question
Title: Unity: RigidBody2D, Trying to Set rb;
So for Unity I've been trying to to do the code line `public RigidBody2D rb;` I've followed the gmetrix unity programming course and they do that just fine with the unity set up code and just this. This then allows them to put the object ubsprite that I and them called player inside the c# program for player. However for me the error CS0246 comes up. I've looked up similar situations and haven't found a fix for mine.

## Complete Code

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

public class Player : MonoBehaviour

{
    public RigidBody2D rb;//RigidBody Slot

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
}

```

For them RigidBody2D lights up blue however for me it does not and I won't get to be able to add the sprite gameobject into the code slot for it.

Edit: Sorry noticed there are actually a couple of error messages. Hope this image helps from console.

Also to the comment I recieved about the video if I can upload it sadly this course is not publicically available its the simple course for Unity programming however it still provides a certificate and is associated with unity so it is a pay for course or if you are a student teachers can get course keys. It is the gmetrix course associated with unity and certiport for those who wanna know still.

Edit 2: An answer was provided for fixing the error CS0246, however the other 2 errors are still present.

# Answer
> 0 votes
I found the issue! I was looking into the error messages and found a similar post on the unity forums.

--https://forum.unity.com/threads/visual-studio-tools-tab-dont-show-and-cant-attach-to-unity.365416/

One of the people said that there are issues if you have multiple versions of unity or multiple versions of visual studios. I found a few things about this. First some computers already have visual studios installed so you may not need to download visual studio, or if you're upgrading then you need to uninstall the older versions first. Second Unity has an option to download visual studios with it so you don't need to download it if you already have it. It seems that with my computer I had a dozen versions of visual studios. There were was all from 2012-2017 in 32 and 64 bit form. Meaning I had 12 different visual studios installed + 1 more since I had unity download one before. So a total of 13. Anyways I've used stackexchange before and I believe you have to wait 24 hours before you can click your own answer as an answer for your own question so please wait to knock me down tell then.

# Answer
> 1 votes
It's spelled `Rigidbody2D`, not `RigidBody2D`. Capitalization matters in C#.

---
Tags: unity, c#, sprites, rigidbody
---


# Question
Title: Moving my character/camera makes environnement jerky
I'm learning to make a Tilebased game with Unity and for that I use the Zelda alttp assets. I just have Tiles, a Camera and a moving Character with a rigidbody2D and a CircleCollider.

When the Camera follows the Character, the scene feels Jerky.

Info:

* The Camera uses the 2D Pixel Perfect package.
* The Character is moving via Rigidbody2D.MovePosition() in the `FixedUpdate` Method:

code:

```
void Update()
{
    float yInput;
    float xInput;

    #region yMovement
    if (Input.GetKey(keyMoveTop))
    {
        if (Input.GetKey(keyMoveBot))
        {
            yInput = 0f;
        }
        else yInput = 1f;
    }
    else if (Input.GetKey(keyMoveBot))
    {
        yInput = -1f;
    }
    else yInput = 0f;
    #endregion

    #region xMovement
    if (Input.GetKey(keyMoveLeft))
    {
        if (Input.GetKey(keyMoveRight))
        {
            xInput = 0f;
        }
        else xInput = -1f;
    }
    else if (Input.GetKey(keyMoveRight))
    {
        xInput = 1f;
    }
    else xInput = 0f;
    #endregion

    //Walking
    isWalking = Input.GetKey(keyMoveWalk);
    moveDirection = Vector2.ClampMagnitude(transform.right * xInput + transform.up * yInput, 1f);
}

private void FixedUpdate()
{
    _rb.MovePosition(_rb.position + moveDirection * (isWalking ? walkSpeed : runSpeed) * Time.fixedDeltaTime);
}

```

You can see the problem here: https://youtu.be/MA2zZPME5X4

Edit: Added all my movement code

# Answer
> 1 votes
Cameras are ***very sensible*** to anything that does not move them perfectly smoothly. The camera should be updated in an Update or LateUpdate. One way to handle cameras is to adjust variables in a FixedUpdate, and to move the camera in the (Late)Update based on the given variables. Moving the player in a FixedUpdate with the camera being parented to will cause flickering.

The reason why is because FixedUpdate does not align with the frame rate. Update and LateUpdate however do, which is why these are the ideal moments to move your camera.

Many people like to attach their cameras to the player, but I'd discourage from doing so. Cameras should have their own, controlled moving patterns unrelated to the arbitrary movements of the player, otherwise you risk all sorts of flickering issues like this including a loss of camera quality in general.

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


# Question
Title: Programming Test for a job in Game Dev - expected levels of documentation etc
If this is the wrong place to be asking this - please let me know and I'll happily ask it somewhere else!

I am completing a C++ Proficiency test for a "Junior Engine Programmer" role at a game studio in the UK. The test involves creating a pathfinding demo and rendering it to the screen. I won't go too into the details of the test, but the brief doesn't mention any documentation or unit testing etc.

I've been told by a lecturer I should definitely include both of those, despite not being asked, and by another that I should use my time more wisely to make a great implementation. What is the done thing here? The only thing close that the brief mentions is making clear where I've used other libraries.

Is there anything else I should consider submitting with the implementation as well? Thinking of technical specification such as class diagrams etc, or anything really.

Thanks!

# Answer
> 2 votes
I'm sorry, but we can not answer this question for the general case, because interviewers are not all the same. People who make hiring decisions are all individuals who apply their own personal judgment systems and expect very different things. While one person might be impressed by the extra length you went to, another might wonder why you are wasting your and their time by adding stuff they never asked for.

What you can try, is to do some research to find out what they are likely looking for:

* Read the job offering description, test instructions and other information provided to applicants very carefully. Read between the lines to find out what kind of person they are looking for. Do they want someone who can follow instructions? Or someone with the initiative to do their own thing?
* Try to find out how they are working internally. Do they have any development blogs describing their development processes? Did people from that company talk about them at conventions like GDC? (by the way, if you do get to the personal interview stage, then showing you did your homework about the company you applied to will almost always earn you a couple extra points)
* Are they a large or a small company? Large companies tend to have very standardized application processes with very formalized rating systems. These simply don't leave room to take any additional work into account, so it's often futile to try to score that way. Smaller companies often tend to look at applications a lot more subjectively and might be impressed by applicants who do things which set them apart from the rest. But this is not a hard rule either.
* Just ask them back whether or not they would want to see supplemental material like that together with your test submission.

If this doesn't give you any pointers, then the best thing you can do is think about what course of action does best represent *you* and the way *you* want to work.

---
Tags: c++, game-design, jobs
---


# Question
Title: Render a sphere when the user clicks on the screen with libgdx
I’m really new to Libgdx, and decided to try out some codes to familiarise myself with it. I’m trying to write a program such that a sphere is rendered at the position of the user’s click.

Here’s my code:

```
package com.mygdx.game;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.graphics.FPSLogger;

public class Render implements ApplicationListener {
    public Environment environment;
    public PerspectiveCamera cam;
    public CameraInputController camController;
    public ModelBatch modelBatch;
    private FPSLogger fps;

    public Model model;

    @Override
    public void create() {
        Gdx.graphics.setContinuousRendering(false);

        environment = new Environment();
        environment.set(new ColorAttribute(ColorAttribute.Specular, 0.4f, 0.4f, 0.4f, 0.6f));
        environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, 0f, 0f, -1f));

        modelBatch = new ModelBatch();

        cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        cam.position.set(0f, 0f, 10f);
        cam.lookAt(0,0,0);
        cam.near = 1f;
        cam.far = 300f;
        cam.update();

        ModelBuilder modelBuilder = new ModelBuilder();
        model = modelBuilder.createSphere(1f, 1f, 1f, 30, 30,
                new Material(), Usage.Position | Usage.Normal)
        camController = new CameraInputController(cam);
        Gdx.input.setInputProcessor(camController);
        fps = new FPSLogger();
    }

    @Override
    public void render() {

        if (Gdx.input.justTouched()){
            ModelInstance Instance = new ModelInstance (model);
             Instance.transform.setToTranslation(Gdx.input.getX(),Gdx.input.getY(), 0);
            DataBase.array.add(Instance);
            Gdx.graphics.requestRendering();
        }
        camController.update();

        Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

        modelBatch.begin(cam);
        for (ModelInstance instance: DataBase.array) {
            modelBatch.render(instance, environment);
        }
        modelBatch.end();

        //fps.log();
    }

    @Override
    public void dispose() {
        modelBatch.dispose();
        model.dispose();
    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }
}

```

The DataBase.array is simply an ArrayList.

What am I doing wrong? Any help would be really appreciated; thanks!

# Answer
I see few mistakes in your code :

```
environment.set(new ColorAttribute(ColorAttribute.Specular, 0.4f, 0.4f, 0.4f, 0.6f));

```

It has no effect since specular should only used with materials. Maybe you wanted ambiant light. Then replace it by ColorAttribute.AmbientLight.

The main problem in your case is coordinates conversion from screen space to world space. What you can do is :

```
// get screen space Z from world space zero
float z = cam.project(new Vector3(0,0,0)).z;
// get world space position from screen space pointer
Vector3 v = cam.unproject(new Vector3(Gdx.input.getX(),Gdx.input.getY(), z));
// set your model position in world space
Instance.transform.setToTranslation(v.x, v.y, v.z);

```
> 0 votes

---
Tags: libgdx
---


# Question
Title: Explicit difficulty selection without breaking the game flow
According to the flow theory, in short, if the challenge is too hard, from flow state the player will go into an anxiety state, and if the challenge is too easy, he will go into a boredom state. This is fixed with dynamic difficulty, where a system tracks the player's performance and adjusts the difficulty.

But what about explicit difficulty selection which is often seen in shooters (Easy, Medium, Hard)? With such predefined difficulties, the challenge will always be either too easy or too hard, won't it? Therefore we cannot achieve a flow state, and following that, an immersion into the game is less likely. How do we fix this?

# Answer
> 3 votes
> How do we fix this?

I'm not sure there is anything to fix, but if you really want an answer:

You make *good* difficulty levels.

Not all players want to have a dynamic difficulty level, and not all games would allow such a feature (not to mention that it could be much harder to get right).

You have to identify the challenge the player wants to face. For instance, in a shooter game, some players will want to enjoy the story mode and, while they could be good at it shooting and hiding, don't want to spend too much energy on the actual gameplay elements. Others will want very much the completion achievements offered by the higher difficulty levels, even if their skill as a player is of the lower difficulty level. In all of these examples, the player will probably in flow state.

# Answer
> 3 votes
A dynamic difficulty system has the purpose to adjust to challenge of the game to the skill level of the player. But you can use the difficulty setting chosen by the player as a guide for the level of relative challenge the dynamic difficulty should aim for.

* On "Hard", make it adjust in a way that the player is always slightly overburdened to keep them in a constant state of slight anxiety. Train your dynamic difficulty to make the player suffer, but not beyond their capabilities.
* On "Easy", make sure that the player is always slightly underburdened, to keep them in a constant state of relaxation (I would not call it "boredom"). Train your dynamic difficulty to make the player prosper, but not without providing no challenges at all.
* On "Normal", look for a balance to ensure the optimal flow of the game.

# Answer
> 2 votes
Avoid having big dips or spikes in difficulty, and make it so easy challenges can be beaten faster by being more reckless.

If you have big dips and spikes in difficulty, like a bunch of easy fights followed by a difficult boss, then any player will either be bored by the easy fights or find the boss frustratingly difficult. But if the fights before the boss are nearly as hard as the boss, there will be some people for whom the whole experience is pleasantly intense for a flow state. (keeping in mind that you can have intentional periods of less difficulty, like possibly some time to explore and take in the scenery, to pace the game and avoid fatigue)

If playing fast is more challenging than playing slow, but also results in faster progress, players can self-regulate their own challenge to hit that flow state, like dynamic difficulty but perhaps not as condescending. The trick is to make it so playing faster is the right amount more rewarding: if you're not careful, a player could find that they make more progress by banging their head against the wall (metaphorically) and dying constantly than by playing at the speed that they'd actually enjoy the most.

# Answer
> 2 votes
## Difficulty curve

How a game difficulty changes over time is commonly called a "difficulty curve", which you can probably find some more resources about online.

The basic idea is the game should get more difficult over time as the player gets more comfortable with the mechanics to constantly keep the game challenging.

**This doesn't have to be dynamic difficulty.** One can design levels by hand such that one is more difficult than the next. This may, in fact, often be easier than trying to adjust difficulty purely dynamically. Designing a game such that you can basically have a slider of difficulty at any point in time is not trivial.

Difficulty selection adjusts this for variance in general player skill and in what players are looking for in the game (a challenge or something relaxing). Although not all games have this (or dynamic difficulty).

Reference (with slightly modification).

## Difficulty dips

Many games have occasional dips in challenge after bosses or at other points in the game.

These dips allow players to enjoy their victory and give them a break to prevent exhaustion.

Reference.

## Allow players to change difficulty

One player may be better than another, so their Easy mode may be another player's Hard mode. They also wouldn't be equally good in every game. This could make it difficult for players to accurately pick the "correct" difficulty for them.

They may also learn new skills faster or slower than other players, meaning a fixed difficulty curve wouldn't always work so well.

Dynamic difficulty is one way to deal with the above problems, but another way would be to simply allow players to change the difficulty throughout the game.

This may not work so well in games where you unlock one difficulty after the other (although I'm not a big supporter of that).

One should also be careful about allowing players to trivialise a part of the game that's *supposed* to be challenging. Of course you don't want them to be stuck there too long, but having them drop the difficulty right after the first failed attempt would remove most of the reward from overcoming the challenge. This could make your game a whole lot less fun.

You could wait until they've failed a few times before giving them the option of dropping the difficulty (or automatically drop it until they finish that part).

You could alternatively require them to restart the level or chapter or whatever if they want to change difficulty. This would add an additional (minor) barrier to make changing the difficulty less appealing, so they'd be more inclined to try to get past the challenge instead.

## Start off easy or hard?

A significant part of the challenge of a game could be getting used to the mechanics.

You could be thrown right into the action with little to no time to get used to everything. Too much of this would alienate inexperienced players.

You could alternatively be slowly introduced to the mechanics of the game. Too much of this would alienate experienced players.

This is a balancing act, but there is a bit of lenience here. Most players expect some time to adjust to the mechanics and experienced players expect the introduction to be a bit slower than they'd like.

The tutorial could also be optional. Although you shouldn't expect players to have mastered something immediately following the tutorial.

This also applies to new abilities and enemies.

## New abilities or weapons

Unlocking new abilities as the game progresses would make the game easier, but you should also make these abilities be required in subsequent parts of the game.

This could:

* Make things more challenging by requiring players to master the new abilities.
* Keep the game varied enough to remain fun (even if it doesn't change the difficulty)
* Make things more challenging by adding the complexity of having to pick between or chain different abilities.

This can very clearly be seen in many platformers:

Perhaps you start off only being able to (or needing to) jump. The very first level is trivial with only one small gap to jump over. Subsequent levels require better and better jumps. After a while you may unlock a new ability like double-jump or wall-jump. The first level after unlocking this ability is typically fairly straight-forward and subsequent levels get harder. This repeats until the end of the game.

## New enemies or environments

This is very similar to the above point, and similarly requires mastery and adds variety and complexity.

In the beginning there often aren't many different types of enemies, environment types or hazards. More of these are unlocked as the game progresses.

## Making it seem like it was closer than it was

Some games:

* ignore the first hit that would kill you
* make you think you have less health than you actually have
* make you stronger if you're on lower health
* or even briefly make you invulnerable if you're close to death

This gives players the feeling of barely surviving more often, which makes the game more exciting and feel more challenging.

It can also create a bigger buffer for whether a player would find a difficulty too easy or too difficult, since better players could feel challenged even if they're still quite far from *actually* dying. A bigger buffer makes different difficulties (and dynamic difficulty) easier to balance.

Related video on The Game Theorists (this also talks about dynamic difficulty).

## Combine difficulty selection with dynamic difficulty

Players could be looking for:

* Something relaxing
* A challenge
* A good middle-ground between the two

Dynamic difficulty by itself can't really provide all three of these in one.

Difficulty selection does allow players to pick this, but variations in player skill and learning rate may make this less than ideal.

Combining difficult selection with dynamic difficulty allows players to pick what sort of challenge they're looking for, and have the difficulty adjust accordingly.

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


# Question
Title: Why code reflection became a must in game engines?
I'm currently doing some research on programming languages(compile time reflection area, if you ask) and I found that on the game engine area the reflection feature becomes a must, an engine either uses a language which has reflection feature itself(for example uses C#), or implements it for non-reflection languages(for example both UE and CryEngine implement reflection mechanisms for C++).

I'm not a game developer, so I have no experiences on game developing and not familiar with engines, so can anyone tell me in what case the reflection becomes a must? And what's more, does reflection used only in development phase or also used in released production?

# Answer
It allows to expose variables and functions to be used in the editor. That is, the game creation tool will use a form of reflection (or similar) on the code provided by the developers, which then allows it to expose parts of it in editors for designers.

For example, let us say a developer has created a class of objects (created as source code) to be placed in game by the level designers. However, there are some properties the developer wants to allow the designer to tweak. To do this, the tool will have to expose these properties to the level designer in the editor.

Similarly, functions/methods could be exposed. Which may allow to use them in scripting (including visual scripting, for example “blueprints”) or even allow to call them from an in-game debug console.

---

Since the editor cannot know the type information before hand (the editor was created before the game). Instead the editor will need a manifest with this information. To get this manifest, the editor (uses a tool that) generates it, either directly from the source (this could be part of the built process) or from a binary. The developer might have to mark what to expose.

---

*This is similar to how Visual Studio form designer shows you a property panel where you can edit the properties of the controls you place... and that the controls had been built beforehand.*

---

See also Unreal Property System (Reflection).

---

We might also find reflection and emission to generate bindings for different languages. That is, the engine has main supported language, yet the developers of the engine want to provide the ability to write code for the engine in other languages... if they are not integrating a compiler for those languages, then they need an SDK for those languages. Well, they can generate code for those languages by doing reflection on their API and emitting the SDK interop code. Add this to continuous integration, and this ensures that the SDK code is always up to date.

Yet another place where we might find reflection is when loading plugins or mods.
> 66 votes

---
Tags: code-reflection
---


# Question
Title: Null reference on gameObject that has been successfully referenced
It's exactly as the title says. I am getting a null reference error even though I have properly referenced the object. I have debugged my code to show that the result is always exactly what I need however whenever put into practical use, the code returns an error.

```
                if(hit == true && canSee.transform.CompareTag("Unit"))
                {
                    //var Obehaviour = other.gameObject.transform.parent.gameObject.GetComponent<UnitBehaviour>().Health; <--- Error is here.
                    float Health = other.gameObject.transform.parent.gameObject.GetComponent<UnitBehaviour>().Health;
                    float fullHealth = other.gameObject.transform.parent.gameObject.GetComponent<UnitBehaviour>().MaxHealth;
                    //Debug.Log("Object " + other.gameObject.transform.parent.gameObject);
                    //Debug.Log("Component and name " + Obehaviour.Name);
                    ReferenceScript.GetComponent<UnitBehaviour>(other.gameObject.transform.parent.gameObject);
                    if(Health < fullHealth)
                    {
                        if(fullHealth - Health < Ubehaviour.supplies)
                        {
                            Health += Ubehaviour.supplyTransferRate;
                            Health = Mathf.Clamp(Health, 0, fullHealth);
                            other.gameObject.transform.parent.gameObject.GetComponent<UnitBehaviour>().UpdateHealth();
                            Ubehaviour.supplies -= Ubehaviour.supplyTransferRate;
                            Ubehaviour.supplies = Mathf.Clamp(Ubehaviour.Health, 0, Ubehaviour.maxSupplies);
                            Ubehaviour.LoseSupplies();
                        }
                        else
                        {
                            return;
                        }

                    }
                }

```

As shown in the code above, I have tried to get the values I need by storing them in variables other than caching the entire class. But this also didn't work. What could be wrong? The debugs below work perfectly as well.

# Answer
```
var Obehaviour = other.gameObject.transform.parent.gameObject.GetComponent<UnitBehaviour>().Health; <--- Error is here.

```

There are 3 reasons why this line could throw a NRE:

* `other` is null
* `other` doesn't have a parent
* the parent gameObject doesn't have a `UnitBehaviour`

Keep in mind that when you put this code snippet into some event handler (I suspect you have it in some OnTrigger\* or OnCollision\* method) then it might get triggered by an object you weren't expecting. It's always dangerous to have long chains of dereferentiations without any checks in between if one of them returns a `null` value.

If I was to debug this problem in my own code, I would break it up into individual lines so I can see which dereferentiation actually fails:

```
GameObject otherGameObject = other.gameObject;
Transform otherParent = otherGameObject.transform.parent;
UnitBehaviour parentUnitBehaviour = otherParent.gameObject.GetComponent<UnitBehaviour>();
var Obehaviour = parentUnitBehaviour.Health;

```

Another thing you can do is to wrap the whole code section into a `try { ... } catch NullReferenceException e { ...}` block and set a debugger breakpoint in the `catch` block. When the breakpoint triggers, you can examine what exactly you got in `other`. You might be in for a surprise.
> 1 votes

---
Tags: unity, gameobject, game-component
---


title: One DeviceContext per Material?

text:
# Question
Title: One DeviceContext per Material?
In D3D11, we have a DeviceContext, which represents the Renderpipeline.

In Metal, we have a RenderPipelineState. In Metal, I cache the RenderPipelineState, it is the abstraction of a "material".

Is DeviceContext in D3D11 the same? I.e. 1 DeviceContext = "1 Material" or do I set the DeviceContext (BlendState,DepthState) whenever the Material changes? My idea was to have a Material Class which holds a pointer to a DeviceContext and whenever i want to draw this material, i execute Draw\*() on this context.

# Answer
A device context is just an interface that allows you to issue commands to the GPU. It doesn't hold any internal state, and therefore it doesn't represent any 'RenderPipelineState'. Moreover, looking at https://docs.microsoft.com/en-us/windows/win32/direct3d11/overviews-direct3d-11-devices-intro (and other tutorial), it appears that the only use of multiple context is with multithreading (where each thread has its own context, immediate or deferred).

What you can do is (as once I did), build your own RenderPipelineState, which holds pointers to the resources needed (shaders, textures, ...) and has the method "set" (or draw). On top of this I'd build a RenderPipelineStateManager which holds pointers/id of the current resources active at a given time, in this way you can check wherever you actually need to set that resource or not (reducing overhead) as, if I rembember correctly, is not done DirectX side (e.g. if your current vertex shader is VS\_1 and in your next material you still use VS\_1 and call context-\>VSSetShader(VS\_1) it will result in a driver call to change the shader as if it was a new one).

Something like this:

```
class RenderPipelineState {
    VShader* _vs;
    PShader* _ps;
    BlendState* _bs;
    ...
}

class RenderPipelineStateManager {
    Context* _ctx;
    VShader* _ActiveVs;
    PShader* _ActivePs;
    BlendState* _ActiveBs;
    ...

    void set(RenderPipelineState* _rps) {
        if (_rps->_vs != _ActiveVs) {
            _ctx->VSSetShader(_rps->_vs);
            _ActiveVs = _rps->_vs;
        }
        ...
    }
}

class Material {
    RenderPipelineState* _material;

    void apply(RenderPipelineStateManager* _mng) {
        _mng->set(_material);
    }
}

```
> 2 votes

---
Tags: directx11, metal
---


# Question
Title: The children of a Transform are in reverse order
I am making a simple 4-player turn-based card game. At one point, a player can "open" his hand on the table. As the player does this, I want cards to be aligned in a way such that left side of each one is visible.

In my hand, the cards look like this.

When I carry them on the table, they look like this

Not only the order is reversed, which I wouldn't mind, but also the cards are not visible now.

This is how the green area looks like in the Inspector

I don't want cards to change shape to fill the area, and I also don't want them to go outside the green area.

When I unselect `Control Child Size`, the cards are aligned just as I want, but now they are too spread out and outside the green area.

Is there a way to achieve the behavior that I want?

# Answer
> 0 votes
The problem with the configuration is the negative spacing. The negative spacing exceeds the width of a card, and the card slides all the way back to the left side as a result.

To fix it, the spacing should be set to a value which is greater than -50 units.

---
Tags: unity
---


title: VAO not showing

text:
# Question
Title: VAO not showing
My VAO is simply not showing up and i'm not sure if my matrices are wrong or if the shader is wrong… Please have a look a see what is wrong… My code is big so i'll post the essential.

```
Matrix4 Matrix4::LookAt(Vector3 eye, Vector3 target, Vector3 up)
{
    Vector3 z = Vector3::Normalize(eye - target);
    Vector3 x = Vector3::Normalize(Vector3::Cross(up, z));
    Vector3 y = Vector3::Normalize(Vector3::Cross(z, x));

    Matrix4 result;

    result.row0.x = x.x;
    result.row0.y = y.x;
    result.row0.z = z.x;
    result.row0.w = 0;
    result.row1.x = x.y;
    result.row1.y = y.y;
    result.row1.z = z.y;
    result.row1.w = 0;
    result.row2.x = x.z;
    result.row2.y = y.z;
    result.row2.z = z.z;
    result.row2.w = 0;
    result.row3.x = -((x.x * eye.x) + (x.y * eye.y) + (x.z * eye.z));
    result.row3.y = -((y.x * eye.x) + (y.y * eye.y) + (y.z * eye.z));
    result.row3.z = -((z.x * eye.x) + (z.y * eye.y) + (z.z * eye.z));
    result.row3.w = 1;

    return result;
}

Matrix4 Matrix4::CreatePerspectiveOffCenter(
float left, float right, float bottom, float top,
float near, float far)
{
    float x = 2.0f * near / (right - left);
    float y = 2.0f * near / (top - bottom);
    float a = (right + left) / (right - left);
    float b = (top + bottom) / (top - bottom);
    float c = -(far + near) / (far - near);
    float d = -(2.0f * far * near) / (far - near);

   Matrix4 result;

   result.row0.x = x;
   result.row0.y = 0;
   result.row0.z = 0;
   result.row0.w = 0;
   result.row1.x = 0;
   result.row1.y = y;
   result.row1.z = 0;
   result.row1.w = 0;
   result.row2.x = a;
   result.row2.y = b;
   result.row2.z = c;
   result.row2.w = -1;
   result.row3.x = 0;
   result.row3.y = 0;
   result.row3.z = d;
   result.row3.w = 0;

   return result;
}

Matrix4 Matrix4::CreatePerspectiveFieldOfView(
float fovy, float aspect,
float near, float far)
{
float maxY = near * tanf(0.5f * fovy);
float minY = -maxY;
float minX = minY * aspect;
float maxX = maxY * aspect;

return CreatePerspectiveOffCenter(
    minX, maxX, minY, maxY, near, far);
}

Matrix4 Matrix4::CreateTranslation(Vector3 position)
{
    Matrix4 result = Matrix4::Identity();
    result.row3.x = position.x;
    result.row3.y = position.y;
    result.row3.z = position.z;
    return result;
}

GLfloat* Matrix4::ToGlArray()
{
    GLfloat result[16] =
    {
        row0.x, row0.y, row0.z, row0.w,
        row1.x, row1.y, row1.z, row1.w,
        row2.x, row2.y, row2.z, row2.w,
        row3.x, row3.y, row3.z, row3.w,
    };
    return result;
}

```

This is How I'm setting up the shader matrices

```
void MeshRenderer::Render(Shader* shader)
{
    glProgramUniformMatrix4fv(
        shader->GetID(),
        shader->GetUniformLocation("model"),
        1, GL_TRUE,
        GetGameObject()->GetTransform()->
        GetTransformation().ToGlArray());

        mesh->Render(shader);
}

void Camera::Render(Shader *shader)
{

glClearColor(
        backgroundColor.GetR(),
    backgroundColor.GetG(),
    backgroundColor.GetB(),
    backgroundColor.GetA());

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glLoadIdentity();

float aspect = (float)Screen::GetWidth() / (float)Screen::GetHeight();

projection = Matrix4::CreatePerspectiveFieldOfView(
    60 * Mathf::DegreesToRadians(),
    aspect,
    near, far);

view = Matrix4::LookAt(
    GetGameObject()->GetTransform()->GetPosition(),
    GetGameObject()->GetTransform()->GetPosition() +
    GetGameObject()->GetTransform()->GetForward(),
    GetGameObject()->GetTransform()->GetUp());

glProgramUniformMatrix4fv(
    shader->GetID(),
    shader->GetUniformLocation("view"),
    1, GL_TRUE, view.ToGlArray());

glProgramUniformMatrix4fv(
    shader->GetID(),
    shader->GetUniformLocation("projection"),
    1, GL_TRUE, projection.ToGlArray());
}

```

Here is my vertex shader

```
#version 330 core

layout (location = 0) in vec3 position;
layout (location = 1) in vec2 texCoords;
layout (location = 2) in vec3 normals;

out vec2 TexCoords;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main()
{
    gl_Position = model * view * projection * vec4(position, 1.0);
    TexCoords = texCoords;
}

```

This is how I'm setting the vao etc...

```
void Mesh::Entry::SetupEntry()
{
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);

glGenBuffers(1, &VBO1);
glBindBuffer(GL_ARRAY_BUFFER, VBO1);
glBufferData(
    GL_ARRAY_BUFFER,
    sizeof(float) * vertices.size(),
    &this->vertices[0],
    GL_STATIC_DRAW);
glVertexAttribPointer(
    0, 3,
    GL_FLOAT, GL_FALSE,
    sizeof(float) * 3, NULL);
glEnableVertexAttribArray(0);

glGenBuffers(1, &VBO2);
glBindBuffer(GL_ARRAY_BUFFER, VBO2);
glBufferData(
    GL_ARRAY_BUFFER,
    sizeof(float) * uvs.size(),
    &this->uvs[0], GL_STATIC_DRAW);
glVertexAttribPointer(
    1, 2, GL_FLOAT,
    GL_FALSE, sizeof(float) * 2,
    NULL);
glEnableVertexAttribArray(1);

glGenBuffers(1, &VBO3);
glBindBuffer(GL_ARRAY_BUFFER, VBO3);
glBufferData(
    GL_ARRAY_BUFFER,
    sizeof(float) * normals.size(),
    &this->normals[0], GL_STATIC_DRAW);
glVertexAttribPointer(
    2, 3,
    GL_FLOAT, GL_FALSE,
    sizeof(float) * 3,
    NULL);
glEnableVertexAttribArray(2);

glGenBuffers(1, &VBO4);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, VBO4);
glBufferData(
    GL_ELEMENT_ARRAY_BUFFER,
    sizeof(unsigned int) * indices.size(),
    &this->indices[0],
    GL_STATIC_DRAW);

glBindVertexArray(0);
}

```

EIDT :

```
void Mesh::Entry::Render(Shader *shader)
{
glBindVertexArray(VAO);
glDrawElements(
    GL_TRIANGLES,
    indices.size(),
    GL_UNSIGNED_INT,
    (void*)0);
glBindVertexArray(0);
}

```

# Answer
So as Daniel\_1985 pointed out the function was returning an array that was getting out of scope.

So I've changed my method to this:

```
GLfloat* Matrix4::ToGlArray()
{
    GLfloat* result = new GLfloat[16]
    {
        row0.x, row0.y, row0.z, row0.w,
        row1.x, row1.y, row1.z, row1.w,
        row2.x, row2.y, row2.z, row2.w,
        row3.x, row3.y, row3.z, row3.w,
    };
    return result;
}

```

EDIT :

For anyone having the same problem the method above is alocating to the heap which a delete cal is necessary. If you don't want to deal with that and possibly have leaks there is a better solution for this:

Matrix4.h

```
static void ValuePointer(Matrix4 mat, GLfloat* array);

```

Matrix4.cpp

```
void Matrix4::ValuePointer(Matrix4 mat, GLfloat* array)
{
    array[0] = mat.M11(); array[1] = mat.M12();
    array[2] = mat.M13(); array[3] = mat.M14();
    array[4] = mat.M21(); array[5] = mat.M22();
    array[6] = mat.M23(); array[7] = mat.M24();
    array[8] = mat.M31(); array[9] = mat.M32();
    array[10] = mat.M33(); array[11] = mat.M34();
    array[12] = mat.M41(); array[13] = mat.M42();
    array[14] = mat.M43(); array[15] = mat.M44();
}

```

And should be used like this :

```
void MeshRenderer::Render(Shader* shader)
{
    GLfloat array[16];
    Matrix4::ValuePointer(
        GetGameObject()->GetTransform()->
        GetTransformation(), array);

    glProgramUniformMatrix4fv(
        shader->GetID(),
        shader->GetUniformLocation("model"),
        1, GL_FALSE,
        array);

    mesh->Render(shader);
}

```
> 1 votes

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


# Question
Title: What's wrong with my line segment plane intersection code?
I'm following the algorithm on on this website for my line segment intersection test code. But when looking at my line segment and plane intersect it doesn't produce the correct point of intersection.

Here is an example of what I'm talking about.

Here is my code for the test

```
public static bool SegmentPlane(Vector3 p1, Vector3 p2, float distance, Vector3 normal, out float time, out Vector3 point)
{
    time = 1f;
    point = Vector3.zero;

    time = (Vector3.Dot(normal, normal * distance) - Vector3.Dot(normal, p1)) / Vector3.Dot(normal, (p2 - p1).normalized);
    if(time >= 0f && time <= 1f)
    {
        point = p1 + time * (p2 - p1).normalized;
        return true;
    }
    return false;
}

```

Display Code

```
public void OnDrawGizmos()
{
    plane = new Plane(transform.forward, transform.position);

    colliding = CollisionLibrary.SegmentPlane(p1.position,p2.position,Vector3.Distance(Vector3.zero,transform.position),transform.up,out time,out point);

    if (!colliding)
        Gizmos.color = Color.yellow;
    else
        Gizmos.color = Color.red;

    Gizmos.DrawLine(p1.position, p2.position);
    Gizmos.DrawSphere(point, .1f);

    Gizmos.color = Color.white;
    Gizmos.DrawLine(transform.position, transform.position+transform.up * 100);

}

```

# Answer
> 0 votes
Looking at the code you referenced in your link, and the code you wrote, I'm not sure how you came up with that to be honest... Especially the time variable which doesn't exist in the example you posted and what you do to calculate it isn't in the example you posted either... So I'm wondering whether I'm understanding your question correctly or whether you actually want to do something else.

But in case you actually wanted to implement the intersect3D\_SegmentPlane function in your example, below is how you could do that in Unity3D.

```
bool SegmentPlane(Vector3 p0, Vector3 p1, Vector3 planeCenter, Vector3 planeNormal, out Vector3 I)
{
    I = Vector3.zero;

    Vector3 u = p1 - p0;
    Vector3 w = p0 - planeCenter;

    float D = Vector3.Dot(planeNormal, u);
    float N = -Vector3.Dot(planeNormal, w);

    if (Mathf.Abs(D) < Mathf.Epsilon)
    {
        // segment is parallel to plane
        if (N == 0)                         // segment lies in plane
        {
            I = p0;                         // We could return anything between p0 and p1 here, all points are on the plane
            return true;
        }
        else
        {
            return false;                   // no intersection
        }
    }

    // they are not parallel
    // compute intersect param
    float sI = N / D;
    if (sI < 0 || sI > 1)
        return false;                       // no intersection

    I = p0 + sI * u;                        // compute segment intersect point
    return true;
}

```

EDIT: Reading it again, I think I understand what you tried to do and just misinterpreted Pn.v0 to be the same as Plane.distance, while it instead is the center point of the plane.

* p0 and p1 would be the 2 points of the line
* planeCenter would be transform.position of the plane.
* planeNormal would be transform.up of the plane.

---
Tags: unity, collision-detection
---


# Question
Title: Vertical push doesn't let the object fall down instantly [UNITY]
An object (Wall) is continuously moving forward on the X axis with a simple script:

```
public float speed = .2f;
void FixedUpdate()
{
    transform.Translate(speed, 0, 0);
}

```

It is pushing an other object (Penguin), which is affected by gravity. It can "jump" too, with a script of:

```
public void Jump()
{
    transform.position = new Vector3(transform.position.x, transform.position.y + 1.15f, transform.position.z);
}

```

When jumping, over a certain value of speed, like **0.2f**, the Penguin is not falling to the ground until it reaches a velocity Vector of around **(0.0, -10.0f, 0.0)**.

Setting the speed to **0.02f** makes it instantly fall.

How can I achieve the same result with higher speed value?

I attached the setup of the two object in inspector:

# Answer
To move a rigidbody, there's a few different tools:

---

If it is not kinematic, use rigidbody.velocity or rigidbody.AddForce. For example

```
rigidbody.velocity = Vector3.forward * Input.GetAxis("Vertical") * playerSpeed;

```

---

If it is kinematic, use MovePosition:

```
rigidbody.MovePosition(rigidbody.position + Vector3.forward * (Input.GetAxis("Vertical") * playerSpeed * Time.fixedDeltaTime));

```

---

If you use a CharacterController, use Move or SimpleMove.

```
controller.Move(Vector3.forward * (Input.GetAxis("Vertical") * playerSpeed * Time.deltaTime));

```

---

Only use rigidbody.position if you want to teleport your rigidbody instead of moving it continuously.

Only use transform.position if you don't have a rigidbody, or want to teleport a character controller.

---

Rotations follow nearly the exact same rules. Scaling is however more complicated, and should be avoided for rigidbodies.
> 2 votes

---
Tags: unity, physics, rigidbody, rigid-body-dynamics, collider
---


# Question
Title: why does Physics.Raycast always return my player game object instead of the object I clicked?
I have 3D world. I want to detect when the player clicks on a game object in the world.

In this image, I have 2 objects I want to detect mouse click on. The white sphere does have collider on it. The dumpster does not. The behavior is the same as noted below.

I am getting the mouse down detection. When I check the `RaycastHit`, I always get the player game object transform and not the game object I clicked on in the world. If I remove the raycaster checks, then I get mousedown for anything in the game not just mouse down over the game object. I need to be able to distinguish between clicks on different game objects.

I found a post here and added a PhysicsRayCaster, but it didn't change the behavior. The problem isn't getting the event. My problem is detecting which game object the player clicked on in the world.

Here's my code:

```
public class InventoryItemSearchHandler : MonoBehaviour
{
    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = UnityEngine.Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit))
            {
                // CompareTo always fails because hit.transform.name is always "Player" and
                // not the name of the object clicked on
                if (0 == hit.transform.name.CompareTo(transform.name))
                {
                    print("mouse down");
                }
            }
        }
    }
}

```

**EDIT**: In the image below (compared to the one above) I do get the correct transform in the RaycastHit type when I click on the white sphere (and when I click on the dumpster I get the player transform as noted above).

So it looks like the player object is getting in the way. What would be causing that?

# Answer
Turns out, the problem was the boundaries of the box collider attached to the player. As shown in the image below, box collider boundaries (green lines) covered the game objects I thought I was clicking on and that blocked getting the click messages.

Once I changed the collider boundaries, the click messages were getting through to the objects.

The collider boundaries can be turned on by clicking the gizmos button in the game window.
> 1 votes

---
Tags: unity, c#, raycasting, picking
---


# Question
Title: How to Enable canvas with Event during a animation clip
I want to enable a canvas while an animation clip is playing, I used animation Event and call the following script to enable the canvas, but the editor does not recognize any game object.

How a canvas can be enabled?

```
public void SetActiveTrue(GameObject game_object)
{
    game_object.SetActive(true);
}

```

# Answer
> 1 votes
This is a conceptual problem, Animations are file assets in the project while GameObject is a reference to something in your active Scene(s). you cannot drag a Scene GameObject in an AnimationEvent but only prefabs. you can have a workaround:

* by passing a string and doing the lookup ? don't forget some defensive null checks.
* Having that animation directly in a parent of the Canvas so you can enable it directly in the timeline ?

---
Tags: unity, animation
---


# Question
Title: How can I match the delta rotations of two objects?
Here is the code I'm starting from:

```
func orientation_follow(state, current_basis : Basis, target_basis : Basis):
    var delta : Basis = target_basis * current_basis.inverse();

    var q = Quat(delta);
    var axis = Vector3(q.x, q.y, q.z);

    if (axis.length_squared() > 0.0001):  # bullet fuzzyzero() is < FLT_EPSILON (1E-5)
        axis = axis.normalized();
        var angle = 2.0 * acos(q.w);
        state.set_angular_velocity(axis * (angle / (state.get_step())));
    else:
        state.set_angular_velocity(Vector3(0,0,0));

```

The basis is the direction in which each vector of the object has been rotated. That is inverted and multiplied by the basis of the target object (in this case, the player's motion controller) to get the delta rotation from the object to the controller. That delta gets converted to a quaternion, from which its axis is derived and normalized before multiplying the arccosine of the quaternion's z coefficient by 2 to get the angle and finding the product of the angle and that axis (divided by delta time, which I suppose smooths the rotation a bit), setting the angular velocity per how RigidBody objects are meant to be interacted with in Godot.

At least, that's what I think is going on.

The problem is, every time you pick up an object, it essentially snaps to the rotation of the controller, because the function is interpolating the rotation of the object to the rotation of the controller every frame. So if you're trying to turn something upside-down, you have to turn your controller all the way around, instead of picking it up, putting it down partially rotated, then using your other controller to complete the rotation.

What I would like to do is get the difference in rotation in the controller between the last frame and the current frame, then apply that difference to the held object each frame, but nothing I've tried over the last few hours seems to work. The end goal is for an object to keep its rotation when initially picked up, but to rotate the same amount as the controller while held, rather than immediately snapping to the orientation as the controller as soon as it gets picked up.

# Answer
> 2 votes
Turns out the solution to the fundamental problem is to avoid the complicated math and just use an appropriately-configured HingeJoint. When a player grabs an object, set node A to a kinematic body child node of that controller, and set node B to the object being grabbed. Set both paths to empty strings when they let go.

The actual result is a little wonky, but today, I choose to leave tomorrow's problems for tomorrow's me.

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


# Question
Title: Unity RigidBody not rebounding as expected on low-impact collisions
I have a Rigidbody2D with a CircleCollider2D, on which I display a sprite of a circle. This Rigidbody can be "shot" in my game.

I also have 4 rectangular BoxCollider2Ds on the edges of the game screen.

When I shoot the circle, it rebounds fine from the rectangular colliders, except for cases when the impact velocity normal to the rectangular collider's surface is very small. In that case, the rebound velocity in that direction is somehow zero.

Here is the circle's RigidBody2D and CircleCollider2D setup:

Here is the BoxCollider2D of the rectangular collider:

The material "New Physics Material 2D" attached to the ball and the BoxColliders has Friction set to 0 and bounciness set to 1:

Here are two gifs, the first one demonstrating how it works (correctly) in most cases, and the second one demonstrating what happens on a low velocity impact. The "choppiness" of these gifs is due their "giffy" nature. In my game, the movement is smooth.

**I'm wondering why, on the low-velocity impacts, the ball doesn't rebound in the same way as on the high-velocity impacts (i.e, by the outbound angle = inbound angle rule)?**

**----------------------------**

**Edit:**

**----------------------------**

I stepped into the circle's `void OnCollisionEnter2D(Collision2D collision)` method, and, sure enough, on the very slow collisions, the `collision.otherRigidbody.velocity` had a zero-component for the slow velocity of the incoming collision (so depending on whether the impact's x- or y-velocity was slow, the respective component of the resulting velocity was, for whatever reason, set to 0).

Oddly enough (at least for me - I am still not completely familiar with all of Unity's in's and out's), the `collision.relativeVelocity` had been updated to hold the correct resulting velocity of the impact. Thus, by adding following code to the `OnCollisionEnter2D` method, I am able to handle the collision correctly, even on low-impact collisions:

```
if (collision.otherRigidbody.velocity.x == 0)
{
    collision.otherRigidbody.velocity = new Vector2(collision.relativeVelocity.x, collision.otherRigidbody.velocity.y);
}
if (collision.otherRigidbody.velocity.y == 0)
{
   collision.otherRigidbody.velocity = new Vector2(collision.otherRigidbody.velocity.x, collision.relativeVelocity.y);
}

```

**While this *seems* to solve the issue I am experiencing, it doesn't seem to me that I should need to be doing this...**

# Answer
> 2 votes
I had the same issue days ago while creating a pong game. The problem was with the ***Velocity Threshold*** of the Physics Engine provided by unity. You need to tune it to get a smooth bounciness effect. This is the overall set up *(i.e. 1 and 2 is already there in your project*)

1. Angular Drag and Drag of the rigidbody2d = 0
2. Physics2d Material's bounciness = 1
3. **Finally, Go to Edit -\> Project Settings -\> Physics2D and change Velocity Threshold to something lower (I used 0.03)**

---
Tags: unity, physics
---


# Question
Title: Unity generates bad mipmap, making voxel terrains look bad
It's just a **dirt terrain** with **grass blocks** on the **top**. *(which are just dirt blocks with green tops.)*

I sampled a Unity terrain's heightmap, and constructed a voxel terrain based on it, and divided it into chunks, whose meshes then were combined.

Sadly the **generated mipmaps are bad**, the mipmap change is easily noticeable: first the **shade of green changes**, then it **fully becomes dirt colored**.

# Answer
The problem appears to be that Unity generates mip maps from your texture without considering the "cell borders" in your textures (how could it at the texture importing stage when it does not yet know how you are going to set up your UV maps?). So the brown parts of the textures bleed into the green parts.

A quick and dirty solution would be to turn off mip map generation, but that will likely result in a performance penalty (and in a scene like that you need any performance you can get) and other kinds of visual artifacts.

So a better solution could be to use three separate texture images - one for the sides of the cubes, one for the top and one for the bottom. That will prevent the mipmap generation algorithm from mixing these textures.
> 1 votes

---
Tags: unity, rendering, voxels
---


title: Mouse movement with deltaTime?

text:
# Question
Title: Mouse movement with deltaTime?
Is it good idea to multiply Mouse movement by Time.deltaTime?

```
float mouseX = Input.GetAxis("Mouse X") * lookSens * Time.deltaTime;

```

Should we use deltaTime with inputs and when should we use deltaTime with inputs?

# Answer
No, you should not use `deltaTime` for this input.

`Input.GetAxis("MouseX")` and `..."MouseY"` give you values proportional to the number of pixels the mouse has moved *since the last frame*

So assuming the mouse is moving in one direction over this interval, the values will already naturally be larger on long frames that cover a lot of movement, and smaller on short frames where the mouse hasn't had a chance to move as far.

If you then scale this by `Time.deltaTime`, you end up double-dipping this effect: over-diminishing the effective input at high framerates, and making your game behave inconsistently.

When you multiply by `deltaTime`, what you're doing is integrating or "totalling up" an instantaneous sample over that time interval, assuming it was constant for the whole interval. The same way we integrate physics effects from...

Acceleration (meters/second²)
`* deltaTime` (seconds)
Velocity or Speed (meters/second)
`* deltaTime` (seconds)
Position or Distance (meters)

So it makes sense if you're sampling the instantaneous magnitude of an analog stick, and interpreting it as a speed of motion that should be totalled over the frame to get the total distance travelled / total change in position.

But for the mouse, you're already starting with a distance — the distance travelled on the screen, not the speed of that movement — so you don't need to integrate it over the frame time.
> 3 votes

---
Tags: unity, input, timestep
---


# Question
Title: How to align a 3D object with four points?
I'm sure there's a better way to articulate this question, but I lack the vocabulary.

Imagine a skateboard. As it rolls straight down a road, the "deck" is aligned with the road, just offset a few inches higher.

If the skateboard is on a ramp with an incline of say 20º, then then deck of the skateboard can be aligned with the ramp by rotating along it's x-axis by 20º.

But what if the skateboard approaches the ramp at an angle?

Perhaps a visual explanation might be easier to understand.

If I know the points at the top of each pink/purple pole, and I wanted to place an object in the scene that aligned with those points, like this...

Is there some known method for figuring this out?

I'm using Unity, if that makes a difference?

# Answer
The easy solution would be to simply give the object a BoxCollider and a Rigidbody and let the Unity physics engine figure out how it lands. But let's assume you have a good reason why you want to use your own physics and thus want to calculate it yourself.

You will have to cheat here a bit, because in many situations there will be two correct solutions. If you put a perfectly balanced 4-legged table on an uneven surface, it will wobble. There are two solutions to put it down, each one with one leg in the air. Neither solution is more correct than the other.

Applying this to your problem means that you will have to pick 3 of the 4 contact points and ignore the 4th. A good approach is to simply ignore the lowest of the 4 points.

You can now use the surface normal of this triangle as the surface normal of the board. A good explanation how to do this can be found in this stackoverflow answer. The resulting vector is a direction which you can convert into a quaternion using SetLookRotation and assign to `transform.rotation`.

The `transform.position` is the average of the two highest points.
> 3 votes

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


# Question
Title: How can I add biomes to my generated world?
I need a way to generate a world realistically. I want to generate worlds similar to dwarf fortress.

My current code for world generation is this:

```
    worldTiles = ['^',',','.','.']
    def generateWorld(self, x=40, y=20):
        world = []

        for i in range(y):
            row = []
            for z in range(x):
                row.append(random.choice(self.worldTiles))

            world.append(row)
        return world

```

with the worlds it generates being this:

The world is ok, however what I want is biomes, not just completly random generation.

In case it helps, heres how the current generation works:

A variable called worldTiles has alls the tiles the world can have. This is used by the function. The function, creates an array, and appends a row to it. The row is then added to the world, as another array.

A example world might be:

```
  [
    ['^', ',', '^'],
    ['^', ',', '.'],
    ['^', ''., '.']
  ]

```

# Answer
> 3 votes
A common technique for generating random worlds with large biomes is to use stock noise algorithms like perlin noise or simplex noise. Such algorithms generate noise patterns which generate a kind of "smoothed out randomness". Values don't change abruptly like they do in random white noise (like you are using right now). They change gradually with varying steepness. Another more "retro" approach to terrain generation is the diamond-square algorithm which is based on starting out with a linear gradient and then recursively adding subdividsions with slight random offsets.

I could explain these algorithms in detail, but it would be a lot easier to just use a library instead of implementing it on your own. Like this one or this one, for example.

A common technique to tweak the results to match specific requirements or aesthetics is to layer multiple instances of noise with different scales and amplitudes on top of each other. You can even layer different algorithms on top of each other. Like using Simplex Noise for the rough outlines of the world and then Diamond-Square to interpolate within chunks.

When you want to use noise patterns for biome generation, then a common technique is to generate different noise patterns for properties like humidity or temperature and then use a lookup table which decides the biome depending on the combination of values. For example:

* high temperature and high humidity gets you a jungle tile
* high temperature and medium humidity gets you a savanna tile
* high temperature and low humidity gets you a desert tile.
* medium temperature and high humidity gets you swamps
* medium temperature and medium humidity gets you woodland
* medium temperature and low humidity gets you steppe
* low temperature gets you arctic

This is of course just a gross simplification of climate zones. If you want to get really deep into simulationism, then you might want to study some real-world climate science and let a system like the Köppen climate classes guide you.

# Answer
> 2 votes
Don't add biomes, instead vary parameters around your world and pick the biome based on that.

For example you set a temperature and rainfall and you can use them to pick a biome; dry and how would be a desert, cold and dry would be taiga, cold and wet would be snow lands etc.

That way you avoid having a snow biome next to a hot desert without a buffer zone.

You can also create geological interactions to the landscapes like rivers that carve themselves out running to the oceans, mountains creating a rain shadow, etc.

# Answer
> 0 votes
What you're doing there with the random won't work with biomes. Biomes generate differently based on local climate - which on earth is determined by the physical location on the planet surface.

Even Perlin noise or other 'organized random' functions won't give you a biomes effect you are looking for. They only generate localized groupings. It's still random with no perceived overall pattern.

I haven't yet put anything to code because that would depend on the engine. I think what we need to do is program a 'framework' of sorts. This pattern would model a typical planet and allow us to designate a certain set of parameters for: north, south, mountain, desert etc... Those parameters could then be combined with Perlin noise to get a more natural feel.

So an overview of this might be:

* Create the planet surface
* Break up the surface into segments with a specific pattern
* Assign each segment a set of parameters
* Feed those parameters into a noise function

---
Tags: procedural-generation, python
---


title: SDL2 draw red lines around a texture

text:
# Question
Title: SDL2 draw red lines around a texture
I'd like to debug the SDL\_Rect around of my textures visually, what is the best way to draw red lines like an unfilled rectangle around the texture.

# Answer
> 1 votes
You can use the `SDL_RenderDrawRect()` function to render an outline around a texture.

```
void Render(void)
{
   SDL_SetRenderDrawColor(pRenderer, 255, 0, 0, 255);

   const SDL_Rect Quad = {TexXPos, TexYPos, TexWidth, TexHeight};

   SDL_RenderDrawRect(pRenderer, &Quad);
}

```

---
Tags: sdl2
---


title: Creating A UDP Game Server

text:
# Question
Title: Creating A UDP Game Server
I am currently creating a game in need of networking i.e. server and clients. I have basic experience with socket programming and am able to transfer data between two machines via UDP sockets using sdl\_net. Now I would like to start building a game server and client for one of my current projects. Ive taken a look at https://gafferongames.com to help with packet compression and emulating a connection, however i am stumped from there on.

Because my game will be a real-time game, it constantly needs to be sending packets back and forth (perhaps at a set interval) to exchange data and check for timeouts. How do I structure my server? Should I have a thread constantly listening for clients packets and another broadcasting game states every time interval? Or should I stick to a single thread (If so how do I approach it)?

Simply put, I'm a little lost on how to properly make a efficient game server. Any help and explanation would be great!

# Answer
A common architecture is to have:

* one thread which listens to network messages from clients, parses them and collects the parsed results in a message queue.
* At least one other thread which runs the game loop.

At one specific point in the game loop, the following happens:

* The game loop locks the message queue through a thread synchronization like a mutex, semaphore or critical section. The network thread will now block while it tries to enqueue new messages.
* The game loop processes all the network messages from the queue.
* The game loop unlocks the message queue so the network thread can add more messages for the next update.
* The game loop updates the world state
* The game loop sends the results of its update to the clients

Processing network messages at one specific point in your game loop has the advantage that you avoid race conditions. If a network message can cause a gamestate change at pretty much any point of the game loop, then it might do so when you least expect it. This can cause bugs which are very difficult to reproduce and debug, because they only occur when things happen with very specific timing.
> 1 votes

---
Tags: c++, networking, client-server, udp
---


# Question
Title: Struggling to get AI to repeat infinitely
I am following this as a guideline to help me figure out a simple AI for an enemy as I am new to java.

https://www.javacodegeeks.com/2014/08/game-ai-an-introduction-to-behaviour-trees.html

https://github.com/obviam/behavior-trees/tree/master/src/net/obviam/bt

I am calling this function:

```
AI goombaBrain = Routines.selector(Routines.repeatInfinite(Routines.wander(Board.board, InitObject.goomba)));

InitObject.goomba.setRoutine(goombaBrain);

```

But once it finishes wandering to a random location once it doesn't automatically reset. Any ideas? if you need any more information let me know. (InitObject.goomba is the enemy)

# Answer
I've done some code reading and now it's obvious...

you do the following with your code:

1. create a wander `Routine`
2. create a repeatInfinite `Routine` for the wander `Routine`
3. create a selector `Routine` for the repeatInfinite Routine

so far so good - but if you read the code for the `Selector` (the selector `Routine`) you'll notice the following:

```
// We need to progress the sequence. If there are no more routines
// then the state is the last routine's state. (Success for OR was already handled)
if (routineQueue.peek() == null) {
    this.state = currentRoutine.getState();
} else {
    currentRoutine = routineQueue.poll();
    currentRoutine.start();
}

```

this part of the code will **REMOVE** the *repeatInfinite Routine for the wander Routine* from the selector Queue and hence it will be no longer executed. See LinkedList.poll() for details.

## Solution

if you really want to infinitely execute the *repeatInfinite Routine for the wander Routine* then you have to do it solely, without the selector:

```
AI goombaBrain =  Routines.repeatInfinite(Routines.wander(Board.board, InitObject.goomba));
InitObject.goomba.setRoutine(goombaBrain);

```
> 2 votes

---
Tags: java, ai
---


# Question
Title: Player ranking using Elo with more than two players
I would like to use Elo to track player rankings between matches of a certain game, however the game can be played with up to four players in a match. I have seen games like Carcassonne use Elo with more than two players playing, but I am not familiar with Elo beyond a 1-1 matchup.

From the wikipedia article the two-player equations I would like to extend are:

> Ea = 1/(1 + 10(Rb \- Ra) / 400)
>
> Eb = 1/(1 + 10(Ra \- Rb) / 400)
>
> Rxnew = Rxold \+ 32 * (W – Ex), where W=1 if X wins and W=0 if X loses.

How would the computation for Ex and W change given more than two players?

# Answer
As suggested by the top link in my Google search, you could calculate the individual changes in a players Elo rating (your R values), and then sum them up to provide the total change to apply to each player's rating.

i.e. If you have 4 players (A,B,C,D), calculate the change to A's rating (R-sub-a-sub-new) from their scores against B, C, and D, and then adjust A's rating by the total of the R-values calculated.
> 12 votes

# Answer
I found a paper with PHP source code of a method similar to fnord's answer here: http://elo-norsak.rhcloud.com/3.php I created a more general purpose php implementation here: https://github.com/FigBug/Multiplayer-ELO I am using it with my board game group, and so far it seems to be working well.

The calculation of Ex and W would stay the same. Instead of using a K of 32, use a K of 32 / (#players - 1). Then, look at each permutation of 2 players and calculate (32 / (#players - 1) * (W - Ex)). Then RxNew is equal to RxOld + Sum of all the values you just calculated.
> 1 votes

# Answer
I recently wrote this post on the topic. I hope it helps. I will soon also add the code in another post.

> Here is an outline of what it entails:
>
> One decision you have to make is if you have a kind of sub-match or not. For example: In foosball, you will see that in a 2v2 game there are always two players facing each other directly and two indirectly. That means: the two defenders never really interact, it's only the attacker-defender pairs. The alternative is a scenario like Dota which is 5v5 and there are no real individual, predictable 1v1 matchups as part of the real match.
>
> Case one: No sub-match structure:
>
> In this case, you can simply average the rating of all players involved and use that as a team-rating for that team. So for R\_a and R\_b, you would simply use the sum of the ratings of all players of that team, divided by the number of players. Once you have computed the update for the team, you update every team-members rating with the update.
>
> Case two: Sub-matches:
>
> In this case, you split into sub-matches and weigh them against each other. So you compute E\_a and E\_b for every pair and then weigh these. For example: For 5v5 with a 1v1 sub-structure you compute the 5 E\_a values for the 5 pairs. Then you compute a weighted term for every individual player based on the sub-match he is a part of. So if player 1 is part of submatch 1, you compute something like 0.6\*E\_a1 + 0.1\*E\_a2+ 0.1\*E\_a3+ 0.1\*E\_a4+ 0.1\*E\_a5 (where E\_a1 is E\_a for the sub-match the player is involved in).
>
> The parameters here can be freely chosen, but you can optimize them once you have some data. Try to find a weighting scheme for which the player ratings don't fluctuate as much. This can be done automatically by computing the variance fo the values and then minimizing that for a given set of match results by adapting the weights. I hope this is helpful.
> 0 votes

---
Tags: algorithm, multiplayer, ranking
---


# Question
Title: Rotate object always at same speed on screen, no matter camera distance?
I am rotating a globe like XCOM's hologlobe,

I rotate it using Quaternion.RotateTowards(Quaternion from, Quaternion to, float maxDegreesDelta).

I found a good value for `maxDegreesDelta`, in my case it is `5.0f`.

There is a limit on how close or far the camera can be, let's assume clos is `1.0f` and far is `2.0f`.

I want to be able to zoom into the globe, but obviously when I do, it rotates a bit too fast then.

When zoomed out, rotation speed is satisfying:

When zoomed in, rotation is too fast, making it more difficult to manipulate:

And the problem is even more evident as game view size gets bigger, i.e. fullscreen.

Using `Mathf.Lerp` and `Mathf.InverseLerp`, I've tried to make `maxDegreesDelta` and mouse delta proportional to the distance the camera is but it's hardly convincing.

Note: I rotate the globe, not the camera.

**Question:**

How can I ensure object rotates at same speed on screen, no matter how close or far camera is ?

**Code:**

(assumes there is a sphere of radius `0.5` at `Vector3.zero` and camera is positioned at `Vector3.back`)

```
using UnityEngine;
using UnityEngine.InputSystem;

namespace Test2
{
    public class GeoScapeController : MonoBehaviour
    {
        #region Public

        public Transform TargetObject;

        public Camera TargetCamera;

        [Range(0.01f, 1.0f)]
        public float Sensitivity;

        public bool Smooth;

        public float ZoomDistanceMin;

        public float ZoomDistanceMax;

        #endregion

        #region Private

        [SerializeField]
        [HideInInspector]
        private Quaternion TargetRotation;

        [SerializeField]
        [HideInInspector]
        private int ZoomLevel;

        [SerializeField]
        [HideInInspector]
        private int ZoomLevels;

        [SerializeField]
        [HideInInspector]
        private Vector3 ZoomVector;

        [SerializeField]
        [HideInInspector]
        private Vector3 ZoomVelocity;

        private void Reset()
        {
            Sensitivity = 0.05f;
            Smooth = true;

            ZoomDistanceMin = 0.625F;
            ZoomDistanceMax = 1.25F;
            ZoomLevels = 10;
        }

        private void Start()
        {
            TargetRotation = Quaternion.LookRotation(TargetObject.forward, TargetObject.up);
            ZoomVector = TargetCamera.transform.position;
        }

        private void Update()
        {
            var mouse = Mouse.current;
            var delta = mouse.delta.ReadValue();
            var scale = new Vector4(-1.0f, +1.0f, +1.0f);

            var x = mouse.leftButton.isPressed ? delta.y * scale.y * Sensitivity : 0.0f;
            var y = mouse.leftButton.isPressed ? delta.x * scale.x * Sensitivity : 0.0f;
            var z = mouse.middleButton.isPressed ? delta.x * scale.z * Sensitivity : 0.0f;
            var r = Quaternion.AngleAxis(x, Vector3.right) *
                    Quaternion.AngleAxis(y, Vector3.up) *
                    Quaternion.AngleAxis(z, Vector3.forward);

            if (Smooth) // hopefully, quaternion limits won't be crossed !
            {
                TargetRotation = Quaternion.RotateTowards(TargetRotation, r * TargetRotation, 2.5f);

                TargetObject.rotation = Quaternion.Slerp(TargetObject.rotation, TargetRotation, Time.deltaTime * 5.0f);
            }
            else
            {
                TargetObject.rotation = TargetRotation = r * TargetRotation;
            }

            var wheel = (int) mouse.scroll.ReadValue().y / 120;
            if (wheel != 0)
            {
                ZoomLevel = Mathf.Clamp(ZoomLevel + wheel, 0, ZoomLevels);
                var lerp1 = Mathf.InverseLerp(ZoomLevels, 0, ZoomLevel);
                var lerp2 = Mathf.Lerp(ZoomDistanceMin, ZoomDistanceMax, lerp1);
                ZoomVector = Vector3.back * lerp2;
            }

            TargetCamera.transform.position = Smooth
                ? Vector3.SmoothDamp(TargetCamera.transform.position, ZoomVector, ref ZoomVelocity, 0.3f)
                : ZoomVector;
        }

        #endregion
    }
}

```

# Answer
This is my solution, Google Earth like control with smooth animation (or not), when zoomed in it is user friendly and slows panning down.

The only thing I am not satisfied about is the quaternion slerp, at these defaults there won't be any sudden jumps but I would have loved to understand how to sub-interpolate quaternions so it works even when rotating very fast.

Also the other thing is speed is different when at fullscreen but it should be reasonably easy to address that.

Right now however it is quite satisfying.

Feel free to improve and sharing improvements are welcome !

```
using UnityEngine;
using UnityEngine.InputSystem;

namespace Test2
{
    public class GeoScapeController : MonoBehaviour
    {
        #region Public

        public Transform Target;

        public Camera Camera;

        [Range(0.01f, 1.0f)]
        public float MouseSensitivity = 0.01f;

        public bool Smooth = true;

        [Range(0.1f, 90.0f)]
        public float RotationMaxDelta = 5.0f;

        [Range(0.1f, 90.0f)]
        public float RotationSpeed = 5.0f;

        [Range(2, 100)]
        public int ZoomGrain = 20;

        [Range(1, 100)]
        public float ZoomSpeed = 20.0f;

        [Range(1.0f, 100.0f)]
        public float ZoomMin = 10.0f;

        [Range(1.0f, 100.0f)]
        public float ZoomMax = 60.0f;

        #endregion

        #region Private

        [SerializeField]
        [HideInInspector]
        private Quaternion Rotation;

        [SerializeField]
        [HideInInspector]
        private float Zoom;

        [SerializeField]
        [HideInInspector]
        private int ZoomSlot;

        [SerializeField]
        [HideInInspector]
        private float ZoomVelocity;

        private void Start()
        {
            Rotation = Quaternion.LookRotation(Target.forward, Target.up);
        }

        private void Update()
        {
            var mouse = Mouse.current;

            var position = mouse.position.ReadValue();
            if (position.x >= 0.0f && position.y >= 0.0f && position.x < Screen.width && position.y < Screen.height)
            {
                var d = mouse.delta.ReadValue();
                var n = new Vector3(-1.0f, +1.0f, +1.0f);
                var m = Zoom / ZoomMax * RotationMaxDelta;
                var s = MouseSensitivity * m;
                var x = mouse.leftButton.isPressed ? d.y * n.y * s : 0.0f;
                var y = mouse.leftButton.isPressed ? d.x * n.x * s : 0.0f;
                var z = mouse.middleButton.isPressed ? d.x * n.z * s : 0.0f;
                var r = Quaternion.AngleAxis(x, Vector3.right) *
                        Quaternion.AngleAxis(y, Vector3.up) *
                        Quaternion.AngleAxis(z, Vector3.forward);

                Rotation = Smooth
                    ? Quaternion.RotateTowards(Rotation, r * Rotation, m)
                    : r * Rotation;

                var wheel = (int) mouse.scroll.ReadValue().y / 120;
                ZoomSlot = Mathf.Clamp(ZoomSlot + wheel, 1, ZoomGrain);

                var lerp = Mathf.InverseLerp(1, ZoomGrain, ZoomSlot);
                Zoom = Mathf.Lerp(ZoomMax, ZoomMin, lerp);
            }

            Target.rotation = Smooth
                ? Quaternion.Slerp(Target.rotation, Rotation, Time.deltaTime * RotationSpeed)
                : Rotation;

            Camera.fieldOfView = Smooth
                ? Mathf.SmoothDamp(Camera.fieldOfView, Zoom, ref ZoomVelocity, Time.deltaTime * ZoomSpeed)
                : Zoom;
        }

        #endregion
    }
}

```

Previously this zoom level used to be very difficult to navigate, now it's much better:
> 1 votes

# Answer
Here's an alternative approach: scale your mouse delta down if you zoom in and up if you zoom out. Now my math is a bit rusty, so I am not 100% sure, but I think if you just lerp between whatever speed that "looks" right at max and min zoom, you should achieve something that looks right all the way.
> 0 votes

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