# Question
Title: How to simulate a liquid like "The Cook" or "Bake it"?
I want to make a simple liquid something like these gifs:

# Answer
I will explain the concept in shadertoy then I will convert it to Unity because learning with shadertoy is easier.

Shadertoy uses multiple passes, one per "Buffer". As the name indicates, this passes store the results in a buffer. A buffer is just a texture. I am sure Unity will let you render to textures too.

# Simple Liquid

## Buffer1: Painting

```
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    fragColor = vec4(distance(iMouse.xy, fragCoord) < 10.0);
    fragColor += texture(iChannel0, fragCoord.xy / iResolution.xy);
}

```

## Buffer 2: Scaling Everything From Buffer 1

```
float s = 0.;

vec4 Move(vec2 U,vec2 dir) {

     // smoothing gives a circle
     s += 1./ length(dir);

     // using texelFetch ( if speed always refer to an integer number of pixels ) would make your life a bit easier
     vec4 result = texelFetch( iChannel1, ivec2(U+dir) , 0 );

     result /= length(dir);

     return result;
}

void mainImage( out vec4 O, vec2 U )
{
    O = vec4(0);

    // with 8-neighborhood you have square
    O += Move( U, vec2( 1, 0) )
      +  Move( U, vec2(-1, 0) )
      +  Move( U, vec2( 0, 1) )
      +  Move( U, vec2( 0,-1) )
      +  Move( U, vec2( 1, 1) )
      +  Move( U, vec2( 1,-1) )
      +  Move( U, vec2(-1, 1) )
      +  Move( U, vec2(-1,-1) );

    O /= s;

    O += texelFetch(iChannel0, ivec2(U), 0);
}

```

# Simple Liquid + Lighting

# Normal Calculation Using dFdx and dFdy

> **dFdx** and **dFdy** return the partial derivative of expression p in x and y, respectively. Deviatives are calculated using local differencing. Expressions that imply higher order derivatives such as dFdx(dFdx(n)) have undefined results, as do mixed-order derivatives such as dFdx(dFdy(n)). It is assumed that the expression p is continuous and therefore, expressions evaluated via non-uniform control flow may be undefined. https://docs.gl/el3/dFdx

# Calculating Diffuse

```
diffuse = max(dot(N, L)  + 1., 0.);

```

# Calculating Specular

```
specular = clamp(dot(reflect(L, N),vec3(0, 0, -1)), 0., 1.0);

```

# Final Result

---

# Using shader in unity

1. Main Camera -\> Position (0,0,0)
2. 3D Object -\> Quad -\> Position (0,0,1)
3. Add script to quad and assign shader. Play.
4. Use left mouse to paint

# LiquidPaint script:

```
using UnityEngine;

public class LiquidPaint : MonoBehaviour
{
    public int Resolution = 1024;
    public Shader LiquidPaintShader;
    Material material;
    RenderTexture RTA1, RTA2, RTB1, RTB2;
    bool swap = true;

    void Blit(RenderTexture source, RenderTexture destination, Material mat, string name, int pass)
    {
        RenderTexture.active = destination;
        mat.SetTexture(name, source);
        GL.PushMatrix();
        GL.LoadOrtho();
        GL.invertCulling = true;
        mat.SetPass(pass);
        GL.Begin(GL.QUADS);
        GL.MultiTexCoord2(0, 0.0f, 0.0f);
        GL.Vertex3(0.0f, 0.0f, 0.0f);
        GL.MultiTexCoord2(0, 1.0f, 0.0f);
        GL.Vertex3(1.0f, 0.0f, 0.0f);
        GL.MultiTexCoord2(0, 1.0f, 1.0f);
        GL.Vertex3(1.0f, 1.0f, 0.0f);
        GL.MultiTexCoord2(0, 0.0f, 1.0f);
        GL.Vertex3(0.0f, 1.0f, 0.0f);
        GL.End();
        GL.invertCulling = false;
        GL.PopMatrix();
    }

    void Start ()
    {
        material = new Material(LiquidPaintShader);
        RTA1 = new RenderTexture(Resolution, Resolution, 0, RenderTextureFormat.ARGBFloat);  //buffer must be floating point RT
        RTA2 = new RenderTexture(Resolution, Resolution, 0, RenderTextureFormat.ARGBFloat);  //buffer must be floating point RT
        RTB1 = new RenderTexture(Resolution, Resolution, 0, RenderTextureFormat.ARGBFloat);  //buffer must be floating point RT
        RTB2 = new RenderTexture(Resolution, Resolution, 0, RenderTextureFormat.ARGBFloat);  //buffer must be floating point RT
        GetComponent<Renderer>().material = material;
    }

    void Update ()
    {
        RaycastHit hit;
        if (Input.GetMouseButton(0))
        {
            if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition) , out hit))
                material.SetVector("iMouse", new Vector4(
                    hit.textureCoord.x * Resolution, hit.textureCoord.y * Resolution, 1.0f, 1.0f));
        }
        else
        {
            material.SetVector("iMouse", new Vector4(-1000.0f, -1000.0f, -1.0f, -1.0f));
        }

        material.SetInt("iFrame",Time.frameCount);
        material.SetVector("iResolution", new Vector4(Resolution,Resolution,0.0f,0.0f));

        if (swap)
        {
            material.SetTexture("_BufferA", RTA1);
            Blit(RTA1, RTA2, material, "_BufferA", 0);
            material.SetTexture("_BufferA", RTA2);

            material.SetTexture("_BufferB", RTB1);
            Blit(RTB1, RTB2, material, "_BufferB", 1);
            material.SetTexture("_BufferB", RTB2);
        }
        else
        {
            material.SetTexture("_BufferA", RTA2);
            Blit(RTA2, RTA1, material, "_BufferA", 0);
            material.SetTexture("_BufferA", RTA1);

            material.SetTexture("_BufferB", RTB2);
            Blit(RTB2, RTB1, material, "_BufferB", 1);
            material.SetTexture("_BufferB", RTB1);
        }

        swap = !swap;
    }

    void OnDestroy ()
    {
        RTA1.Release();
        RTA2.Release();
        RTB1.Release();
        RTB2.Release();
    }
}

```

# Liquid Paint Shader

```
Shader "LiquidPaint"
{
    SubShader
    {

//------Common-------------------------------------------------------------------------------------------

        CGINCLUDE
        #pragma vertex VSMain
        #pragma fragment PSMain

        Texture2D<float4> _BufferA;
        Texture2D<float4> _BufferB;
        SamplerState _LinearClamp;

        int iFrame;
        float4 iMouse;
        float4 iResolution;

        void VSMain (inout float4 vertex:POSITION, inout float2 uv:TEXCOORD0)
        {
            vertex = UnityObjectToClipPos(vertex);
        }

        ENDCG

//------Buffer A-------------------------------------------------------------------------------------------

        Pass
        {
            CGPROGRAM

            void PSMain (float4 vertex:POSITION, float2 uv:TEXCOORD0, out float4 fragColor:SV_TARGET)
            {
                float2 fragCoord = uv * iResolution.xy;
                fragColor = (distance(iMouse.xy, fragCoord) < 10.0).xxxx;
                fragColor += _BufferA.Sample(_LinearClamp, fragCoord.xy / iResolution.xy);
            }

            ENDCG
        }

//------Buffer B-------------------------------------------------------------------------------------------

        Pass
        {
            CGPROGRAM

            #define Move(U, dir) _BufferB.Load( int3(U + dir, 0) )

            void PSMain (float4 vertex:POSITION, float2 uv:TEXCOORD0, out float4 O:SV_TARGET)
            {
                float2 U = uv * iResolution.xy;
                O = float4(0,0,0,0);
                float s = 0.;
                for (int i=0; i<9; i+= i==3 ? 2 : 1 )
                {
                    float2 D = float2( i%3-1, i/3-1);
                    O +=  Move( U, D ) / length(D);
                    s += 1./ length(D);
                }
                O /= s;
                O += _BufferA.Load( int3(U, 0) );
            }

            ENDCG
        }

//------Image-------------------------------------------------------------------------------------------

        Pass
        {
            CGPROGRAM

            float diffuse;
            float specular;

            void calculateLighting(float2 uv)
            {
                float l = length(_BufferB.Sample(_LinearClamp, uv).xyz);
                float dx=ddx(l)*iResolution.x;
                float dy=ddy(l)*iResolution.y;

                // Calculating Normal by dx and dy
                float3 N =normalize(float3(dx,dy,100.0));

                // Light Direction
                float3 L = normalize(float3(1.0, 1.0, 2.0));

                // Calculating Diffuse
                diffuse = max(dot(N, L)  + 1., 0.);

                // Calculating Specular
                specular = clamp(dot(reflect(L, N),float3(0, 0, -1)), 0., 1.0);

                specular = pow(specular, 12.0);
            }

            void PSMain (float4 vertex:POSITION, float2 uv:TEXCOORD0, out float4 fragColor:SV_TARGET)
            {
                float2 fragCoord = uv * iResolution.xy;

                // Normalized pixel coordinates (from 0 to 1)
                calculateLighting(uv);

                // Get Liquid From Buffer B
                float3 liquid = _BufferB.Sample(_LinearClamp, uv).rgb;

                // Normalizing Liquid
                liquid = clamp(liquid,0.,0.5);

                // Cream Color
                float3 color = float3(1.,0.99,0.81);

                float3 finalColor = liquid * color * diffuse + specular;

                fragColor = float4(finalColor, 1.0);
            }

            ENDCG
        }

//-------------------------------------------------------------------------------------------

    }
}

```

# Source is Available on Github
> 17 votes

---
Tags: unity, shaders, fluid-dynamics
---


title: Unity Build GPU Performance

text:
# Question
Title: Unity Build GPU Performance
I have been banging my head against the wall with this for few days now with no improvement..

The problem is that after build my project keeps using over 30% of the GPU. Even in the editor it takes 20%+ I ended up making a new empty scene with few cubes with rigidbodies, but the performance was still going over 30%. It starts with 3-5 % and within the next 5-10 seconds starts climbing up.

I am using Unity 2019.1.12f1, but the problem is still there even on the newest Unity 2020 version. The project is using LWRP.

I have played around with the quality settings but they seem to have absolutely no effect on the issue, besides turning the V-Sync on, which capped the framerate at acceptable levels.

I am using Windows 10 , my video card is Geforce GTX 1080 Ti.

Here are some screenshots + the project build

Project: https://easyupload.io/foqq5x

# Answer
What you are experiencing are various bottlenecks when performance isn't purposely limited.

If you run a game (even a static none-moving cube) a typical game engine will tell the GPU to render and then go through the game loop and tell the GPU to render again. If there is nothing going on in the game this is very fast the GPU spends most of it's time doing a bit of rendering and then spends the rest of the time sending that data to the display and waiting. The cycle repeats and the game might run at a few thousand FPS and look static while using 100% of the resources of the computer, this is normal.

In that scenario you have told the game engine to go crazy and draw as many frames of the same cube as possible, it'll go and do that but certain parts of the rendering process take longer and cause the GPU to wait, like when it has finished and needs new work (but the CPU is busy doing other stuff) so it'll sit there idle waiting for the next draw calls to be sent. You can change the balance a little if you change render resolution which will mean the GPU has to spend more/less time calculating pixel values, accordingly the perceived GPU utilisation will change.

All of this happens when you tell the game to go as fast as possible! If you instead know "I want 60 FPS" you can tell the game to try it's best to make every frame take 16ms and that means that the GPU/CPU will sit idle more (assuming that you where managing more than 60 FPS before) and task manager will tell you it's being used less.

So in this picture you can see that it takes roughly the same amount of time to render either way if you have v-sync on or off but the CPU will wait on purpose until the current frame has taken enough time in order to hit a performance target which forces the PC to be idle lowering the resources used.

## Things to note

The problem with empty games or static scenes are that if nothing has moved technically nothing needs to be re-rendered but working this out is too slow for modern games where 99% of the time something is happening. If you know that nothing is going to happen (like when you are in a menu or something like that) you can build ways of caching the previous frame and re-render it but that's out of scope for this question. So if you know nothing has changed and you see the GPU doing stuff you might get the impression that the game engine is wasting resources and depending on your point of view it might be but if you where to 'optimise' a standard game engine for that use case it will cost you more performance when you need it once you actually start making stuff move on screen and the calculation tells you not to cache the frame most of the time.

Some game engines will look at the last few frames and notice trends and optimise the game on the fly to get more performance which can change the CPU to GPU load ratio. Unity's Entity system is one case where it takes a few frames to "Warn up" until it knows what requests the game will make and how it needs to structure the data in memory in order minimise overhead (though Unity being Unity this will probably be different in a few years when they inevitably change the system).
> 2 votes

---
Tags: unity, performance, gpu, nvidia
---


# Question
Title: How should I handling clipping vertices that are closer to the eye than the near clip plane?
I'm rolling my own 3D engine, in JavaScript, and using only canvas drawing, no WebGL. This is another Minecraft clone; I love boxes, don't judge me.

So far, everything works wonderfully, except for one thing: in 3D, when some vertices go behind the near clipping plane, their projection on the screen comes out weird (assuming other vertices used to trace a plane are in front).

I tried clipping these points but then I can see trough the surfaces that use these vertices. In WebGL/OpenGL the graphics card takes care of these points and the plane is rendered correctly, but I don't have access to hardware so I must code this myself.

I'm not quite sure what to make of it, currently the last thing that came to mind is to reverse the projection of points behind the player's near clipping plane, which seems logical since I must project a point to a screen which is in front of the vertex.

Here are my thoughts:

Here are some images to illustrate what happens:

From distance the blue box renders perfectly well.

When some of the vertices go behind the player's near clipping plane I do reverse projection, but it doesn't look right:

```
focalLength *= -1;
2d.x = x*focalLength/z;
2d.y = y*focalLength/z;

```

Note that the gray box behind is completely removed since all the vertices used to draw its faces are behind the player.

This is what happens when look up or down.

I don't know what to make of the math behind this, I'm hoping somebody has encountered the same problem already and can help me.

# Answer
The purpose of the near clipping plane is that it is a *clipping plane*. Triangles that are outside of a clipping plane are *clipped*: cut into pieces so that each piece that is left is within the clipping region.

You can attempt to ignore the near clip if you wish. Indeed OpenGL and D3D have ways of turning off near plane clipping altogether (though the depth buffer still has a minimum near value). The problem is not the near clip.

The problem is with vertices that are *behind* the camera.

You cannot render triangles that are behind the camera. Not with a perspective projection. Such triangles do not make sense under the math behind perspective projections. Furthermore, they are also outside of the frustum.

Turning off near clipping turns a frustum into a pyramid. The reason the pyramid stops at the point is because points above the pyramid are behind all four of the sides of the pyramid. So any point behind the camera (the tip of the pyramid) is above, below, to the left, and to the right of the visible region of the screen. All at the same time.

As I said: vertices under a perspective projection that are behind the camera don't make sense.

You must implement clipping. You must detect when any vertex of a triangle, in clip-space (*before* the perspective divide) is behind the camera. If it is, then you must clip that triangle, generating only triangles that are in front of the camera.

This is not a simple process. It will involve math that only makes sense if you have a full understanding of homogenous coordinate systems. Alternatively, you could just straight-up cull any triangle if any vertex of it is behind the camera.
> 2 votes

# Answer
I know this is probably a bit late, but I have a solution to this.

The transformation from world coordinates to points on a screen involves multiple parts, which involve subtracting the camera's coordinates, rotating around the camera, and then dividing by the axis perpendicular to the camera. (generally the Z axis.)

The problem with the clipping happens with the divide, because division by negative z indexes and coordinates close to 0 result in huge values, so the clipping algorithm is done just before that, but after the coordinates have been rotated and transformed.

Having the points of the face you want to clip in an array helps for organization. The algorithm goes through each point, sees if it's clipped or not, and then creates new points based off of that.

I apologize if I wasn't completely clear. Here's my code:

```
//loop through all points
for (var y=0;y<tempPoints.length;y++) {
    //if the selected point will be clipped, run the algorithm
    if (tempPoints[y][2] < render_clipDistance) {
        //freefriends is the number of adjacent non-clipped points
        var freeFriends = (tempPoints[(y+(tempPoints.length-1))%tempPoints.length][2] >= render_clipDistance) + (tempPoints[(y+1)%tempPoints.length][2] >= render_clipDistance);

        if (freeFriends == 0) {
            //if there are no free friends, there's no point in attempting, so just move on
            tempPoints.splice(y, 1);
            y -= 1;
        } else {
            //move towards friends
            var friendCoords = tempPoints[(y+(tempPoints.length-1))%tempPoints.length];
            var moveAmount = getPercentage(friendCoords[2], tempPoints[y][2], render_clipDistance)
            var newPointCoords = [linterp(friendCoords[0], tempPoints[y][0], moveAmount), linterp(friendCoords[1], tempPoints[y][1], moveAmount), render_clipDistance + 0.05];

            tempPoints.splice(y, 0, newPointCoords);

            y += 1;

            friendCoords = tempPoints[(y+1)%tempPoints.length];
            moveAmount = getPercentage(friendCoords[2], tempPoints[y][2], render_clipDistance)
            newPointCoords = [linterp(friendCoords[0], tempPoints[y][0], moveAmount), linterp(friendCoords[1], tempPoints[y][1], moveAmount), render_clipDistance + 0.05];
            tempPoints.splice(y, 1);
            tempPoints.splice(y, 0, newPointCoords);
        }
    }
}

```
> 2 votes

# Answer
If part of the triangle in behind the near plane could you then do a per-pixel check to see if the pixel position is behind the clipping plane?

You might treat the near plane like any other clipping plane. For example clipping planes are used for things like water planes (for reflections and refractions). I would think that this clipping plane would work just like the near clipping plane, and clip on a per-pixel basis.

I know how to handle clipping planes in HLSL with DirectX, but their implementation could be proprietary. If you could get a hold of the info for that it might be helpful.

Additionally here is a link that might help you: http://http.developer.nvidia.com/GPUGems2/gpugems2\_chapter42.html
> 0 votes

---
Tags: html-canvas
---


# Question
Title: My runtime (game) won't reset back to how it was?
I increase the scale of the objects when it passes a certain time or in this case, my "difficulty"

```
    //Spawn Size
float spawnSize = 8;

void Update()
{
    if (Time.time > nextSpawnTime)
    {
        float SpawningInBetween = Mathf.Lerp(spawnsMinMax.y, spawnsMinMax.x, Difficulty.GetDifficultyPercent());
        print(SpawningInBetween);
        nextSpawnTime = Time.time + SpawningInBetween;

        if(Difficulty.GetDifficultyPercent() > 0.7f)
        {
            fallingRockPrefab.transform.localScale = Vector2.one * spawnSize;
        }

```

Then as expected, the object increases the size after it passed that conditions so i want to revert back to its previous state so i remove:

```
  if(Difficulty.GetDifficultyPercent() > 0.7f)
    {
        fallingRockPrefab.transform.localScale = Vector2.one * spawnSize;
    }

```

but when I saved it and go back to unity, the object still in its "increased" size right at the start. What's happening?

# Answer
> 1 votes
Most likely, you are scaling your prefab, which will persist after the program is stopped. Assuming you have some prefab that you have assigned in the inspector, you will need to instantiate it like this:

```
public MyClass : MonoBehaviour{
   public GameObject rockPrefab; //assign this in the inspector

   void Update(){
    if (Time.time > nextSpawnTime){
      //spawn new rock
      GameObject go = Instantiate(rockPrefab);
      go.transform.position = (your position vector3);
      go.transform.localScale = (your scale vector3);
    }
}

```

Make sure you later destroy your rocks as they will not "despawn" automatically. Either track them in some sort of List and manually check when to destroy them, or better, attach a script to the rock prefab, add a method that checks for some circumstance (position is greater/less than some value, the amount of time lived is larger than some value, etc) and then call

```
Destroy(this.gameobject)

```

Hope this helps.

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


# Question
Title: Launch event at the end of an animation with phaser 3
I'm starting to develop in Phaser 3, and I'm really a begginer.

I'm trying to make an attack move of an archer sprite, but I cannot make it work right...

This is how I have defined the things related to combat:

```
class Jugador extends Phaser.Physics.Arcade.Sprite {

    constructor(escena, x, y) {
        super(escena, x, y, "jugador");
        this.escena = escena;
        this.escena.add.existing(this);
        this.escena.physics.add.existing(this);

        this.createVariables();
        this.createControls();
        this.createAnimations();
  }

  createAnimations(){
    this.defineAttackAnimation();
    /// Some others...
  }

  defineAttackAnimation(){
    this.attackAnimation = {};
    this.attackAnimation.key = "attack";
    this.attackAnimation.frames =
      this.escena.anims.generateFrameNames("attack",
      {
        prefix: "attack",
        start: 1,
        end: 6
      });
    this.attackAnimation.frameRate = this.attackFrameRate;
    this.attackAnimation.repeat = 1;
    var atkListener = () => {
      this.arrow();
    };
    this.escena.anims.create(this.attackAnimation);
    this.escena.anims.get("attack")
      .addListener("animationcomplete", atkListener);
  }

  arrow(){
    console.log("arrow");
  }

  attack(){
    if(this.body.onFloor() && this.attackButton.isDown){
      this.setVelocityX(0);
      this.setVelocityY(0);
      this.play("attack", true);
    }
  }

  update() {
    if ( this.body.onFloor() ){
      this.setVelocityY(0);
    }

    this.facing();
    this.idle();
    this.walk();
    this.jump();
    this.attack();

    if (this.body.velocity.y < 0){
      this.play("jump");
    } else if (this.body.velocity.y > 0 && !this.body.onFloor()){
      this.play("falling");
    }

  }
}

```

What I want to do is:

1. Player pushes the attack button.
2. Attack animation plays. I would like it to be played untill it ends, but now I have to keep pushing the attack button.
3. When attack animation ends, the function "arrow" is executes in order to make an arrow appear.

Thanks in advance.

# Answer
using the animationcomplete event is doable for you scenario, however StateMachine probably be better depending on how complicated your animation is. this is a good article on how to create one: https://www.mkelly.me/blog/phaser-finite-state-machine/

Below is a copy of my extended version from above to do complicated attack combo chaining. but also is super useful for going between states i.e JUMPING, IDLE, RUNNING, ROLLING etc

* enter, exit will only be called once
* execute() is an update loop called in your scene update() method
* and depends on your event, im expecting my animationcomplete event to be called multiple times, otherwise you can just use .once() instead of .on so you dont need to remove the event listener with .off
* take note on how i use the event listener .once and .on in the enter(). how .off is used in exit(). and how im continue to listen to isDOWN during the update() loop
* the idea of below code is, when user hit attack once from IDLE state it will come to Attack1State, during this state, user might still holding the key (isDOWN), so you are expecting the user to let go and trigger .on key up event, but limiting it to only one time event preventing multiple presses ( ATTACK.once() ). On the 2nd isDown during update() loops is where i check other conditions, it if match transition to another state. if the user did not press another ATTACK button before the animation ends than we send the object back to IDLE state and reset the counter. after animation ends. I also given a tiny window of buffer to allow user press it again with the delay

note: it is written in typescript

```
    8 class Attack1State extends State {
    9     ANIMATION_END: boolean = false
   10     enter({ref, stateData}) {
   11         var { ATTACK } = ref.KEYS
   12         ref.play("hero_attack1_animation")
   13         ref.body.setVelocityX(0)
   14
   15         ATTACK.once('up', ()=>{
   16             stateData.ATTACK_COUNT++
   17         })
   18
   19         ref.on('animationcomplete', this._animationEnd, this)
   20     }
   21     excecute({ref, stateData}) {
   22         var { ATTACK } = ref.KEYS
   23         if (ATTACK.isDown && stateData.ATTACK_COUNT == 1 && this.ANIMATION_END && ['idle','move'].includes(this.stateMachine.prev_state)) {
   24             this.stateMachine.transition('attack2')
   25         }
   26     }
   27     exit({ref}) {
   28         ref.off('animationcomplete', this._animationEnd, this)
   29     }
   30     private _animationEnd(animation) {
   31         var self = this
   32         if (animation.key !== 'hero_attack1_animation') return
   33         this.ANIMATION_END = true
   34         this.stateMachine.stateArgs.scene.time.addEvent({
   35             delay: 500,
   36             callback:() => {
   37                 if (this.stateMachine.stateArgs.stateData.ATTACK_COUNT == 1) {
   38                     self.stateMachine.transition('idle')
   39                     this.stateMachine.stateArgs.stateData.ATTACK_COUNT = 0
   40                 }
   41         }})
   42     }
   43 }
   44

```
> 0 votes

# Answer
don't use `addlistener` on the animation you can either

1) use `on` on your game object (Sprite)

```
this.on('animationcomplete', this.arrow, this);

```

https://phaser.io/examples/v3/view/animation/on-complete-callback

or

2) use the `.chain` function

https://phaser.io/examples/v3/view/animation/chained-animation
> 0 votes

---
Tags: javascript, animation, events, phaser
---


# Question
Title: What is the correct way of implementing a deterministic frame update?
My goal:

* Implement the game update loop so that it's deterministic (i.e. every frame of updation behaves the same when run multiple times with same frame-input, does not depend on processing speed etc.)
* Limit the framerate of the game at (maximum) 60fps (can be slower if CPU hangs)

What I don't want to do:

* I don't want to use a `delta_time` to compute position updates, because it violates the goal
* Don't want to introduce any additional input-lag that would come with any sort of buffering (for interpolating time between frames etc.)

What I came up with:

* I use vsync to guarantee that the game never produces more than 60 fps
* I disallow any screen-mode that is not running at 60Hz because the game would run at different speeds
* I allow windowed mode only if the current screen-mode is at 60Hz

Is there a better approach that what I'm doing to achieve what I want, perhaps without limiting the supported refresh rates?

# Answer
> 3 votes
DMGregory guided me towards a good solution explained in this article:

Use a fixed timestep

This solution allows the total decoupling of the simulation and rendering frequency, while allowing for a fixed timestep for the simulation part.

Visual smoothness is preserved by interpolating between the previous and current (last) state of simulation with a blending factor that is given by the total remainder amount of non-yet-simulated time (since simulation happens in fixed step intervals).

This introduces a \<1 frame lag between the rendering and the simulation as the rendered state lags behind the simulation, but this does not introduce input lag as the inputs are taken into account in the blending through the current state.

So in terms of lag, responsiveness remains instantaneous while the actual drawn position falls behind by a fraction of an update.

---
Tags: frame-rate
---


# Question
Title: Collision with supposedly aligned box-colliders
I am quite new to game development, and I am trying to create a top-down game with 2D sprites, but with a 3D feel to it. I managed to do so with the 2D engine by setting `Transparency Sort Mode` to `Custom Axis` with the axis values set to `(X=0,Y=1,Z=0)`. I then moved the pivot of GameObjects to bottom-center and used the pivot as sorting point for the sprites. I am now trying to create the environment, but my character 'clips' against the Box Colliders, even though I did all I could think of to align them (same pivot coordinates, same collider offset and size). See the attached GIF for an example:

I think that the cause is mentioned here, but there are no solutions mentioned there. My two solutions:

* Remove the colliders, group the objects in a parent object, and add the collider there. But then I would get the same issue if I place two of those instances next to each other.
* I am still pondering to drop this approach altogether and try the same in the 3D engine, but with a fixed camera angle. I lack experience to estimate if that would be a better approach, so if someone thinks that approach would be better suited to this game style, I am happy to hear it.

Can anyone give me advice on this issue, or point me towards resources that might be useful?

Thanks in advance,

Florian

---

Some pictures of the settings I used:

# Answer
> 1 votes
DMGregory asked me some other good questions in the comments that made me think about my problem. Based on that, I was able to solve the problem myself. In the end, I solved it by using the proposed `CompositeCollider2D`, and by toggling `Grid Snapping` on.

I then aligned the objects while snapping to the grid, and this seems to have resolved the 'clipping'.

However, the clipping now occured at the edge of the wall. In addition, I had to set the `BoxCollider2D` on the `Player`, to a `CapsuleCollider2D`.

---
Tags: unity, 2d, collision-detection, collider
---


# Question
Title: I am working on an Quiz game i am trying to get user input from the player in ters of button by adding listeners
but i get no touch input when i make click on gameplay, i have added onClick().Here is the code......................

```
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class Level2UI : MonoBehaviour
{
    private List<string> sceneHistory = new List<string>();
    [SerializeField] private Level2Manager gameManager;
   [SerializeField] private TextMeshProUGUI questionText;
   [SerializeField] private List<Button> options;
   [SerializeField] private Color CorrColor, WrongColor, NormalColor;
    private Question question;
    private bool answered;

    // Start is called before the first frame update

    void Awake()
    {
        for(int i = 0; i < options.Count; i++)
        {
            Button localBtn = options[i];
            options[i].GetComponentInChildren<Button>().onClick.AddListener(delegate { ClickedAnswer(localBtn); });
            //   localBtn.onClick.AddListener(delegate { ClickedAnswer(localBtn); });
            Debug.Log("testclick");
      //      btn.onClick.AddListener(ClickedAnswer);

        }
    }
    public void SetQuestion(Question question)
    {
        this.question = question;
        questionText.text = question.questionInfo;

        List<string> answerList = ShuffleList.ShuffleListItems<string>(question.options);
        for(int i=0; i< options.Count; i++)
        {
            options[i].GetComponentInChildren<TextMeshProUGUI>().text = answerList[i];
            Debug.Log("check");
            options[i].name = answerList[i];
            options[i].image.color = NormalColor;
        }
        answered = false;
   //     setButton();
    }

    public void ClickedAnswer(Button btn)
    {

        print("txt");
        if (!answered)
        {
            answered = true;
            bool val = gameManager.Answer(btn.name);

            if (val)
            {
                btn.image.color = CorrColor;
                Debug.Log("test1");
            }
            else
            {
                btn.image.color = WrongColor;
                Debug.Log("test");
            }
        }
    }
    //Call this whenever you want to load a new scene
    //It will add the new scene to the sceneHistory listss
    public void LoadScene(string newScene)
    {
        sceneHistory.Add(newScene);
        SceneManager.LoadScene(newScene);
    }

    //Call this whenever you want to load the previous scene
    //It will remove the current scene from the history and then load the new last scene in the history
    //It will return false if we have not moved between scenes enough to have stored a previous scene in the history
    public bool PreviousScene()
    {
        bool returnValue = false;
        if (sceneHistory.Count >= 2)  //Checking that we have actually switched scenes enough to go back to a previous scene
        {
            returnValue = true;
            sceneHistory.RemoveAt(sceneHistory.Count - 1);
            SceneManager.LoadScene(sceneHistory[sceneHistory.Count - 1]);
        }

        return returnValue;
    }
}

```

# Answer
I reduced your project to the smallest running example.

```
using UnityEngine;
using UnityEngine.UI;

public class Demo : MonoBehaviour {
[SerializeField] private Button option;

void Awake()
{
    option.GetComponentInChildren<Button>().onClick.AddListener(delegate { ClickedAnswer(option); });
}

public void ClickedAnswer(Button btn)
{
    Debug.Log("button clicked");
}

}

```

Which is working and prints button clicked when clicked. This is tested on an empty scene with nothing but a canvas, the auto added event system and a single button on the canvas.

Since this code sample is not working for you and in your screenshot you are missing the event system as well. This should be the reason why your clicks are failing. Normally it gets automatically added to the scene when you first add the canvas. If by chance you deleted it or it is othervise missing, you can just add it again from GameObject - UI - Event System.
> -1 votes

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


# Question
Title: Godot: Move_and_slide_with_snap not working on slopes
**My Problem**

I am currently building a platformer game. I was attempting to use move\_and\_slide\_with\_snap for the first time and can't find it working for me. My character does snap to the ground like I expected, but I find that it still slides when it's on a slope. I *think* that I implemented the code properly with it.

If there is a solution I would love to hear it. What am I doing wrong?

```
func _physics_process(delta):

var current_gravity = GRAVITY - (int(is_on_wall() and inventory.Frog) * GRAVITY/2)
var current_jump_force = JUMP_FORCE

var x_input = Input.get_action_strength("ui_right") - Input.get_action_strength("ui_left")

if x_input != 0:

    motion.x += x_input * ACCELERATION * delta
    motion.x = clamp(motion.x, -MAX_SPEED, MAX_SPEED)

else:

    playback.travel("Stand")

if !is_on_wall():
    if motion.y <= max_fall_speed:
        motion.y += current_gravity * delta
else:
    if motion.y <= max_slip_speed:
        motion.y += current_gravity * delta

if is_on_floor() or is_on_wall():
    if x_input == 0:
        motion.x = lerp(motion.x, 0, FRICTION)

    if Input.is_action_just_pressed("ui_up"):
        var can_jump = int(inventory.Spring)
        motion.y = -(current_jump_force + (JUMP_FORCE / 2.5 * can_jump))
else:

    if Input.is_action_just_released("ui_up") and motion.y < -JUMP_FORCE/2:
        motion.y = -current_jump_force/2

    if x_input == 0:
        motion.x = lerp(motion.x, 0, AIR_RESISTANCE)

if !motion.y:
    motion = move_and_slide_with_snap(motion, Vector2.DOWN * 320, Vector2.UP, true, 1)
else:
    motion = move_and_slide(motion, Vector2.UP)

```

# Answer
> 1 votes
I struggled with this for a long time. For me, the solution was centered around having a correct `snap` vector. Using `get_floor_normal()` as `snap` when not jumping resolved my problem. For example:

```
snap = get_floor_normal()
if is_on_floor():
  if Input.is_action_just_pressed("jump"):
    snap = Vector3.ZERO

move_and_slide_with_snap(velocity, snap, Vector3.UP, true, 4, max_slope_angle)

```

I took this example code from my own project which is why I have `Vector3`'s. I believe it will work just the same for `Vector2`. Let me know if this solves the problem for you.

---
Tags: physics, movement, platformer, godot, character
---


title: sprite group doesn't support indexing

text:
# Question
Title: sprite group doesn't support indexing
I have a sprite group created with pygame.sprite.Group() (and add sprites to it with the add method)

How would I retrieve the nth sprite in this group?

Code like this does not work:

```
mygroup = pygame.sprite.Group(mysprite01)
print mygroup[n].rect

```

It returns the error: group object does not support indexing.

For the moment I'm using the following function:

```
def getSpriteByPosition(position,group):
    for index,spr in enumerate(group):
        if (index == position):
            return spr
    return False

```

Although working, it just doesn't seem right...

Is there a cleaner way to do this?

EDIT: I mention a "position" and index but it's not important actually, returning any single sprite from the group is enough

# Answer
What do you need the index for? Since sprites are hashed, the index is not stable; since you can't use it to easily find the sprite again, I don't know why you'd want to store it; and since you can't easily get from a sprite to an index I don't know how you got it in the first place.

If you need a reference to a sprite, reference *the sprite itself*, not its index.
> 3 votes

# Answer
You can save a reference to the sprite elsewhere. Game class might have a variable pointing to the player instance, as well as sprite list.

You can have a reference to one sprite, in multiple sprite groups. Ex: Starcraft unit selections, could use a unit\_list of all unit sprites. And a sprite group for selected\_units.

```
player = Unit()
units = pygame.sprite.Group()
units.add( Unit(), Unit() , player, Unit() )

# use player, by ref.
print player.rect
for unit in unit_group:
    print unit.rect

```
> 1 votes

# Answer
If you really, truly, absolutely want access a sprite by index, you can do this:

```
third_sprite = mygroup.sprites()[2]

```

So your function would be:

```
def getSpriteByPosition(position,group):
    return group.sprites()[position]

```

Which throws `IndexError` if the index is not found. If you want to return `None` in that case, simply enclose the line with a `try` block:

```
def getSpriteByPosition(position,group):
   try:
       return group.sprites()[position]
   except IndexError:
       pass

```

But... quoting user744, *"What do you need the index for?"*. Afterall, the index of a sprite changes when you add or remove sprites to that group. And even if you don't, Pygame does not guarantee the list order will be the same in each call. So what do you mean by the "3rd sprite in the group"? It may be the 3rd now, but the 5th or 2nd later. How useful is that for you?

Simply put:

**Being the nth sprite in a group means *absolutely nothing* !**

*(as a side note, `position` is a poor name for an index, as it might get confused as the sprite `(x,y)` position on screen)*

Another sidenote: try to think OO. Instead of a *function* that receives a group as argument, subclass `Group` and create a custom *method*, so you can use it like `mygroup.getSpriteByPosition(3)`
> 0 votes

# Answer
As others have already said, you should probably refer to a sprite by something else then its order of addition to the group. I'll try to give some examples of uses both using a group and a regular list.

# sprite.Group

You can iterate over `sprite.Group` (or `sprite.Group.sprites()` \- both give you the same) and check each sprite against some criteria.

Should you need to remove "dead" sprites, for example, you could use:

```
wanted_sprites = [sprite for sprite in mygroup if not sprite.alive]
# replace .alive with whatever condition you need
for sprite in wanted_sprites:
    sprite.do_something()

```

or simply:

```
   [mygroup.remove(sprite) for sprite in mygroup if not sprite.alive]

```

# list

However, if you really need to keep a sprite's position in a list, why not just use a regular `list`? Instead of using `mygroup.update()` (one of the `sprite.Group` functions) you would have to use:

```
[sprite.update() for sprite in my_sprite_list]

```

or

```
[sprite.update() for sprite in my_sprite_list if sprite.visible]  # or whatever condition

```

For collisions, what really matters is the `sprite.rect` anyway, so you could check if a sprite collides with the last sprite of your list with:

```
some_sprite.rect.colliderect(my_sprite_list[-1].rect)

```

I've tried to say something about different possible needs to deal `sprite.Group`/`list`, but, in the end, you should consider your specific needs (and possible future needs) to decide what to do:

* change your logic to use a `sprite.Group` (changing the way you search for sprites);
* or change your logic to use a `list` of sprites (replacing the few functions that the Group has with your own).
> 0 votes

# Answer
Use Sprites method on the group, it returns a list of all the sprites on older pygame versions. And an "ordered" list if your using pygame 1.8, which is a new feature.

Like this:-

Bullet = Group()

Out\_list = Bullet.sprites()

Or

Our\_list = Bullet.sprites().copy()

"We use copy method if we are going to do modifications on the list,it might get mess if we dont"

Our\_list\[index\]

"by putting your index in the square bracket you get access to a sprite in your list"
> 0 votes

---
Tags: sprites, python, pygame
---


# Question
Title: Godot: How do I get the id mask for a physics layer by name?
I would like to figure out whether a collider is in a physics layer by the name (string) I set in project settings:

```
func _physics_process(delta):
    var collision = move_and_collide(direction * delta * speed)
    if collision and (collision.collider.collision_layer & get_collision_layer("Walls")) != 0:
        direction = direction.bounce(Vector2.LEFT)
    # more behaviors based on other layer tests

```

`Walls` is the name of the physics layer and I am trying to find `get_collision_layer`.

I am using Godot 3.2.1. `self` is a `KinematicBody2D` & colliders are `StaticBody2D`'s & also `KinematicBody2D`'s.

I have figured out the collision id (as an int) but still think it would be cleaner to use layer names, preferably using a built-in function.

# Answer
> 4 votes
Getting layer via name is not possible as of Godot v3.2.1.

However, you can use groups and the logic will be the same. Add the wall collision objects to a "Walls" group and then check if it's in the group instead of checking the collision layer. For example:

```
    if collision and collision.collider.is_in_group("Walls"):
        direction = direction.bounce(Vector2.LEFT)

```

# Answer
> 5 votes
Just a demo in an empty node - range starts with 1 up to the number of layers It creates a dictionary where you can access with layer name and get the number as 2 to the power of layer number - run only once in a parent node

```
func _ready():
    var layers = {}
    for i in range(0, 5, 1):
        var layer = ProjectSettings.get_setting("layer_names/2d_physics/layer_" + str(i + 1))
        layers[layer] = pow(2, i)
    print(layers)
    print(layers['Coins'])

```

{Bumpers:16, Coins:4, Enemies:2, Player:1, World:8}

4

and a working version

```
var is_stomping = false
var _layers := {}

func _ready():
    for i in range(0, 5, 1):
        var layer = ProjectSettings.get_setting("layer_names/2d_physics/layer_" + str(i + 1))
        _layers[layer] = pow(2, i)

func _on_StompDetector_area_entered(area: Area2D) -> void:
    is_stomping = area.collision_layer == _layers['Bumpers']

```

---
Tags: physics, godot, collider
---


title: Prefab spawning issue

text:
# Question
Title: Prefab spawning issue
I am having trouble spawning some obstacles from some prefabs. The aim is to make and endless runner (like normal) with obstacles to go through that spawn as the sprite goes up. But my prefabs don't spawn at the top?

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

public class RandomSpawn : MonoBehaviour
{
    public GameObject B1, B2;
    public float spawnrate = 2f;
    float nextSpawn = 0f;
    int whatToSpawn;

    void Update()
    {
        if (Time.time > nextSpawn)
        {
            whatToSpawn = Random.Range(1, 3);
            Debug.Log (whatToSpawn);

            switch (whatToSpawn)
            {
                case 1:
                    Instantiate(B1, transform.position, Quaternion.identity);
                    break;
                case 2:
                    Instantiate(B2, transform.position, Quaternion.identity);
                    break;
            }

            nextSpawn = Time.time + spawnrate;
        }
    }
}

```

# Answer
As Phillip said above, your current bug seems to be caused by your instantiation code `Instantiate(B1, transform.position, Quaternion.identity);` which will spawn an instance of B1 at the current game objects position. However instead of moving your RandomSpawner object I would suggest adding a new component to each of your level pieces:

```
public class LevelPart
{
    public Transform nextPartSpawnPoint;
}

```

You can then change your Random Spawner script to something like the following:

```
public class RandomSpawn : MonoBehaviour
{
    public List<GameObject> levelPartPrefabs = new List<GameObject>();
    public float spawnRate = 2f;
    private Transform nextSpawnPosition = null;
    private Coroutine spawnRoutine = null;

    private void OnEnable()
    {
        spawnRoutine = StartCoroutine(SpawnParts);
    }

    private void OnDisable()
    {
        StopCoroutine(spawnRoutine);
    }

    private IEnumerator SpawnParts()
    {
        while (true)
        {
            yield return new WaitForSeconds(spawnRate);
            SpawnLevelPart();
        }
    }

    // Public so this can be called from another class if you want to force extra parts to spawn.
    public void SpawnLevelPart()
    {
        if (nextSpawnPosition == null)
        {
            nextSpawnPosition = transform;
        }

        GameObject nextPartPrefab = levelPartPrefabs[Random.Range(0, levelPartPrefabs.Count];
        Debug.Log("Spawning level part: " + nextPartPrefab.name);
        GameObject nextPart = Instantiate(nextPartPrefab, nextSpawnPosition.position, nextSpawnPosition.rotation);
        nextSpawnPosition = nextPart.GetComponent<LevelPart>().nextPartSpawnPoint;
    }
}

```

This is far from the best solution (heck it's not even tested) but it should do what you want it to do and add a bit of extra flexibility.

If you want to do things like allow your player to change direction, use level parts with different sizes, or, with a bit more modification, even stuff like branching paths.

For future enhancements you may want to look in to how to delete old level parts since your game could get laggy if played for a long time and possibly object pooling if you want to dip a toe in some more advanced design.
> 1 votes

# Answer
Your code spawns the obstacles at `transform.position` which refers to the position of the game object this script is attached to.

So you just have to move the game object with this script to the location where you want the objects to spawn.

I am not sure what exactly you mean with "go through that spawn as the sprite goes up". But if it means that you want the spawn location to somehow change throughout the game, then you would either have to add some code to move the position of this game object or you would have to stop using `transform.position` as the instantiation location and instead create a `new Vector3` with the spawn coordinates you want.
> 0 votes

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


title: Correct use of AttachActorToActor [ue4]

text:
# Question
Title: Correct use of AttachActorToActor [ue4]
I'm trying to stick some blocks together, but frankly I have no idea what I'm doing. I spawn 2 blocks during run time, and if they have an on hit event they're supposed to stick to each other.

It struck me that I'm not even sure if that's what attach does, and maybe it has some completely different meaning.

with the following blueprints, I'm getting all sorts of errors like "already attached" and "can't attach actor to actor, already attached"

https://i.stack.imgur.com/FALTZ.jpg

Any help appreciated

# Answer
> 1 votes
**It really depends on your use case.**

For example can any cube stick to any cube?
Or maybe a number of cubes can only stick to some others etc...

**Regarding the error messages:**

I guess both of your Blueprints are triggering your attachment functionality, and that is why you getting the errors. You have to find a way to trigger it only once per collision.

You can use the Get Attached Actors node to get a list of all the attached Actors of an Actor, or any similar node that fits your use case.

Then you can iterate though it and check if you are already attached to that Actor.

Keep in mind I have not tested this working, and this might not be a very good solution if you have a large number of colliding objects in a short period of time.

But could be a good starting point.

---
Tags: unreal-4, blueprints
---


# Question
Title: Find range between two signed 180° angles
How can I find the angle between two angles that go from -180 to 180 degrees?

I would like to do :

```
if (angleDiff > 90)
{
    // The angle is bigger than 90 degrees...
}

```

I tried subtracting them but that doesn't seem to work. Thank you

# Answer
Unity has a built-in function for this:

> public static float **DeltaAngle**(float **current**, float **target**);
>
> **Description**
>
> ---
>
> Calculates the shortest difference between two given angles given in degrees.

So you can write...

```
if ( Mathf.Abs(Mathf.DeltaAngle(angleA, angleB)) > 90f ) { ... }

```

Don't forget to search for past answers and read the documentation when you have questions about common tasks like this. It's almost guaranteed you're not the first one to try to solve this problem.
> 1 votes

---
Tags: unity, angles
---


# Question
Title: How can I implement a Boardgame.io project using Webpack?
I am following the boardgame.io tutorial, but I do not want to use either of the two implementation options covered in the tutorial (React and Parcel).

The tutorial requires a framework or bundling method because the client web application has dependencies on node.js modules which cannot be directly imported into browser scripts.

# Answer
> 1 votes
This tutorial is derived from the official Boardgame.io Tutorial. It uses Webpack as an alternative to using React or Parcel.

# Tutorial

This tutorial walks through implementing a simple game of Tic-Tac-Toe.

## Setup

We’re going to use node.js modules with our web client, so we’ll need to use some kind of build system to compile our code for the browser. In this version of the tutorial, we will use Webpack to package the javascript code our web client needs into a single file `dist/main.js`

Let’s create a new Node project from the command line:

```
mkdir bgio-tutorial
cd bgio-tutorial
npm init -yes

```

We’re going to add boardgame.io and Webpack modules to help us build our app:

```
npm install boardgame.io
npm install --save-dev webpack webpack-cli

```

Now, let’s create a basic HTML page that will load our app:

**index.html**:

```
<!DOCTYPE html>
<html>
  <head>
    <title>boardgame.io Tutorial</title>
    <meta charset="utf-8" />
  </head>
  <body>
    <div id="app"></div>
    <script src="./dist/main.js"></script>
  </body>
</html>

```

Next, create a basic http-server to share our html and javascript files:

**server.js**:

```
const PORT = 3004;

const fs = require('fs');
    http = require('http');

http.createServer(function (req, res)
{
  console.log(`Request for url:${req.url}`);

  if (req.url == '/')
    req.url = '/index.html';

  fs.readFile(__dirname + req.url, function (err,data) {
    if (err) {
      res.writeHead(404);
      res.end(JSON.stringify(err));
      return;
    }
    res.setHeader('Cache-Control', 'no-store');

    if (req.url.endsWith('.js'))
      res.setHeader('Content-Type', 'text/javascript');

    res.writeHead(200);
    res.end(data);
  });
}).listen(PORT);

console.log(`Server started on port ${PORT}`);

```

Create a `src` folder to hold our game files:

```
mkdir src

```

Our completed project directory will look like this:

```
bgio-tutorial/
├── dist
│   └── main.js
├── index.html
├── node_modules/
├── package-lock.json
├── package.json
├── server.js
└── src/
    ├── App.js
    └── Game.js

```

## Defining a Game

We define a game by creating an object whose contents tell boardgame.io how your game works. More or less everything is optional, so we can start simple and gradually add complexity. To start, we’ll add a `setup` function, which will set the initial value of the game state `G`, and a `moves` object containing the moves that make up the game.

A move function receives the game state `G` and updates it to the desired new state. It also receives `ctx`, an object managed by boardgame.io that contains metadata like `turn` and `currentPlayer`. After `G` and `ctx`, moves can receive arbitrary arguments that you pass in when making the move.

In Tic-Tac-Toe, we only have one type of move and we will name it `clickCell`. It will take the ID of the cell that was clicked and update that cell with the ID of the player who clicked it.

Let’s put this together in `src/Game.js` to start defining our game:

**src/Game.js**:

```
export const TicTacToe = {
  setup: () => ({ cells: Array(9).fill(null) }),

  moves: {
    clickCell: (G, ctx, id) => {
      G.cells[id] = ctx.currentPlayer;
    },
  },
};

```

> NOTE: The `setup` function will receive `ctx` as its first argument. This is useful if you need to customize the initial state based on some field in `ctx` — the number of players, for example — but we don’t need that for Tic-Tac-Toe.

## Creating a Client

We’ll start by creating a class to manage our web app’s logic in `src/App.js`.

In the class’s constructor we’ll create a boardgame.io client and call its start method to run it. **src/App.js:**

```
import { Client } from 'boardgame.io/client';
import { TicTacToe } from './Game';

class TicTacToeClient {
  constructor() {
    this.client = Client({ game: TicTacToe });
    this.client.start();
  }
}

const app = new TicTacToeClient();

```

Let’s also add two scripts to `package.json` to make serving the web app simpler:

**package.json**:

```
{
  "scripts": {
    "webpack": "webpack-cli --mode=development src/App.js",
    "start": "node server.js"
  }
}

```

Pack our classes and packages for distribution to client browsers:

```
npm run webpack

```

Open port 3004 on your firewall if necessary. On my CentOS 8 server I run:

```
sudo firewall-cmd --zone dmz --add-port 3004/tcp
sudo firewall-cmd --zone dmz --add-port 3004/tcp --permanent

```

You can now serve the app from the command line by running:

```
npm start

```

You should now be able to view the site in your browser. If you started the server on the same machine, just browse: `http://localhost:3004`

Although we haven’t built any UI yet, boardgame.io renders a Debug Panel. This panel means we can already play our Tic-Tac-Toe game!

You can make a move by clicking on `clickCell` on the Debug Panel, entering a number between `0` and `8`, and pressing `Enter`. The current player will make a move on the chosen cell. The number you enter is the `id` passed to the `clickCell` function as the first argument after `G` and `ctx`. Notice how the `cells` array on the Debug Panel updates as you make moves. You can end the turn by clicking `endTurn` and pressing `Enter`. The next call to `clickCell` will result in a “1” in the chosen cell instead of a “0”.

> Note: You can turn off the Debug Panel by passing `debug: false` in the `Client` config.

# Next Steps

This is the end of the WebPack-specific content of the tutorial. You can now complete the "Plain JS" version of the official tutorial continuing from the Game Improvements section.

---
Tags: javascript, node.js
---


title: RayCasting with Mode7

text:
# Question
Title: RayCasting with Mode7
I'm trying to join the mode7 algorithm with RayCasting. For mode7, I'm using a simple rotation matrix to implement the rotation. The result is a little strange and I can't fix it. Do you know what is the problem of the alignment of the algorithms? See the gif below to understand:

The code I'm using is:

```
function mode7() {
    let _x = 0;
    let _y = 0;
    let z = 0;
    let sin = Math.sin(degreeToRadians(data.player.angle));
    let cos = Math.cos(degreeToRadians(data.player.angle));
    for(let y = data.projection.halfHeight; y < data.projection.height; y++) {
        for(let x = 0; x < data.projection.width; x++) {
            _x = ((data.projection.width - x) * cos) - (x * sin);
            _y = ((data.projection.width - x) * sin) + (x * cos);

            _x /= z;
            _y /= z;

            if(_y < 0) _y *= -1;
            if(_x < 0) _x *= -1;

            _y *= 8.0;
            _x *= 8.0;

            _y %= data.floorTextures[0].height;
            _x %= data.floorTextures[0].width;

            screenContext.fillStyle = data.floorTextures[0].data[Math.floor(_x) + Math.floor(_y) * data.floorTextures[0].width];
            screenContext.fillRect(x, y, 1, 1);
        }
        z += 1;
    }
}

```

Is there someway or a tutorial to teach how to fix this issue? I tried to find it but i didn't find anyone about RayCasting with mode7.

# Answer
I assume you're using 8.0 for scaling here?

```
 _y *= 8.0;
 _x *= 8.0;

```

The scaling needs to take account the current horizontal FOV and viewport/screen width. I've found that if your FOV is 90 degrees using (ViewWidth/2) as the scaling factor works well.

If it's not 90 degrees FOV, you can approximate it via

```
90.0/fov * (ViewWidth/2)

```
> 0 votes

---
Tags: javascript, rendering, graphics-programming, raycasting
---


title: Declaring Keycodes as strings

text:
# Question
Title: Declaring Keycodes as strings
How do I declare the keycodes as strings instead of selecting the keys from a list? Such that the user can input a key in inspector window and it will be read?

```
public string StringKey = "a";

void Update () {

   if (Input.GetKeyDown (KeyCode.StringKey)) {

   }

```

# Answer
As Phillipp mentioned, `Enum.Parse`, I used the following and it worked:

```
if (Input.GetKeyDown((KeyCode) System.Enum.Parse(typeof(KeyCode), StringKey))) {
...

```
> 1 votes

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


# Question
Title: Unity facebook sdk 'Didn't find class "com.facebook.FacebookContentProvider"' any more fixes / workarounds for this?
How to replicate this error...

* Create a new Unity project.
* Import the facebook sdk unitypackage
* Set your App Id for facebook via Facebook\Edit Settings
* Using Assets\External dependency manager\Android, press 'Resolve dependencies', then press 'delete resolved libraries' (otherwise the build will fail at the gradle stage)
* Build and run.
* When the app tries to run I immediately get the error message on my phone 'app has stopped working' and see this error in the logs ...

```
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.facebook.FacebookContentProvider" on path: DexPathList[[zip file "/data/app/com.SandwichGeneration.MakeASquare--nLEHpzOYlwW6XKmGzPfIw==/base.apk"],nativeLibraryDirectories=[/data/app/com.SandwichGeneration.MakeASquare--nLEHpzOYlwW6XKmGzPfIw==/lib/arm64, /data/app/com.SandwichGeneration.MakeASquare--nLEHpzOYlwW6XKmGzPfIw==/base.apk!/lib/arm64-v8a, /system/lib64, /system/vendor/lib64]]

```

Suggested fixes I've tried from here

1. I've tried different combinations of old or new facebook sdks and old or new versions of Unity.
2. I've tried building from a few different machines to different Android devices.
3. I've deleted the external dependency manager included with the facebook sdk and used this one instead. In order to get this one to resolve I had to set a 'Custom Gradle Properties Template'in the player setting under publishing settings.
4. I've set a Custom Proguard file'in the player setting under publishing settings, and I added the following two lines to the file..

```
-keep class com.facebook.internal.* {*;}
-keep class com.facebook.* {*;}

```

So I've tried all the suggested fixes and various combinations thereof. I dont know what more I can do. Can anyone suggest anything else to try?

# Answer
Ok heres one specific method I followed where it worked.

* Unity version: 2019.3.15f1
* Facebook SDK version: 7.21.2
* Using the PlayServicesResolver, Resolve libraries
* **Do not** Delete Resolved Libraries
* Set a Custom Proguard file in the player setting under publishing settings, and add the following two lines to the file..

```
  -keep public class com.facebook.**{public *; }
  -keep public class com.facebook.internal.**{ public *; }

```
* Comment out these lines from mainTemplate.gradle

```
     com.android.support:appcompat-v7
     com.android.support:support-v4
     com.android.support:customtabs

```

So your mainTemplate.gradle will look something like this...

```
    `// Android Resolver Repos End
    apply plugin: 'com.android.library'

    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation 'com.google.android.gms:play-services-ads-identifier:17.0.0'
    // Android Resolver Dependencies Start
        //implementation 'com.android.support:appcompat-v7:25.3.1' // Facebook.Unity.Editor.AndroidSupportLibraryResolver.addSupportLibraryDependency
        //implementation 'com.android.support:support-v4:25.3.1' // Facebook.Unity.Editor.AndroidSupportLibraryResolver.addSupportLibraryDependency
        //implementation 'com.android.support:customtabs:25.3.1' // Facebook.Unity.Editor.AndroidSupportLibraryResolver.addSupportLibraryDependency

        implementation 'com.facebook.android:audience-network-sdk:6.0.0' // Assets/IronSource/Editor/ISFacebookAdapterDependencies.xml:8
        implementation 'com.facebook.android:facebook-applinks:[7.1.0, 8)' // Assets/FacebookSDK/Plugins/Editor/Dependencies.xml:6
        implementation 'com.facebook.android:facebook-share:[7.1.0, 8)' // Assets/FacebookSDK/Plugins/Editor/Dependencies.xml:8
        implementation 'com.android.support:cardview-v7:25.3.1' // Facebook.Unity.Editor.AndroidSupportLibraryResolver.addSupportLibraryDependency
        implementation 'com.facebook.android:facebook-gamingservices:[7.1.0, 8)' // Assets/FacebookSDK/Plugins/Editor/Dependencies.xml:9
        implementation 'com.parse.bolts:bolts-android:1.4.0' // Assets/FacebookSDK/Plugins/Editor/Dependencies.xml:4
        implementation 'com.facebook.android:facebook-core:[7.1.0, 8)' // Assets/FacebookSDK/Plugins/Editor/Dependencies.xml:5
        implementation 'com.facebook.android:facebook-login:[7.1.0, 8)' // Assets/FacebookSDK/Plugins/Editor/Dependencies.xml:7
        implementation 'com.google.android.gms:play-services-ads:19.4.0' // Assets/IronSource/Editor/ISAdMobAdapterDependencies.xml:8
        implementation 'com.google.android.gms:play-services-ads-identifier:17.0.0' // Assets/IronSource/Editor/IronSourceSDKDependencies.xml:17
        implementation 'com.google.android.gms:play-services-basement:17.2.1' // Assets/IronSource/Editor/IronSourceSDKDependencies.xml:25
    // Android Resolver Dependencies End
    **DEPS**}`

```
> 0 votes

---
Tags: unity, android, facebook
---


# Question
Title: Get all supported resolutions for a monitor
I've been receiving complaints from users that my game doesn't support the 16:10 aspect ratio.

Currently I list everything in `Screen.resolutions` in a dropdown and allow the user to pick from that. I have since come to the understanding that the first element is not necessarily the native resolution of the monitor.

I've found the Display class but this appears to only give the native resolution, not all scaled resolutions. E.g. if the monitor is 1920x1080 then I need a list of 1600x900, 1280x720, 640x360 etc.

I thought about just multiplying by some scale factor but then I'm afraid I'll get something obscure like 885x497.8. And if I have a pre determined list of resolutions for a specific aspect ratio, how do I support obscure aspect ratios like widescreen for example.

# Answer
> I've been receiving complaints from users that my game doesn't support the 16:10 aspect ratio.

You should get a more specific description of the problem. It could be that the game allows the player to select such resolutions, but the game does not look right. And that would be a different problem. You should check if your game is not stretching elements on wide screen, and that it is positioning UI elements correctly. Notice also that the perspective camera field of view is vertical, thus you may see more or less to the sides depending on the resolution.

You can try by going to the game tab on the Unity editor, on the top you will see a drop down (it says Free Aspect by default), you can change it to test your game in different aspect ratios, at the end of the list there's is a plus option to add your own. You can add an aspect ratio (select aspect ratio instead of fixed resolution) such as 16:10, or a fixed resolution such as 1680:1050.

---

> I've found the Display class but this appears to only give the native resolution

It should give you both the "native"※ (`Display.systemWidth`, `Display.systemHeight`) and the current resolution (`Display.renderingWidth` , `Display.renderingHeight`). *`Screen.currentResolution` is the resolution of the screen even when windowed, while (`Display.renderingWidth` , `Display.renderingHeight`) is the resolution of the game, which may not match the screen resolution when windowed.*

※: I believe Unity falls back to the configured resolution on Windows when native resolution information is not available. This means that the monitor could support a higher resolutions than Unity says.

> not all scaled resolutions

`Screen.resolutions` should give you all supported resolutions (according to Unity). You can filter that list to those that have the same aspect ratio as the native resolution (if that is what you want). To do that, iterate over `Screen.resolutions`, compute the aspect ratio, and compare it to the aspect ratio of the native resolution.

By the way, if all you want is the native resolution first, you can start the list with the native resolution taken from `Display`, followed by all the resolutions from `Screen.resolutions`. You compare each one with the native resolution so you can skip adding that one twice.

---

> I thought about just multiplying by some scale factor but then I'm afraid I'll get something obscure like 885x497.8

You can ignore all not integer resolutions. In fact, if you want to use divisors of the native resolution, you want to only use common divisors of the horizontal an vertical resolutions. To find the common divisors, get the gcd (greatest common divisor) with Euclid's algorithm, get get the divisors of the gcd iterating from `1` to `sqrt(gcd)` and doing a simple divisibility test (eg. `if (n % i == 0){/*...*/`}).

---

Since you only intent on supporting Windows platforms, you could sidestep Unity, and use the Windows API. *You can also filter by aspect ratio if that is what you want.*

First you need to get the device name. To do that, call `EnumDisplayDevices`, to which you pass a pointer to a `DISPLAY_DEVICEA` structure to be populated.

Once you have your device name, you can call `EnumDisplaySettings` or `EnumDisplaySettingsEx`. You will do multiple calls, each time with a different value of `iModeNum` starting at 0 and incrementing, until the call fails. Each call gives you the information of a supported mode of the monitor in a `DEVMODEA` structure. Your resolution are the fields `dmPelsWidth` and `dmPelsHeight`.

You can change the resolution with `ChangeDisplaySettings`.

You can get the P/Invoke declaration from PInvoke.net. There is also a complete example on Stackoverflow: How to list available video modes using C#?. See also the article Dynamic Screen Resolution by sreejith ss nair at Code Project.

*If you are going to be doing a lot of P/Invoke, you might be interested in a library that makes that easier, such as dahall/Vanara.*

---

Perhaps the solution to your problem is simply to allow the player to type the desired resolution, and then change to that. You can write a coroutine that reads the resolution waiting for a change. If the resolution not changed after a while (say 5 seconds), we can assume it failed.

If the change succeeded, then wait for user input to confirm or revert (ESC). *In particular, if you use `ChangeDisplaySettings` to change the resolution you may end up with a black screen, in which case the player would want to revert (traditionally by pressing ESC) to get back to a supported resolution.*

---

One more thing, you may want to figure out the minimum playable resolution for your game and not offer anything below that (in particular if you are going with the divisors of the native resolution).

*Anecdotally I can tell you that I can change the resolution of my monitor to 320:240, even though that is not listed anywhere. The minimum listed by both Windows API and Unity is 640:480. The minimum on Windows configuration is 800:600 (there are ways to modify that list, but that is another tale).*
> 1 votes

---
Tags: unity, resolution, screen, screen-management
---


# Question
Title: How to access and change a Tilemap's Order in Layer?
I'm making a game about two ghosts, and an important thing that I want to add is the possibility to pass through walls. I have managed to make the passable behaviour and everything.

Next, I need to change the Tilemap's Order in Layer number. That's because I want to add some things inside the Tilemap that should be shown until player passes the wall. The way I though of to do this is to decrease the tilemap's layer order when the player is inside it, and put it back to the previous value when player exits.

# Answer
> 1 votes
I solved my problem with `GetComponent<TilemapRenderer>().sortingOrder = x;`

---
Tags: unity, tilemap
---


# Question
Title: How to fix lag in 64 bit Android devices
My game's FPS drops to 30 - 8 FPS on any 64 bit Android device but is at 59 - 60 FPS on an even lesser 32 bit Android device.

I've tried unchecking Development Build on Build settings and I've tried disabling debug calls on my game by using:

```
void Update ()
{
#if UNITY_EDITOR
if(!Debug.unityLogger.logEnabled)
    Debug.unityLogger.logEnabled = true;
#else
if(Debug.unityLogger.logEnabled)
    Debug.unityLogger.logEnabled = false;
#endif
}

```

But there wasn't any change. And I tried setting all Stack Trace Log type to None(Edit \> Project Settings \> Player). Also no change.

PS: I used that update call because there are other imported assets that call the Debug class and I wouldn't want to mess around with their classes.

EDIT: As you can see in the screenshots below, the device that runs the game at less than 30 FPS(every 64 bit device) has Gfx.WaitForPresentOnGfxThread take 71.6% of the frames and RenderPipelineManager.DoRenderLoop\_Internal() takes up 51.1%. While the device that ran the game at 60FPS(every 32 bit device) has RenderPipelineManager.DoRenderLoop\_Internal() take up the most frames with 35.7% of the frame. How should I fix the frame rate drop on the 64 bit device?

EDIT: The 32 bit Android device is an Infinix Hot 4, 2GB RAM, 1.3GHz quad-core MediaTek MT6580 CPU, OpenGLES2, Android 7.0, 1280x720. - This reaches a maximum of 62FPS(Average 59FPS).

The 64 bit Android devices are:

1. Cubot X19 - 4GB RAM, \[8 core CPU: 4x 2.3 GHz ARM Cortex-A53, 4x 1.65 GHz ARM Cortex-A53\], OpenGLES3, Vulkan supported, Android 9.0, 2160x1080. - This reaches a maximum of 30 FPS(Average 25FPS).
2. Qubo P19 - 3GB RAM, 1.5GHz Quad-Core MT6739WA CPU, OpenGLES2, OpenGLES3 supported, Android 9.0, 1280x640. - This reaches a maximum of 25FPS(Average 19FPS).

I'm using Unity 2019.3.1f for my project.

# Answer
> 1 votes
Since the GPU was obviously handling too much work on the 64 bit devices, I decided to allow my project to use only the OpenGLES2 API instead of including OpenGLES3 and Vulkan also since the 32 bit device I tested with supported only OpenGLES2. I didn't change anything else and I've got 70 - 60FPS on the 64 bit devices.

---
Tags: unity, rendering, performance
---


# Question
Title: Android LibGDX game: Choosing starting activity
I am making a Android game with LibGDX (using ADT eclipse bundle). How do I choose the default activity to launch when the user opens the app. I set the project up with the LibGDX setup GUI, and I can't find the main activity. I want a main menu to open before the game starts, is there something I should change in the manifest? Thanks in advance.

# Answer
If you are using LibGDX, you need to forego the concept of Activities and Views, since your entire game will now just be a single Activity. To have a main menu when you game starts up doesn't switch the Activity, but just presents a different set of objects to be rendered to the same Activity.

The easiest way to accomplish this would be to do the following. You should have a .java file in your -core project named after your game name. It would be a class extending `ApplicationListener`. Now, change it to extend `Game` instead, which should be in the package `com.badlogic.gdx`. If you look at the logic of the `Game` class, you will see it has a `setScreen` function. Once a `Screen` has been set, it simply passes all the method calls like `render()` and `resize()` to a given screen.

Thus, to have different screens, just create a new class that extends `com.badlogic.gdx.Screen`. You can do this for any number of screens you need (e.g., MainMenuScreen, GameScreen). Whenever you need to switch screens (e.g., going from Main Menu -\> Game), you can just call the `setScreen` function from your game.

The reason why you should take this approach, and not mess with the manifest.xml and adding additional activities, is because in this way your game is cross-platform. Your main menu will not just be specific to the Android build, and can be used across desktop, ios, and html too.
> 7 votes

# Answer
try to invalidate cache first.Then try other options
> 0 votes

---
Tags: android, libgdx
---


# Question
Title: How can I raycast between two moving objects in Unity?
How can I raycast between two moving objects?

I want to raycast from a moving enemy to a moving player. I dont know how to actually code to make the direction work.

```
using UnityEngine;
using System.Collections;

public class Enemy_Manage_Two : MonoBehaviour {

    public GameObject player;

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

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

        player = GameObject.FindGameObjectWithTag ("Player");
        //Debug.Log (player.transform.position + " " + transform.position);

        Ray ray = new Ray (transform.position, player.transform.position);
        RaycastHit hit;

        Debug.DrawRay (transform.position, player.transform.position,
            Color.red);

        if(Physics.Raycast(ray, out hit)) {
            gameObject.renderer.material.color = Color.blue;
        } else {
            gameObject.renderer.material.color = Color.white;
        }
    }
}

```

# Answer
http://docs.unity3d.com/ScriptReference/Ray.html

This shows us that ray takes 2 parameters; an origin( the place the ray is being cast from ), and a *direction*. This is where your code is wrong, you pass in the enemy position for an origin, and pass in the player's position for the direction.

A direction should be a normalised vector. To get the direction from one point to another, you must subtract the origin position from the target position and then normalise. So, your code would end up like this:

```
Vector3 direction = ( player.transform.position - transform.position ).normalized;
Ray     ray       = new Ray( transform.position, direction );

```

We get the vector difference between the player and the enemy( the vector between the player and enemy ), then we normalise so the vector is of unity length and only describes a direction. Using that and an origin, Ray can figure out that it must shoot from *origin* towards *direction*.
> 1 votes

# Answer
Subtract to get the position difference:

```
/**
 *  Show ray between two points
 */
void ShowRayBetweenPoints (Vector3 p1, Vector3 p2)
{
    Debug.DrawRay (p1, (p2 - p1), Color.yellow);
}

```
> 0 votes

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


# Question
Title: Does swap buffer with vsynch guarantee synchronization?
I was wondering if I could assume that all buffer related GPU operations such as:

* glDrawElements
* glBufferData
* glSubBufferData
* glUnmapBuffer

are guaranteed to be completed after swap buffer is performed (i.e. frame is finished) assuming vsync is on.

I'm confused as I've come across implementations of vertex streaming techniques such as rond robin vbo which imply that a vbo could still be in use during the next frame.

What I basically want to do is stream vertices through glMapBufferRange with GL\_UNSYNCHRONIZED\_BIT, managing the correct ranges myself so that writes and reads never overlap. This would work very well if I could just assume synchronization and reset the stream range index at the end of the frame.

In other words, does swap buffer with vsynch guarantee synchronization?

# Answer
> 1 votes
SwapBuffers and vsync aren't part of OpenGL so this behaviour would be implementation-dependent (or more correctly, windowing system dependent).

If you want to guarantee synchronisation then use glFinish, it's what it's for. Alternatively issue a GL command that can't run until synchronisation happens - anything that needs to read back from the GPU is normally a good bet.

For your specific use case, the usage pattern is known in D3D land as no-overwrite/discard, and has been well-known there for 20-odd years. Just append new data to previously-written data, and if the buffer fills orphan it and begin again at the start of the buffer.

---
Tags: opengl, glfw
---


# Question
Title: What does it mean to develop a VR game from the ground up?
Some virtual reality games are advertised as being created from the ground up for virtual reality. What does this mean exactly?

What are some of the differences between developing a 3d pc game and a vr game?

# Answer
> 2 votes
**Controls**

Games for PC are often develop with keyboard and mouse in mind. That is not the usual interface for VR games.

Even if we treat a VR controller as a pointing device, the expectation is that you will have one on each hand, and you would use them to interact with the game world in a believable manner.

For example, you may do a key-press to open a door in a PC game… on a VR game, it is expected that you actually reach with your VR controller to interact with the door (and yes, we need to consider that the play might limited real space to play). For another example, if a PC game you would press a key to reload your weapon, on a VR game you do a gesture to pull a magazine and you put it in the gun.

Similarly, while the mouse is often the solution to control the camera in a PC game, on a VR game the expectation is that you move your head. *Will come back to the camera.* Yet, while we are talking about controls, you don't have buttons to agree or disagree on a dialog, but a good alternative is to gesture with your head.

A much bigger consideration is locomotion. On a PC game, you probably just press W to move forward. But moving around in a VR game is a design challenge that must be considered from the start. A common solution is to have teleportation in the game. Other solutions include placing the player inside a vehicle so that they can navigate by controlling the vehicule, making the game on rail (as in rail shooters), having the whole game in a small area (for example defending against waves or enemies), or using some gesture to move around (e.g. moving the VR controllers as if you were skiing, or as if you were playing maracas running).

---

**Camera**

Your VR game is very likely going to be first person. That is the player expectation. And while any 3D PC game could be modified to support a VR headset, a VR game has some extra considerations…

In particular, we want to set a confortable head height for the player. And this often means that there will be calibration step.

Another expectation of VR games is that the control of the camera (moving your head around) will never be taken away from the player. And that means that when you are playing a cut-scene, the player must still be able to look around. And this increases the challenge of making sure the player pays attention to what we want as game designers.

Plus, as designers it is more interesting to do exposition in a diegetic way (and rely somewhat less on the cinematic language, and avoid not diegetic HUDs and menus). *Sudden camera cuts, or things floating in midair can break the immersion.*

In fact, keep in mind that a person is experiencing the game in a headset. You could get the player disoriented, dizzy (some people are more susceptible to that than others), or simply with a bad headache.

---

Ultimately, if you are designing for VR, you want to provide a good experience for VR players. When a game is advertised as being created from the ground up for virtual reality, they are promising a good experience for VR players, or at least one better than simply having support for playing a PC game with a VR headset.

---
Tags: game-design, software-engineering, virtual-reality
---


# Question
Title: Inverse Distance Weighted interpolation between N Vector3s in Godot
I have a number of Vector3s in Godot arranged in a grid, let's say they look like this (looking at them from above, with Godot Y-is-up):

```
z
|(0,6,2) (1,5,2) (2,3,2)

|(0,2,1) (1,A,1) (2,3,1)

|(0,2,0) (1,3,0) (2,4,0)
--------------------------x

```

I would like to interpolate the center Y-value marked as A based on the surrounding vectors. The thing is, the center value is not bound to the grid, so it can be closer to the lower left corner for example, so I want to weight the interpolated value based on the distance to each vector.

So, is there some clever trick in Godot using built in functions, or do I need to implement my own Inverse Distance Weighting-code?

# Answer
> 0 votes
I believe you'll have to implement your own code. Perhaps the `Vector3` functions `cubic_interpolate` or `linear_interpolate` will help.

---
Tags: godot, interpolation
---


# Question
Title: How camera works in 2d platformer in level transitions
I want to know how Camera works in game of Celeste.

Currently what I have is, camera follows the player using interpolation:

```
cameraPosition = cameraPosition + (playerPosition - cameraPosition) * 0.1;

```

and I clamp the camera position to the edge of the world size:

```
cameraPosition = mu.clamp(cameraPosition - [160, 90], 0, worldSize);

```

I subtract `[160, 90]` to center the camera.

This works OK. But is that all there is to it.

Specifically, how does the camera work between room transitions.

I might drop room transitions, and just do a black screen transition between levels, but I've heard there is camera triggers that offset the camera relative to player position, and what other tricks are used?

# Answer
Start with a simple refactor: the camera does not follow the player. The camera follows a target. Make the target the player. The game should behave exactly as it does right now.

*You will want to use interpolation, which you already do.*

Instead of doing `player.Position - camera.Position` you do `target.Position - camera.Position`. And `target` happens to be equal to `player`.

Next refactor: Take `target.Position - camera.Position` into a separate variable. We want to know when the camera is close enough, and when it is far from the target. That will be useful later. Taking that into separate variable should leave the game with exactly the same behavior.

Next, we want to define rooms. You will probably want some structure to hold your rooms (unless they are all the same size). How do you define the rooms is of little importance, as long as we can keep track of the room in which a position is. Naive approach will be a list of rects, more involved solutions usually use tree structures (see Space Partioning).

So, we will not only have the `target.Position`, but also a `targetRoom`. Why is this important? Because we will clamp the camera to the `targetRoom`. *And the game should behave exactly the same way as it does now.*

Now, for the grand reveal: When the `target.Position` is close enough to the edge of the `targetRoom`, you want to set a global flag that indicates we are in a transition (we will not clamp while that flag is set. User input will be disabled. Also halt enemies or any other thing you deem pertinent). Next, change the `target` to a temp object on the next room, and change the `targetRoom` to that other room. Remember we have interpolation? Ta-da! the camera interpolates to the position on the next room.

Once the variable we extracted (`target.Position - camera.Position`) is small enough (for some definition of small), you can set the `target` to `player` again. `targetRoom` was already updated, and clamping will be done for the new room.

---

Offset the camera relative to player position? Sure. For example, if the player holds down for two seconds we can give the camera a target below the player. Now the camera interpolates to that target, and the result is that the player can see further down. When the player releases down, we set the target to the player again.

Furthermore, if you want to do a flyby of a room, or you want to take control of the camera for a cut-scene… Well, you can move the target of the camera following a predefined path. The movement does not have to be relative to the player.

---

You probably want a slightly different strategy hide loading scenarios. A battle tested solution is to have a small corridor (Variants of this include elevators, tunnels, bridges), so you can dynamically load the next scenario and unload the prior one while in the corridor. *It is also good for pacing, creating anticipation for the next level, and a small moment of respite after a challenging scenario.* Having camera transitions from room to room, and not only from and out the loading corridor, will further hide when loading will happen.

*And who says that the corridor has to be empty or that nothing happens there? Some games use it as an opportunity for character moments or exposition. Or you can put some health pickups, so healing when starting a new scenario is a little more diegetic. Stuff like that.*
> 2 votes

---
Tags: 2d, javascript, camera, platformer
---


# Question
Title: How to prevent audio files and particle system from playing automatically when loading the game?
I am using Unity. I have attached an audio-file (via Audio Source) to an empty object. I will play the game this plays automatically. The same is happens with the particle system. I would like to know how to prevent this from occurring.

Thanks in advance.

# Answer
Untick the Play on start tickbox, or something similar.

Please read the docs before you start doing anythin in Unity or in any game engine!
Makes your life a whole lot easier!
> 0 votes

---
Tags: unity
---