# Question
Title: Playing a game as it's downloading, how do they do it?
I always believed this was a feature only mobile games had, until I played world of warcraft and guild wars 2

To give you and example Tera Online takes 48 hours to download and completely instal if you don't have optic fiber internet.

But for WOW you literally just click on the .exe file and the game starts instantly, no need to install anything....the game downloads and installs the files you need as you are logging in and creating a character.

Is this possible in Godot? Has anyone ever did it using Godot?

# Answer
> 29 votes
I'm aware of a few games that do this, although none made with Godot. With that said, yes, this is possible in Godot.

---

You will have a background `Thread`, which goes down a list of data files to download, and downloading them.

With Godot, your first option for data files is pck files.

When you export a Godot game, Godot makes a pck file with all the `Resource`s of the game... Godot loads and access this file using `res://` paths.

You can create custom pck files from Godot using the `PCKPacker` class. And you can load custom pck files in runtime with `load_resource_pack`.

See also:

Beyond pck files, you have some other options:

* You can also work with Godot file formats. On that note, using the binary formats for release (i.e. don't use `.tres` use `.res`, and don't use `.tscn` use `.scn`) will result in smaller file size.
* Addendum: Godot 4 can also save and load glb/gltf file in runtime using `GLTFDocument`.
* You can create your own formats. To add support to load them and saving them, create an `EditorPlugin` that installs custom `ResourceFormatLoader` and `ResourceFormatSaver`. Errata: The `EditorPlugin` should not be necessary for this use case.

---

Whatever your data files are, you will make them available for download from the server. If it is a web server, your game can download them using HTTP client class.

*A multiplayer server might be able to send serialized `Resource`s (including scripts). But I'll remind you that you cannot send instances.*

*I'll also remind you that the `res://` paths are a representation of the contents of the pck files. So you don't download into there (as a matter of fact, the `res://` are not writable in release). Instead you download the data files into `user://` paths, and load them from there.*

*By the way, you can have different data files for different platforms, different languages, or whatever criteria you deem appropriate.*

---

As you can imagine, the player might want to interact with something that is not ready.

You can use the order of the data files in the list of the server to make that situation less likely.

But to actually deal with the incident, you want a module that loads scenes on demand... If the scene is not available, queue the appropriate data file for download instead... And wait (which might mean showing a "loading" screen). And the background `Thread` should focus on whatever that module has queued.

---

I presume you don't want a "loading" screen...

Be aware that after downloading, the game needs to load the data files. And also loading and instancing the scenes takes time. So downloading the data files is not enough on its own to remove load times.

What you want is to load adjacent regions in a background process. And also unload distant regions.

See Background loading for Godot 4, or Background Interactive loading for Godot 3. *You can use `Area`(`2D`/`3D`) for load triggers.*

And to be able to load adjacent regions, the game will first demand them from the module I described before. That will also result in in downloading the associated data files early.

And thus the situation where the player tries to interact with something that is not ready (where you need the "loading" screen) is even less likely... But we cannot completely rule it out. For example, in the case of a network disconnection... In a multiplayer game, you would have the player reconnect. But in a single player game, it would be a "loading" screen.

---

You would release the game with whatever the data files need to work. But if loading a data file requires loading another first, your games needs to know the order. So you would have to annotate it in the server.

I want to point out that a bit of duplication is acceptable. For example, if the common dependency is a few functions, it is not worth it to create a data file for them. Instead duplicate them in the data files that need them.

---

Finally, you might also want to incorporate updates and integrity checks. In fact, it is a good idea to do this in the first release to avoid future headaches.

So you annotate in the server the version of the data files, so the game can check if it has the latest one. And also annotate a hash of the data files. So the game can do the hash, and compare the result with the server, without downloading the data file.

You could also use binary diff patches for the data files... In this case, the client would download the diff to update instead of doing a full download. Which results in downloading less data for an update. Yet, this is beyond the question.

# Answer
> 1 votes
I'm not entirely sure which approaches are most common in practice, or how it's done in Godot, but to answer the title in the question:

On a highly oversimplified level, the 3 ways one could allow players to play a game before they've fully downloaded it is:

1. **Before you play, download the things you need in the early game. While you play, download the things you need later.**

You'd need to have resources for the starting area to start playing, but you probably won't need some late-game or end-game area until you've played for quite a while.

If a player gets to a part of the game that hasn't been completely downloaded yet, you may need to force them to wait at that point. Or you could just restrict access to areas that haven't been fully downloaded yet.
2. **Before you play, download things required for play. While you play, download optional things.**

You can probably get by without some background textures or custom cosmetics, for example.

Some of these things could be silently added once it's done downloading (like background textures for any new areas you load), while others would unlock certain functionality or items (like custom cosmetics).
3. **Before you play, download simplified versions of things. While you play, download the full versions.**

This could apply to graphics, for example: you could download low-res graphics before you start, and download high-res graphics while you play.

You could silently replace the simplified versions with the full versions when e.g. players change areas.

Any of these can be done in batches of different sizes (from a single batch for everything, all the way to roughly every object being it's own batch), where the batch is applied to the game once it's finished downloading. More batches may be more complex (since you'd need to decide which batches to have), but it means a player can start playing earlier and there's less risk of getting into a situation where a player wants to do something they're not able to do yet, and/or the player ends up seeing full versions of things and being able to access optional content sooner (which would hopefully improve the player experience). This is especially relevant to slow connections.

---
Tags: godot-4, installer, godot-3
---


# Question
Title: How to paint a circle of pixels so that at diameter=3 the result is a cross shape?
I have a pixel art brush and a canvas. When the brush size is 3, I want to draw a cross shape instead of a 3x3 square.

I implemented the following formula: if the distance between two points is less than or equal to the radius, paint in the pixel.

The problem is, the distance between the center point and the corner pixel is sqrt(2), or 1.4, while the radius is 1.5. I am not sure how to solve this.

# Answer
Look:

Here you see a Circle of 1.5 radius. So it barely touches the outside of the 3 by 3 grid.

Now, you are checking a point that is `(1, 1)` from the center of the circle. Where is that? That is the center of one of the corner cells of the 3 by 3 grid. And yes, that point is inside the circle.

Notice that only the center cell is fully inside the circle.

You want some criteria that will include the side cells but not the corner cells (making a cross). Well, observe that:

* Most of the corner cell is outside.
* Only one of the corners of the corner cell is inside. But the side cells have two corners inside.

Checking corners of the cell is easier. You would check four points for the cell:

* `(0.5, 0.5)` from the center, which is inside (distance is 0.707107... \< 0.5).
* `(1.5, 0.5)` from the center, which is outside (distance is 1.58114... \> 0.5).
* `(0.5, 1.5)` from the center, which is outside (distance is 1.58114... \> 0.5).
* `(1.5, 1.5)` from the center, which is outside (distance is 2.12132... \> 0.5).

Checking how much of the cell is inside is harder, but also more interesting, because you could use it to shade the cells proportionally.

You can reach an approximation by checking an array of points inside of the cell. In fact, checking the four corners is a first approximation.

But we can do better by cutting some corners. Once you know which corners are inside, you also know which sides does the circle cut. Then by computing the intersection of the circle with the sides, you can get this approximation:

You would have to identify which case it is based on which corners are inside. The area inside the segments drawn should be simple to compute. And the missing area is a circular segment, so you can apply the formula for that.

---

I doubt you would need to go into figuring out how much of each pixel is inside the circle for your use case. Checking the corners should be sufficient.

You might also be interested in Midpoint circle algorithm, Marching squares.
> 2 votes

# Answer
One thing you could do is continue to use the formula you currently are, but tweak the radii. For example, a circle of diameter 2 (radius 1), or anywhere between radius 1 and radius \\$\sqrt{2}\\$, will hit exactly the pixels you want, if properly centered:

Subtracting 1 will not be desirable for arbitrarily large circles since it would lead to them always having a 1-pixel nub on 4 sides, but perhaps you could subtract 0.5, or have a table of “fudge factors” applied to specific very small circle sizes, set to whatever makes each size look good.
> 0 votes

---
Tags: mathematics, pixel, pixel-art
---


# Question
Title: How to support Texture Tiling + Offset for custom shader
I've written a custom shader (with help) and I'm not sure why it does not have tiling & offset capabilities. What is the simplest way to add that feature to my shader?

*current shader code*

```
// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'

Shader "Custom/RadarTile"
{
    Properties {
        _MainTex ("Base (RGB) Trans (A)", 2D) = "black" {}
    }

    SubShader {
        Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
        //LOD 100 // todo: may need to go up after bump map added @jkr

        ZWrite Off
        Blend SrcAlpha OneMinusSrcAlpha
        // Blend One SrcAlpha

        Pass {
            CGPROGRAM
                #pragma vertex vert
                #pragma fragment frag
                // #pragma multi_compile_fog

                #include "UnityCG.cginc"

                uniform float2 _Tiling;
                uniform float2 _Offset;

                float _EdgeUVEpsilon;

                sampler2D _MainTex;
                sampler2D _RadarFrame2;
                sampler2D _ReflectivityLUT;
                float _FrameInterpolationAmount;
                float4 _ShadowColor;

                sampler2D _NextTex;
                float _PlaybackTime;
                float _PlaybackPosition;
                int _TotalFrames;
                int _FirstFrameIndex;
                int _LastFrameIndex;

                #include "inc/TileBender.cginc"

                v2f vert(appdata v)
                {
                    // v2f output = vertBender(v, _EdgeUVEpsilon);
                    // return output;

                    // v.texcoord *= _Tiling;    // Apply tiling
                    // v.texcoord += _Offset;    // Apply offset

                    return vertBender(v, _EdgeUVEpsilon);
                }

                float4 frag (v2f i) : SV_Target
                {
                    fixed4 col = lerp(tex2D(_MainTex, i.uv), tex2D(_RadarFrame2, i.uv), _FrameInterpolationAmount);
                    col = saturate(pow(col, 1.0/2.2));
                    col = tex2D(_ReflectivityLUT, float2(col.r, 0));

                    if (col.a > 0) return _ShadowColor; // comment out to disable shadows @jacksonkr_
                    return 0;
                    // return col.a > 0 ? _ShadowColor : 0;

                }
            ENDCG
        }

        Pass {
            CGPROGRAM
                #pragma vertex vert
                #pragma fragment frag
                // #pragma multi_compile_fog

                #include "UnityCG.cginc"

                float _ReflectivityHeightMultiplier;
                float _EdgeUVEpsilon;

                sampler2D _MainTex;
                sampler2D _RadarFrame2;
                sampler2D _ReflectivityLUT;
                float _FrameInterpolationAmount;

                float3 _LightDirection;
                float3 _LightColor;
                float _NdotlEffect;
                float _RadarLightAttenuation;
                float _Roughness;
                float _Vibrance;

                #include "inc/TileBender.cginc"

                v2f vert(appdata v)//appdata_tan_ v)
                {
                    v2f output = vertBender(v, _EdgeUVEpsilon);

                    //this is a bit of a roundabout way to get here, but I have to work around the tile bending code so we're going with it -BH
                    float reflectivity = tex2Dlod(_MainTex, float4(output.uv, 0, 0)).r;
                    float4 offsetWorldPosition = float4(output.worldPos + output.norm * reflectivity * _ReflectivityHeightMultiplier, 1);
                    output.pos = UnityObjectToClipPos(mul(unity_WorldToObject, offsetWorldPosition));

                    //normal calculation
                    const float e = 1.0 / 129.0;
                    if(output.uv.x <= _EdgeUVEpsilon + e || output.uv.x >= 1 - _EdgeUVEpsilon - e || output.uv.y <= _EdgeUVEpsilon + e || output.uv.y >= 1 - _EdgeUVEpsilon - e)
                    {
                        return output;
                    }

                    /*
                    //tangent
                    float2 tangentUV  = v.uv + float2(e,0);
                    float3 tangentSamplePoint = v.position + v.tangent * e;
                    float3 tangentWorldPosition = mul(unity_ObjectToWorld, tangentUV);
                    float3 tangentNormal = normalize(tangentWorldPosition);
                    reflectivity = tex2Dlod(_MainTex, float4(tangentUV, 0, 0)).r;
                    tangentWorldPosition = tangentWorldPosition + tangentNormal * reflectivity * _ReflectivityHeightMultiplier;
                    float3 tangent = normalize(tangentWorldPosition - offsetWorldPosition);
                    //binormal
                    tangentUV = v.uv + float2(0, e);
                    tangentSamplePoint = v.position + cross(v.normal, tangent) * e;
                    tangentWorldPosition = mul(unity_ObjectToWorld, tangentUV);
                    reflectivity = tex2Dlod(_MainTex, float4(tangentUV, 0, 0)).r;
                    tangentWorldPosition = tangentWorldPosition + tangentNormal * reflectivity * _ReflectivityHeightMultiplier;
                    float3 binormal = normalize(tangentWorldPosition - offsetWorldPosition);
                    //final calc
                    output.norm = -cross(tangent, binormal);
*/

                    return output;
                }

                float4 frag (v2f i) : SV_Target
                {

                    fixed4 col = lerp(tex2D(_MainTex, i.uv), tex2D(_RadarFrame2, i.uv), _FrameInterpolationAmount);
                    col = saturate(pow(col, 1.0/2.2));

                    const float3 precipitationTypeThresholds = saturate(pow((float3(255, 200, 150) - 0.5)/ 255.0, 1.0/2.2));

                    float v = 0;
                    if( col.a > precipitationTypeThresholds.x)
                    {
                        v = .67;
                    }
                    else if(col.a > precipitationTypeThresholds.y)
                    {
                        v = .34;
                    }
                    else if(col.a > precipitationTypeThresholds.z)
                    {
                        v = 0;
                    }
                    col = tex2D(_ReflectivityLUT, float2(col.r, v));

                    //minnaert shading implementation
                    float3 viewDirection = normalize(_WorldSpaceCameraPos.xyz - i.norm * _EarthRadius);
                    float3 cameraSpaceLightDirection = mul(unity_CameraToWorld, normalize(_LightDirection));

                    float NdotL = max((1 - _NdotlEffect), dot( i.norm, cameraSpaceLightDirection));
                    float NdotV = max(0, dot( i.norm, viewDirection ));

                    float3 minnaert = saturate(NdotL * pow(NdotL * NdotV, _Roughness));

                    float3 lightingModel =  minnaert * col.xyz;
                    float3 attenColor = _RadarLightAttenuation;
                    col = float4(lightingModel * attenColor, col.a);

                    //vibrance
                    half average = (col.r + col.g + col.b) / 3.0;
                    half maximum = max(col.r, max(col.g, col.b));
                    half vibrance = (maximum - average) * (-_Vibrance * 3.0);
                    col.rgb = lerp(col.rgb, half3(maximum, maximum, maximum), vibrance);

                    // float4 blend = tileblend(i, col);
                    // return blend;

                    return col;

                }
            ENDCG
        }
    }
}

```

*TileBender.cginc*

/**
// Upgrade NOTE: excluded shader from DX11; has structs without semantics (struct v2f members worldPos)
#pragma exclude_renderers d3d11
 * this cginc helps bend shaders to a sphere
 */

// #define PI_5 1.5707963267948966192313216916398f
// #define PI 3.1415926535897932384626433832795f
// #define PI2 6.283185307179586476925286766559f
// #define QUARTER_PI 0.7853981634

// float _TileOverlap;
// float _TileBlendFactor;
float _ShadowOffset;

struct appdata {
    float4 pos: POSITION;
    float2 uv     : TEXCOORD0;
    float4 normal : NORMAL;
};

// struct appdata_tan_ {
//     float4 position: POSITION;
//     float2 uv    : TEXCOORD1;
//     float4 normal : NORMAL;
//     float4 tangent : TANGENT;
// };

struct v2f {
    float4 pos : SV_POSITION;
    float3 norm : NORMAL;
    half2 uv : TEXCOORD0;
    float3 worldPos : COLOR0;
    // UNITY_FOG_COORDS(1)
};

float _EarthRadius;

// #pragma distance from earth

void procDistFromEarth(inout v2f o) {
    float4 offsetWorldPosition = float4(o.worldPos - _ShadowOffset * o.norm, 1);
    o.pos = UnityObjectToClipPos(mul(unity_WorldToObject, offsetWorldPosition));
}

// #pragma vertbender

// v2f vert(appdata v)
/**
 * bends the vertices to fit a sphere shape @jacksonkr_
 */
v2f vertBender(appdata v, float _EdgeUVEpsilon)
{
    v2f o;

    o.pos = UnityObjectToClipPos(v.pos);
    o.uv = clamp(v.uv, _EdgeUVEpsilon, 1-_EdgeUVEpsilon);
    o.norm = v.normal;
    o.worldPos = mul(unity_ObjectToWorld, v.pos);

    procDistFromEarth(o);

    return o;
}
```

# Answer
> 1 votes
I felt silly posting this question because I knew the answer would be simple.

Here's what was missing

First Pass:

* `float4 _MainTex_ST;`
* v2f vert: `output.uv = TRANSFORM_TEX(v.uv, _MainTex);`

Now tiling & offset work as expected.

citation: https://forum.unity.com/threads/undeclared-identifier-\_maintex\_st.468626/

---
Tags: unity, shaders, hlsl, cg, shaderlab
---


title: Unity Touch Pressure with iOS iPad

text:
# Question
Title: Unity Touch Pressure with iOS iPad
I've implemented this: https://docs.unity3d.com/ScriptReference/Touch-pressure.html. It is always returning 1, which makes me think that touch pressure is not a feature of the device.

The only issue is that the device is an iPad 7th generation, which works with my Apple pencil. My other iPad is an 8th generation. Both devices should provide touch pressure metrics, but they always come back as 1. Am I misunderstanding something about what touch pressure is meant to be here, or is compatibility with a pencil/haptic touch not the same as touch pressure?

If this doesn't work for whatever reason, how can I get touch pressure on an iPad through Unity?

# Answer
Pressure sensitivity for the Apple Pencil is built into the Pencil, not the display. This is fairly common for pressure-sensitive drawing tools.

According to Wikipedia, iPhone generations 6 - X had some models with pressure-sensitive displays, but this feature has been discontinued, and was never used in iPads.

Also, as it says in the documentation that you linked to, you can use `Input.touchPressureSupported` to see if the device has a pressure-sensitive touchscreen.
> 2 votes

---
Tags: unity, mobile, ipad
---


# Question
Title: more math or more animations which one is lighter?
I'm adding a non-strafe mode.

Option 1: Take the walk animation, go into blender, flip all keyframes and apply them into various directions

Option 2: have only 1 walk animation, add a bunch of lerp functions and directional stuff to turn the player's mesh

which one is lighter and more performing?

# Answer
TLDR; it likely doesn't matter, you should use the one that is easier for you, and gets you past this step sooner.

It's a hard to tell exactly what you're trying to do, but it seems like you're concerned with the performance impact of basic arithmetic operations like transforming position and rotation (animations are essentially the same thing).

It's common to worry about these when just getting into development, but the reality is that it's extremely rare that the operations are so complex that one method is noticeably better performing than another. The common saying is "premature optimization is the root of all evil".

If you want to know anyway (I understand) then the best option is always to make a test. Make a separate project or script that does your operation in a huge loop, like 1 million iterations, and measure the clock time before and after. You will likely find that the single operation itself takes so little time that it's not worth worrying about.
> 4 votes

# Answer
What do you think the engine does with the key frames? That's right it interpolates them. So there is math going on anyway.

Thus, unless the Option 2 is overly complicated it is likely to not be a reason to worry.

So, I'll echo Wiley Rush advice: do it the way find it easier.

Afterwards, if it turns out to be a performance problem, you might try the other way and compare and see which is actually better in practice. *But if it is not a problem, stick with what is easier to do.*

---

With that said, I want to give you more options:

* Option 3. Assuming you need a simple transformation you might apply it to the parent `Node3D` (Godot 4)/`Spatial` (Godot 3), this will do for mirror, rotation, scaling, or skewing transformations.
* Option 4: If you can do the math in Godot to do or modify the animation on the fly, then you can also have Godot save the modified animation with a `tool` script running in the editor... So when ruining the game, it is the same as if it were an imported animation.
* Option 5: You can encode the key frames in a texture (e.g. the x coordinate is time, and the y coordinate is vertex index, the RGB channels are XYZ positions/displacements) so that you can use a custom shader do the animation entirely in GPU. *This will win the performance battle (useful in particular for crowd animations), but it is worse usability as we don't have tooling for this.*

*I don't know exactly what you are doing (in particular, why my Option 3 is not your Option 1), but we had plenty of questions about how animations work behind the scenes in this site, and if it is not covered, go ahead and ask.*
> 2 votes

---
Tags: godot-3
---


# Question
Title: How to throw an object using a rotating arm controlled by the player?
*Apologies in advance for my lack of knowledge, I am very new to 3D*

My goal is relatively simple. The player controls an arm and uses the mouse to rotate it around a point. They can hold the mouse button to pick up a ball and then throw it by rotating the arm and letting go of the mouse button. (*See GIF below*)

I've managed to get everything to work except for the "throw" part. Once I let go of the mouse button, the ball simply drops straight down with no velocity. I realized that none of the other parts have any velocity for the ball to inherit since I am only setting the rotation.

How can I affect the velocity of the ball based on the speed of the arms rotation and direction?

The code to rotate the arm:

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

public class ArmController : MonoBehaviour
{

    public float sensX;
    public float sensY;

    private float xRotation;
    private float yRotation;

    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    void Update()
    {

        float mouseX = Input.GetAxisRaw("Mouse X") * Time.fixedDeltaTime * sensX;
        float mouseY = Input.GetAxisRaw("Mouse Y") * Time.fixedDeltaTime * sensY;

        yRotation += mouseX;
        xRotation -= mouseY;

        transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);

    }

}

```

The code to pickup and drop the ball:

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

public class Pickup : MonoBehaviour
{

    public Rigidbody ballRB;
    public Transform ball;
    public Transform grabPoint;
    public Rigidbody pointRB;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            PickUpBall();
        }
        else if (Input.GetKeyUp(KeyCode.Mouse0))
        {
            DropBall();
        }

    }

    private void PickUpBall()
    {
        ball.transform.SetParent(grabPoint);
        ball.transform.localPosition = transform.localPosition;

        ballRB.isKinematic = true;
    }

    private void DropBall()
    {
        ball.transform.SetParent(null);

        ballRB.isKinematic = false;

        ballRB.velocity = pointRB.velocity;
    }
}

```

In the code above, pointRB has no velocity. I believe this is because it is a child of the pivot point which is having its rotation set by the first script. I've been trying for hours to figure out a way to calculate the velocity either using rigidbodies or manually with no luck.

The arm is a child of an empty game object which it rotates around. The grab point is a child of the arm to which the ball attaches.

Thank you in advance for any help!

# Answer
I'm not sure if this will end up being the best answer, but an option that I see is:

Attach a gameobject to the ball or "hand" end of the throwing arm. On this gameobject, attach a script that is constantly reading the change in global position of its gameobject, and divding that by Time.deltaTime to get a constant velocity. Here is a possible sample of this script:

```
Vector3 positionLastFrame;
Vector3 velocityPerSecond;

void checkVelocity()
{
   Vector3 newVelocityThisFrame = transform.position - positionLastFrame;
   velocityPerSecond = newVelocity / Time.deltaTime;
   positionLastFrame = transform.position;
}

```

At time of release, read the velocity value on this script, and apply the force to the ball.

You may find it necessary to "filter" the velocity by averaging its value across multiple frames, so it does not jump around at very high or low frame rates.

I am not an expert on the physics system, but if you need to use it, I think you could put your velocity-per-second value directly into the rigidbody with `myRigidbody.AddForce(velocityPerSecond, ForceMode.Impulse)`. However, I often find that I get snappier movement by moving things via script rather than the physics system.

Note: this method will get you "real" release speeds as if the ball were swinging on a string that was suddenly cut- it will fly in the direction the arm is swinging, not in the direction the arm is pointing. In sports, players throw balls in a complex way that leaves them pointing in the direction they threw, like darts- if you want to mimic this, you will have to decide for yourself how exactly you want the ball to move- following the vector of the arm could be a start.
> 0 votes

---
Tags: unity, physics, rotation
---


title: GPU and CPU mode, how do games do that?

text:
# Question
Title: GPU and CPU mode, how do games do that?
I'm playing a lot of older games lately to learn new stuff, mostly private servers.

A game called metin-2 has the option to use mostly CPU or mostly GPU... in GPU mode the game runs faster and lighter than this actual browser I'm writing from...and I was playing a private server with a ton of players, I'm not exagerating when I say there were at least 500 players all smashed and squeezed tightly in a small city throwing all kind of effects, sounds and skills.

so I was wonder how do they do it

# Answer
> 2 votes
That's hard to answer without knowledge of the code of that particular game, but there are all kinds of ways to have code executed on the GPU instead of the CPU.

CPUs are optimized to handle random new instructions with every operation while GPUs are VERY optimized for doing the same "simple" calculations repeatedly on a huge scale.

I recently made a unity project for visualizing data, like a chart. For each data point, a ball was positioned and given a color according to the data value. I calculated the positions and colors in the game code, which uses the CPU.

When I ran the code on data with thousands of data points, it ran very slowly. Each point had to be located by the CPU and updated every frame, THEN handed to the GPU to be rendered one-at-a-time, and there was a lot of processing overhead for features I didn't need.

To get more performance, I wrote a shader- this is code that runs only on the GPU. I was able to send my data directly to the GPU, and the GPU would draw each ball and add colors itself. It was perfect for my code, and it increased performance massively. My CPU-based code ran at 10fps on a large data set, while my new GPU-based one runs over 600fps with the same data.

---
Tags: 3d, game-design, performance
---


# Question
Title: How to make a backdrop that supports different grid effects?
I am learning UE5 using a course on Udemy, and also trying to build a simple (as I thought) project of myself.

The game is billiards with top-down perspective. I want to make a billiards table that has:

1. Different patterns on different levels. E.g. some levels have a checkered board, some levels have a honeycomb pattern.
2. I want to be able to animate individual cells in the grid. E.g. toggle luminosity, cycle colors. I am also considering playing with geometry in some cases.

My current issue is that there's too much terminology that seems to apply in my case. Decals, textures, materials, static mesh, instanced mesh. I am not sure what I should be looking at.

My current implementation is an actor with `UInstancedStaticMeshComponent` that can have different meshes (hex, cube). I am plucking individual instances into separate `UStaticMeshComponents` when I want to have one-off material.

What would be an approach that would make it easier to build unique levels?

# Answer
> 0 votes
By the looks of it, you are reading about shaders and graphics processing, which is a complicated field that you don't necessarily need for your effects. It might help to think of your backdrop and cell effects as game objects, like the balls- instead of trying to modify anything, you just position and display the right ones. Your "highlighted cell" effect could just be a square beneath the ball. Your pool table doesn't even need to be an object- it could just be one of many flat backdrop images, and your code enables the correct one. You may find that you can achieve visually identical effects with far simpler code.

It's generally a good idea to start with the easiest task possible and add features/animations once it's up and running. I'd recommend working with generic featureless shapes, spending time on basic game logic like the menu, taking turns, keeping score, and physics.

Once you have a built a functioning logic system, you will be much more prepared for the advanced stuff like graphics effects.

---
Tags: shaders, unreal, graphic-effects, unreal-5
---


# Question
Title: How can I get the pressure of a touch in Unity?
Does anyone know how to get the `getPressure` function from the Android API into Unity? Or is there another way I can access the pressure of a touch?

# Answer
Short answer: This doesn't do what you think it does.

> `float pressure` \- A normalized value that describes the pressure applied to the device by a finger or other tool. The pressure generally ranges from 0 (no pressure at all) to 1 (normal pressure), although values higher than 1 may be generated depending on the calibration of the input device.

The `float getPressure(int PointerId)` method is a getter method for the `float pressure` instance variable of the `MotionEvent.Pointer` class. It returns a float between 0 and 1 which represent the 'pressure' from the accelerometer.

The value passed to the function is the id for the pointer (finger?) on the screen. For screens that support multi-touch you will probably want to check each finger/id. You can acquire the id from the `event.getPointerId(index)` object passed to a `MotionEvent` listener.

I do not know Unity myself as I avoid using it. However, you should be able to register an event listener for MotionEvent which is passed an event from which you can call `event.getPressure(index)` where index is between 0 and `event.getPointerCount() - 1` and correspond to each 'finger' or touch point.

When you handle your touch events you can also call event.getPressure(index) for the \[pointer\]index your are handling the event for.

From my understanding of the documentation, it doesn't return how much pressure but rather that pressure was applied. This means that **the only information you will garner from calling this is that a pointer event did indeed occur**, which you already knew if you were handling it.

It seems this may be related to calibration. The screen can be calibrated to require more or less 'pressure' for a 'touch' event to be triggered.

Additional Information: This does indeed use the accelerometer to register the value stored in `float pressure`. What it does is when a finger touches the screen it detects whether or not the device accelerated along the axis that intersects the screen. In other words, when you touch the screen you ever so slightly cause your device to move back. This minute movement may be detected and when it is sets your pressure value for that particular touch. For this reason it may be wise to not rely on the data. I would suspect that if a device is flat on a non-movable/non-moving surface (such as a table or counter) then it probably wouldn't detect this. The device would still detect the touch and trigger the MotionEvent listener but the value gotten from `getPressure()` would probably be 0 and therefor meaningless.

*A bit of additional history and the reason that this method exists. Android, and I suppose Apple, intended or at least hoped that pressure touch interface would be possible. However there, at the time, was no easy way to implement such a device. There are, however, external devices which will return more relevant data (such as a Bluetooth touch pad the touch region detection). I am not positive whether it uses this, but there are now devices coming out that have keyboards that literally rise and fall from the glass. I suspect that this may also use pressure sensitivity.*

Finally, this question is a duplicate of this : https://stackoverflow.com/questions/12414491/getpressure-always-returning-1-0
> 2 votes

# Answer
Unity has had a `Touch.pressure` feature on supported devices since Unity 5.3. However, you will find that very few devices have pressure-sensitive screens.
> 1 votes

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


# Question
Title: What does raylib's "no external dependencies" really mean?
I'm considering making a 2D game with C++ and raylib, targeting windows desktop. One of the attractive features of that framework is that it has "no external dependencies".

However, now that I've set it up and started coding and compiling, I see that the linker requires "-lraylib -lopengl32 -lgdi32 -lwinmm".

So those last three...aren't those external dependencies? If not then what are they really? Do they go by some other terminology?

# Answer
> 5 votes
I *suppose* that when they say "no external dependencies", they actually mean "you won't have to run around the internet downloading, installing and maintaining maybe-not-so-up-to-date esoteric packages", because

* assuming raylib is not a header-only library, linking with `raylib` is the compiled functions/classes of raylib
* `winmm` *"winmm.dll is a module for the Windows Multimedia API, which contains low-level audio and joystick functions. winmm.dll is a system process that is needed for your PC to work properly. It should not be removed.*" (source)
* `gdi32` *"exports Graphics Device Interface (GDI) functions that perform primitive drawing functions for output to video displays and printers. It is used, for example, in the XP version of Paint. Applications call GDI functions directly to perform low-level drawing (line, rectangle, ellipse), text output, font management, and similar functions."* (source)
* `opengl32` This is the interface between applications and the graphics card. Windows will typically supply a basic version, allowing the apps to run, then the graphics card vendors will supply another one to adapt the OpenGL API to how their card actually works.

So, although you do need to link against *some* libraries, you'll only have to download raylib's since the other three are already installed on your computer.

I suppose they could have made it so that they would search for the DLL at run time, without the need to use the (windows) .libs at link time, but it requires a setup a bit more complicated (AFAIK).

# Answer
> 1 votes
They tell you what they mean, the website says this:

> NO external dependencies, **all required libraries included with raylib**

---
Tags: c++, raylib
---


title: How to set attack speed

text:
# Question
Title: How to set attack speed
I was checking the new animation with that Mixamo right I made for combo attacks at various speeds.... and I realized I never thought about how implement it in-game.

Is there a simple, fast and straight forward method to just tell Godot "hey if this player has more attack speed %, then speed up this animation by that same %"?

# Answer
> 2 votes
**You can set the `custom_speed` argument when calling `play`.**

For example, to play an animation at half speed you do this:

```
$AnimationPlayer.play("animation_name", -1, 0.5)

```

Here `custom_speed` is `0.5` (i.e half speed).

*The `-1` is telling the `AnimationPlayer` to use the default blending between animations (these are blending times set in the transitions between animations, by default there is no blending, but you can configure them in the "Edit Transitions" option of the "Animation" menu in he "Animation" panel).*

---

Or if you need more fine control, you can set the `playback_process_mode` to "Manual" so you can use `seek` and `advance` to advance the animation.

---

Be aware that `AnimationPlayer` in Godot 4 has a `speed_scale` property, and in Godot 3 it has a `playback_speed`, which you can use to make all the animations play faster or slower.

So if you cannot use the `play` method, you may react to the `animation_started` signal and set the `speed_scale`/`playback_speed`.

---

I have a couple extra tricks for you:

* You can add a "Call Method Track" to your animation, and use it to set the `speed_scale`/`playback_speed` at the start of the animation. *This won't work for animations from an imported scene (e.g. a gltf model), as you cannot modify those, so...*
* You can make an `AnimationPlayer` that plays animations from another `AnimationPlayer` using an "Animation Playback Track". So you can have another `AnimationPlayer` work as a proxy for the `AnimationPlayer` from the imported scene. Sadly this track does not let you set the speed either, but you might combine it with setting `speed_scale`/`playback_speed` from a "Call Method Track". *With this you won't be able play multiple animations of the same animation player at the same time (for that you need an `AnimationTree`), but it might play multiple animations of multiple different `AnimationPlayer`s in sync.*

---

Sadly there is no way to control the playback speed from an `AnimationTree`. Also be aware that an `AnimationTree` could play multiple animations at the same time, so setting `speed_scale`/`playback_speed` might NOT work as desired.

---
Tags: 3d, animation, rpg, combat, godot-3
---


# Question
Title: In Unity 2021.x.x I cannot change value of array item of scriptableobject on Editor Window
So in Unity 2021.x.x I cannot change value of array item but on 2020.x.x it can change. Below the simple example to explain the problem, I can add an item of `listChildren` but I cannot add an item of `children`. Also I cannot edit string of `testString`

```
[System.Serializable]
public class Test
{
    public string testString;
    public List<GameObject> children;
}

public class BaseResources : ScriptableObject
{

}

public class SimpleTest : BaseResources
{
    public List<Test> listChildren;
}

```

This is my editor window

```
public class ResourcesEditorWindow : EditorWindow
{
    protected SerializedObject serializedObject;
    protected SerializedProperty serializedProperty;
    private BaseResources[] resources;
    protected string selectedPropertyPach;
    protected string selectedProperty;

    [MenuItem("Window/Resources")]
    static void Init()
    {
        // Get existing open window or if none, make a new one:
        EditorWindow window = GetWindow(typeof(ResourcesEditorWindow));
        window.Show();

    }

    protected virtual void OnGUI()
    {
        resources = GetAllInstances<BaseResources>();
        serializedObject = new SerializedObject(resources[0]);

        EditorGUILayout.BeginHorizontal();

        EditorGUILayout.BeginVertical("box", GUILayout.MaxWidth(150), GUILayout.ExpandHeight(true));

        DrawSliderBar(resources);

        EditorGUILayout.EndVertical();
        EditorGUILayout.BeginVertical("box", GUILayout.ExpandHeight(true));

        if (selectedProperty != null)
        {

            for (int i = 0; i < resources.Length; i++)
            {
                if (resources[i].name == selectedProperty)
                {
                    serializedObject = new SerializedObject(resources[i]);
                    serializedProperty = serializedObject.GetIterator();
                    serializedProperty.NextVisible(true);
                    DrawProperties(serializedProperty);

                }
            }
        }
        else
        {
            EditorGUILayout.LabelField("select an item from the list");
        }
        EditorGUILayout.EndVertical();
        EditorGUILayout.EndHorizontal();
        Apply();

    }

    protected void DrawProperties(SerializedProperty property)
    {
        while (property.NextVisible(false))
        {
            EditorGUILayout.PropertyField(property, true);
        }
    }

    public static T[] GetAllInstances<T>() where T : BaseResources
    {
        string[] guids = AssetDatabase.FindAssets("t:" + typeof(T).Name);
        T[] a = new T[guids.Length];
        for (int i = 0; i < guids.Length; i++)
        {
            string path = AssetDatabase.GUIDToAssetPath(guids[i]);
            a[i] = AssetDatabase.LoadAssetAtPath<T>(path);
        }

        return a;

    }

    protected void DrawSliderBar(BaseResources[] prop)
    {
        foreach (BaseResources p in prop)
        {
            if (GUILayout.Button(p.name))
            {
                selectedPropertyPach = p.name;
            }
        }

        if (!string.IsNullOrEmpty(selectedPropertyPach))
        {
            selectedProperty = selectedPropertyPach;
        }

    }

    protected void Apply()
    {
        serializedObject.ApplyModifiedProperties();
    }
}

```

# Answer
> 0 votes
I have read somewhere that Unity move all editor UI from UGUI to UIToolkit. Which make reorderable list not supported when using OnGUI(). You can use UIToolkit to make editor and it's less codes than using UGUI.

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


# Question
Title: Parallax-Scrolling Effect Adding Offset in X-Axis
**What I am trying to accomplish:**

* I want to add a parallax effect to the background of my game.
* I am working in **3D space** with a **perspective camera**.

---

**Why:**

* The reason that I want to add a parallax movement script even though I'm already using a perspective camera, is so I can keep all of my background layers the same scale.
* Rather than dragging different layers further back in the Z-axis, I want to keep all of the layers at the same position in the z-axis so they remain uniform in scale.

---

**The issue:**

* Currently, the code that I am using creates a working parallax effect.
* However, the script is adding an offset in the x-axis to the game object it is attached to.
* The offset amount is based on the variable 'parallaxEffectAmount'.
* When parallaxEffectAmount is 0, the offset issue is gone and the layer is positioned at it's correct x-position in the scene. However, the parallax effect is gone.

---

**The code I am currently using:**

```
public class ParallaxScroll : MonoBehaviour
{

private float startPos;
[SerializeField] Camera cam;
[SerializeField] private float parallaxEffectAmount;

// Start is called before the first frame update
void Start()
{
    startPos = transform.position.x;
}

// Update is called once per frame
void Update()
{
    float distance = (cam.transform.position.x * parallaxEffectAmount);
    transform.position = new Vector3(startPos + distance, transform.position.y, transform.position.z);
}
}

```

---

Is there anyway I can implement a parallax effect for my background layers that will keep their original x-positions in the scene?

Does anyone have a better method of accomplishing this?

Thanks so much for taking the time!

# Answer
I unfortunately have no idea why the previous code I was using did not work. If anyone wants to chime in and explain it at any point, that would be terrific.

However, I went with a different approach and it works perfectly!

Hopefully this code will help someone doing something similar to me in the future:

```
public class ParallaxScroll1 : MonoBehaviour
{

    public float percentX;
    public float percentZ;
    [SerializeField] private Camera cam;
    Vector3 camPrev;

    // Start is called before the first frame update
    void Start()
    {
        camPrev = cam.transform.position;
    }

    // Update is called once per frame
    void LateUpdate()
    {
        Vector3 camPos = cam.transform.position;
        float deltaX = camPos.x - camPrev.x;
        float deltaZ = camPos.Z - camPrev.Z;

        float adjustX = deltaX * percentX;
        float adjustZ = deltaZ * percentZ;

        transform.position = transform.position + new Vector3(adjustX, 0, adjustZ);

        camPrev = camPos;
    }
}

```
> 0 votes

---
Tags: unity, parallax-scrolling
---


title: NullReferenceException. Why?

text:
# Question
Title: NullReferenceException. Why?
I have a line:

```
private void OnTriggerEnter2D(Collider2D collider)
{
   checkID = collider.GetComponent<PartInfo>().ID;
}

```

That PartInfo.cs:

```
using System;
using UnityEngine;

public class PartInfo : MonoBehaviour
{
    [SerializeField] int id = 0;
    GameObject parent = null;

    public int ID { get { return id; } }
}

```

So I see this error on *"checkID ="* line. I don't understand why. Help me understand it, please :)

# Answer
> 0 votes
Yes, Thank you @olivier-jacot-descombes . There was no check for null. I just added

```
if(collider.GetComponent<PartInfo>() != null)
   checkID =...

```

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


# Question
Title: Clamp rotation of a follow camera when its target is falling
I'm using this camera script to follow a cube. The cube has rigid body with gravity enabled. There is a plane on which the cube moves. If it goes off the plane, the cube starts falling. However when it falls, the camera starts rotating in all directions. Here is the script. Is there any way to clamp the rotation so that when the cube falls, the camera moves only in the y direction, with no rotation?

```
[SerializeField] Transform target;
public Vector3 defaultDist = new Vector3(0f, 10, -9f);
[SerializeField] float distDamp = .1f;

public Vector3 velocity = Vector3.one;

Transform myT;

void Awake()
{
    myT = transform;
}

void LateUpdate()
{
    SmoothFollow();

}

void SmoothFollow()
{
    Vector3 toPos = target.position + (target.rotation * defaultDist);

    Vector3 curPos = Vector3.SmoothDamp(myT.position, toPos,ref velocity ,distDamp);
    myT.position = curPos ;

    myT.LookAt(target, target.up);
}

```

# Answer
> 2 votes
You are calling LookAt using Target.up instead of Vector3.up.

LookAt takes that Vector so that it can do natural "turret" rotation. Without it, a regular RotateTowards operation doesn't know which axis to rotate. For example, if you wanted to rotate something to face 180 degrees backwards, the system wouldn't know if you want it to turn only on the Y-axis or do a flip backwards over the X axis while rolling on the Z axis.

When you provide an "up" direction for LookAt, it will swivel along that axis. It allows you to do things like have turrets and wheels on slanted surfaces that swivel correctly- instead of Vector3.up, you use the slanted surface normal.

I ran your code and confirmed that changing Target.up to Vector3.up fixes the rotation issue.

---
Tags: unity, c#, camera, transformation
---


# Question
Title: Why is my Button still interactable even when condition is true?
When `BuyCloth()` is executed, Condition `itemIsBought` is `True`, but the Button is still interactable. Why is that?

```
private bool itemIsBought;

public static int coinAmount;

[SerializeField] private Button btn;

private void Start()
}
 StartCoroutine(CheckUnlockCoroutine());
}

    public void BuyCloth()
    {
        itemIsBought = true;
        Debug.Log("" + itemIsBought);
    }

    IEnumerator CheckUnlockCoroutine()
    {

        while (itemIsBought == false)
        {

            yield return new WaitForSecondsRealtime(.1f);

             if (coinAmount <= 100)
             {
                 btn.interactable = false;
             }
             else if (itemIsBought == true)
             {
                 btn.interactable = false;

             }
            else
            {
                btn.interactable = true;
            }
        }

    }

```

I'm not sure what to do next?

# Answer
> 1 votes
Your line:

```
while (itemIsBought == false)

```

Exits the loop when you set it to true. I'd redo this with a few changes:

1. In BuyCloth() add

```
btn.interactable = false;

```
2. Whenever coinAmount changes, call a SaleUpdate method that checks each item if you can afford it and set interactable to true or false there.
3. Create a public Ready(int currentCoins): set coinAmount, call SaleUpdate, then if already bough set interactable to false. Call this before gameObject.SetActive(true) on this script's GameObject.

1. Or better, but requires a bit more knowledge: You have a ScriptableObject with int CurrentCoins; and in the Ready() function you grab that value for coinAmount. And in BuyCloth() you can subtract the coins from the CurrentCoins.
4. Delete this coroutine entirely.

# Answer
> 0 votes
Unless you're making an idle game where the coins are trickling in every frame, running a loop to check every tenth of a second to see if the state has changed is extremely inefficient. If the player spends 10 seconds thinking about their next move before clicking, your code has run 100 times to check a coin count and purchase status that have not changed since the last check. Multiply this by a dozen buttons all checking for whether they should enable and you've got thousands of redundant method calls for no benefit.

This is the kind of situation where the Observer Pattern is a good fit. It lets your code say "This is the state I'm interested in - let me know when it changes", and then incur zero execution overhead until there's a relevant state change to react to.

Here's an example implementation. First, we separate out a script to handle our current coin inventory (because several other scripts might all care about that):

```
public class Wallet : MonoBehaviour {

    // Make editable in inspector, but not directly settable by other scripts.
    [field:SerializeField]
    public int CoinCount { get; private set; }

    [SerializeField] TextMeshProUGUI _coinDisplay;

    // Expose event to notify observerse when coin count changes.
    public UnityEvent<int> onCoinCountChanged;

    // Any changes to wallet contents must go via this function
    // (passing a negative argument to subtract coins).
    public void AddCoins(int coinsAdded) {
        CoinCount += coinsAdded;
        HandleCoinCountChange();
    }

    void HandleCoinCountChange() {
        // Let everyone who cares about the coin count know the latest value.
        onCoinCountChanged?.Invoke(CoinCount);

        // Update the displayed counter.
        _coinDisplay.text = CoinCount.ToString();
    }

    // Also invoke events correctly if coin count is changed in inspector.
    int _cachedCount;
    void OnValidate() {
        if (CoinCount != _cachedCount) {
            _cachedCount = CoinCount;
            HandleCoinCountChange();
        }
    }
}

```

Then we make another script to put on any button that purchases an item. Note that this script makes no assumption that the item to be bought is "cloth" or that it must cost 100 - so you can re-use the same script for multiple purchasables at different prices.

```
// Put this script on the same object as the UI button to get
// automatic wiring-up of the reference and validation that
// the required button component is present (will create if absent).
[RequireComponent(typeof(Button))]
public class PurchaseButton : MonoBehaviour {

    public bool IsPurchased { get; private set; }

    public bool CanPurchase => (!IsPurchased) && (_wallet.CoinCount >= _cost);

    // Use Inspector to select the Wallet script for this player.
    // (You could use a singleton here, but this supports multiple wallets
    // for e.g. multiplayer games)
    [SerializeField]
    Wallet _wallet;

    [SerializeField]
    int _cost = 100;

    Button _button;

    // Get the attached Button and wire up events automatically.
    // You could do this in the Inspector if you prefer, but this makes set-up
    // a little simpler, and has low overhead for just a dozen or so buttons.
    void Awake() {
        TryGetComponent(out _button);
        _button.onClick.AddListener(TryPurchase);
        _wallet.onCoinCountChanged.AddListener(UpdatePurchaseState);

        UpdatePurchaseState(_wallet.CoinCount);
    }

    void TryPurchase() {
        if (CanPurchase) {
            _wallet.AddCoins(-_cost);
            IsPurchased = true;
            _button.interactable = false;
        }
    }

    void UpdatePurchaseState(int coinCount) {
        _button.interactable = CanPurchase;
    }
}

```

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


# Question
Title: In a 3D projection, how to find 'w' for every y point on the screen
I have a standard 3D rendering pipeline. Let's say I have a camera looking down at a flat plane that represents the floor. (in my game, z = height, so this is a plane where z == 0), and for simplicities sake, the camera is tilted so that floor fills the entire screen (there's no horizon).

I have an unproject function, where I can provide a screen (x,y) pair and get back the point on the floor plane. Let's say I do this once for every y value on the screen. If I then project each of these points, I get the original (x,y) cordinates back, but I can also look at the w value for the projected point. This value is dependent on the height and pitch of the camera, and increases in a non linear way towards the top of the window.

My question is - can I calculate this w value per line without going through the unproject-project process for each line on the screen? The value is seemingly a function of camera height, yaw and screen y, so I feel it must be possible to obtain it directly from these three values via some alegbra.

# Answer
> 0 votes
I'm a shader newbie and not yet an expert on camera properties (still vague on w value, depth?) but I'm more comfortable with the math.

The distance from the camera to your point will be a function of your camera FOV, as well as of course its distance from the ground and rotation.

The Secant function is likely what you are looking for. See this animation. Secant(viewing angle) will return the distance to a point on a plane, as a ratio of the distance between the camera and the plane, where viewing angle is the rotation of the camera, plus one half of the FOV times the distance from the middle of the screen.

For example, with an aspect ratio of 1:1 (so I don't have to assume how your FOV is bound) if your camera has an FOV of 32 degrees, positioned 9 units away from the ground and rotated 40 degrees "upward":

An object at the top middle of the screen is`9 * Secant((40 + 16) * π / 180)` away from the camera. Halfway between the center and bottom of the screen, `9 * Secant((40 - 8) * π/ 180)` units away.

Multiplying by pi / 180 is necessary to convert the angle from degrees to radians, so it will work in Secant. Many libraries have trig functions that operate on degrees as well.

To find objects to the left and right, first add your camera vertical rotation to the vertical FOV angle (which is the distance of your screen point away from the screen center multiplied by half your FOV) into one combined vertical angle. Then your horizontal angle is just like the vertical, but always positive since your camera is not rotated left or right. If the combined vertical angle is 'a', the horizontal angle is 'b', and according to the pythagorean theorem a^2 + b^2 = c^2 where c will be your total viewing angle which you feed into Secant (converting degrees to radians where necessary, and then multiplying the final product by the distance of your camera from the plane).

I hope this helps, and I didn't make any errors (which is very possible).

# Answer
> 0 votes
The `w` value is **meaningless** by itself. In a 3D graphics context, a vector with 4 components (x, y, z, w) usually contains homogeneous coordinates, which are a particular mathematical structure that happens to give us two things we want to do lots of, translation and perspective projection, via matrix multiplication.

Any time you have homogeneous coordinates — usually because you multiplied by some 4×4 matrix, such as your unproject function probably does — you should *usually* convert them to normal Cartesian coordinates before looking at the components.

* To convert homogeneous to Cartesian, divide xyz by w: (x/w, y/w, z/w).

This is often called the “perspective division” when discussing the 3D graphics pipeline, because it's the key step without which you cannot have perspective. But the perspective is really defined by the projection matrix that works on homogeneous coordinates; the division is just *how you exit the world of homogeneous coordinates.*
* To convert Cartesian to homogeneous, add a component that is 1: (x, y, z, 1).

You could also use any factor, like (2x, 2y, 2z, 2), and get the same result, but there is no point in doing that under typical circumstances.

Getting back to your problem: you *don't need to* compute `w` for each line. Perform the conversion from homogeneous to Cartesian, so that you have only `x`, `y`, and `z`; then you will find that `y` and `z` are predictable for each line, and that is all the information you need.

---
Tags: opengl, 3d, mathematics, projection, projection-matrix
---


# Question
Title: Why use Time.deltaTime in Lerping functions?
To my understanding, a Lerp function interpolates between two values (`a` and `b`) using a third value (`t`) between `0` and `1`. At `t = 0`, the value a is returned, at `t = 1`, the value `b` is returned. At 0.5 the value halfway between `a` and `b` is returned.

(The following picture is a smoothstep, usually a cubic interpolation)

I have been browsing the forums and on this answer I found the following line of code: `transform.rotation = Quaternion.Slerp(transform.rotation, _lookRotation, Time.deltaTime);`

I thought to myself, "what a fool, he has no idea" but since it had 40+ upvotes I gave it a try and sure enough, it worked!

```
float t = Time.deltaTime;
transform.rotation = Quaternion.Slerp(transform.rotation, toRotation, t);
Debug.Log(t);

```

I got random values between `0.01` and `0.02` for `t`. Shouldn't the function interpolate accordingly? Why do these values stack? What is it about lerp that I do not understand?

# Answer
See also this answer.

There are two common ways to use `Lerp`:

**1. Linear blending between a start and an end**

```
progress = Mathf.Clamp01(progress + speedPerTick);
current = Mathf.Lerp(start, end, progress);

```

This is the version you're probably most familiar with.

**2. Exponential ease toward a target**

```
current = Mathf.Lerp(current, target, sharpnessPerTick);

```

Note that in this version the `current` value appears as both the output *and* an input. It displaces the `start` variable, so we're always starting from wherever we moved to on the last update. This is what gives this version of `Lerp` a memory from one frame to the next. From this moving starting point, we then then move a fraction of the distance toward the `target` dictated by a `sharpness` parameter.

This parameter isn't quite a "speed" anymore, because we approach the target in a Zeno-like fashion. If `sharpnessPerTick` were `0.5`, then on the first update we'd move halfway to our goal. Then on the next update we'd move half the remaining distance (so a quarter of our initial distance). Then on the next we'd move half again...

This gives an "exponential ease-out" where the movement is fast when far from the target and gradually slows down as it approaches asymptotically (though with infinite-precision numbers it will never reach it in any finite number of updates - for our purposes it gets close enough). It's great for chasing a moving target value, or smoothing a noisy input using an "exponential moving average," usually using a very small `sharpnessPerTick` parameter like `0.1` or smaller.

---

But you're right, there is an error in the upvoted answer you link. It's not correcting for `deltaTime` the right way. This is a very common mistake when using this style of `Lerp`.

The first style of `Lerp` is linear, so we can linearly adjust the speed by multiplying by `deltaTime`:

```
progress = Mathf.Clamp01(progress + speedPerSecond * Time.deltaTime);
// or progress = Mathf.Clamp01(progress + Time.deltaTime / durationSeconds);
current = Mathf.Lerp(start, end, progress);

```

But our exponential easing is *non-linear*, so just multiplying our `sharpness` parameter by `deltaTime` will not give the correct time correction. This will show up as a judder in the movement if our framerate fluctuates, or a change in the easing sharpness if you go from 30 to 60 consistently.

Instead we need to apply an exponential correction for our exponential ease:

```
blend = 1f - Mathf.Pow(1f - sharpness, Time.deltaTime * referenceFramerate);
current = Mathf.Lerp(current, target, blend);

```

Here `referenceFramerate` is just a constant like `30` to keep the units for `sharpness` the same as we were using before correcting for time.

---

There's one other arguable error in that code, which is using `Slerp` \- spherical linear interpolation is useful when we want an exactly consistent rate of rotation through the whole movement. But if we're going to be using a non-linear exponential ease anyway, `Lerp` will give an almost undistinguishable result and it's cheaper. ;) Quaternions lerp much better than matrices do, so this is usually a safe substitution.
> 23 votes

# Answer
I think the core concept missing would be in this scenario A is not fixed. A is updated with each step, by however much along the interpolation that Time.deltaTime is.

So, with A getting closer to B with each step, the total space of the interpolation changes with each Lerp/Slerp call. Without doing the actual math, I'd suspect that the effect is not the same as your Smoothstep graph, but is a cheap way to approximate a deceleration as A gets closer to B.

Also, this is frequently used because B may not be static either. Typical case might be a camera following a player. You want to avoid jerkiness, having the camera jump to a location or rotation.
> 1 votes

# Answer
You are right, the method `Quaternion Slerp(Quaternion a, Quaternion b, float t)` interpolates between `a` and `b` by the amount `t`. But watch the first value, it is not the start value.

Here the first value given to the method is the current object rotation `transform.rotation`. So for each **frame** it interpolate between the current rotation and the target rotation `_lookRotation` by the amount `Time.deltaTime`.

That is why it produce a smooth rotation.
> 1 votes

# Answer
Using Time.deltaTime in Lerping functions ensures that the interpolation happens over a smooth and consistent period of time, regardless of the frame rate of the game. Without Time.deltaTime, the interpolation might be too fast or too slow depending on how fast the game is running.

When Lerping, the "t" value represents the percentage of the interpolation between the two values that should have occurred. By multiplying this value with Time.deltaTime, we can ensure that the interpolation happens at a consistent rate, regardless of the frame rate.

The reason why the values of Time.deltaTime stack is because it represents the time that has passed since the last frame. So if the frame rate is constant, the value of Time.deltaTime will be consistent as well. However, if the frame rate fluctuates, the value of Time.deltaTime will also fluctuate accordingly.
> -1 votes

---
Tags: unity, mathematics, interpolation, lerp
---


# Question
Title: Orthographic Camera is not Occlusion Culling?
In the scene where the occlusion culling is done as desired,

When I change the camera to orthographic, occlusion culling is not done.

(Look at the sphere the red arrow points to on the right)

What should I do?

# Answer
I would recommend checking the settings of the orthographic camera to ensure that the occlusion culling is enabled. This can be done by selecting the camera in the scene and navigating to the "Camera" component in the Inspector tab. From there, expand the "Occlusion Culling" section and ensure that the "Use Occlusion Culling" checkbox is ticked.

If the occlusion culling is already enabled for the orthographic camera, then there may be an issue with the occlusion culling algorithm itself. In this case, I would suggest experimenting with different occlusion culling settings or using a different algorithm altogether. It may also be helpful to consult Unity's documentation or seek advice from other developers on forums or communities.
> 0 votes

---
Tags: unity, culling, occlusion
---


title: How to rotate a plane about its origin?

text:
# Question
Title: How to rotate a plane about its origin?
I am trying to figure out how to rotate a plane about its origin in 3D space. Here is the last iteration of the code I am working with; the plane does not move.

```
using UnityEngine;

public class PlaneController : MonoBehaviour
{
public float speed = 5f; // Speed of movement
public float rotationSpeed = 100f; // Speed of rotation

private void Start()
{
    // Create a new GameObject for the plane
    GameObject plane = new GameObject("Plane");

    // Add BoxCollider component to the plane
    BoxCollider collider = plane.AddComponent<BoxCollider>();
    collider.size = new Vector3(1f, 0.01f, 1f);
    collider.center = Vector3.zero;

    // Set the plane's position and rotation
    plane.transform.position = Vector3.zero;
    plane.transform.rotation = Quaternion.identity;

    // Set the plane as a child of the current GameObject
    plane.transform.parent = transform;

    // Move and rotate the plane based on input
    void Update()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");
        float rotate = Input.GetAxis("Rotate");

        // Calculate movement and rotation
        Vector3 movement = new Vector3(moveHorizontal, 0f, moveVertical) * speed * Time.deltaTime;
        Quaternion rotation = Quaternion.Euler(0f, rotate * rotationSpeed * Time.deltaTime, 0f);

        // Apply movement and rotation to the plane
        plane.transform.Translate(movement, Space.World);
        plane.transform.Rotate(rotation.eulerAngles, Space.World);
    }
  }
}

```

UPDATE:

I updated my code to this, and the plane is still not moving. Any help in what I am doing incorrectly would be greatly appreciated.

```
using UnityEngine;

public class PlaneController : MonoBehaviour
{
    public float speed = 5f; // Speed of movement
    public float rotationSpeed = 100f; // Speed of rotation

    private void Update()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");
        float rotate = Input.GetAxis("Rotate");

        // Calculate movement and rotation
        Vector3 movement = new Vector3(moveHorizontal, 0f, moveVertical) * speed * Time.deltaTime;
        Quaternion rotation = Quaternion.Euler(0f, rotate * rotationSpeed * Time.deltaTime, 0f);

        // Apply movement and rotation to the plane
        transform.Translate(movement, Space.World);
        transform.Rotate(rotation.eulerAngles, Space.World);
    }
}

```

# Answer
I ran your code, but instead of using the Input system I just used a Vector3(.25f, 0.5f, 1f) for the Translate and it rockets away. For `rotate` I just pass a constant float of 2f, and the plane indeed rotates along its y axis. Everything "works". The script is of course attached to a plane object.

Its movement is straight away from its starting position, without any regard to its rotation. That is because you are using `Space.World` in your translate function- if you want the plane to fly in the direction it is facing, you would need to use Space.Self, which is the default value and does not need to be set. The same is also true for Rotate, but it depends what you are trying to accomplish with that.

My first game had objects racing around a central point. At that time I just positioned them away from the center of a parent object which was rotating along the Y axis. If I wanted them to move closer to the inside or outside of the track, I changed the `localPosition` of the child "racer" object. It had very simplified controls but it's an example of the many ways to rotate something around an origin in world space.

If that doesn't allow for complex enough movement, manually calculating a position around a central point based on rotations and a radius involves a good familiarity with trig functions and their relationship to the unit circle. If you understand that Sin gives you Y values and Cos gives you X values of positions along a circle based on an input of your rotation in radians, then you can work out your Z and X positions in unity that way. At that point however, you might find it far easier not to swing your plane around an origin point but rather to just drive it relative to itself, like an airplane, only limiting its range of direction and steering.
> 0 votes

# Answer
The reason why no movement at all is working is that there is no `Rotation` Input. Unity is even telling you this with an error message (which should be included in the question)

How should a rotation input look like? You can always rotate towards a direction, a pure rotation input would be something like a twisting knob and that would fail to get the full rotation to be captured in a single Update.

You can see the full supported input commands under `Edit - Settings - Input` (as per error message)

If you have made a custom `Rotation` Input there, you would need to share that one.
> 0 votes

---
Tags: unity, rotation
---


title: Deferred Shading and material ID

text:
# Question
Title: Deferred Shading and material ID
I am implementing a deferred rendering framework, and I wanted to allow programmers to write custom materials. However, I did not find yet how to handle different materials. For now, a material is just a set of uniforms for me.

I wanted to write the material ID in the GBuffer, however, I don't see the point of doing it as the lightning pass is using the same shader for every fragment (obviously).

In the frosbite paper (page 15), they explain they use a Material ID and a MatDat parameter, but I did not really get what it can be and how they handle it during the lightning pass.

Is the material ID used in a simple branching condition? In this case, when a new material is created, do I have to rebuild the lightning pass uber shader by adding this branching and the code to execute?

UE4 seems to build GLSL code from the material editor, which is not something hard, but how do they handle it with the deferred renderer? Do they only plug the GLSL code into the Uber Shader?

# Answer
> 0 votes
In my renderer I have a material ID that I use to change the material settings of rendered objects that way each object can have a different roughness\metalness\Fresnel\specular color\lighting type.

You don't branch with the mat id you just load a different material and use that when you do your lighting eg.

```
struct RenderMaterial
{
uint vHighlight1Color;
uint vHighlight2Color;
uint vFrontColor;
uint vBackColor;
float fReflectivity;
float vHighlight1;
float vHighlight2;
float ior;
float pointlightspecpower;
float spotlightspecpower;
float sunpower;
float roughness;
float fresneladjust;
bool  GGX;
float ambientpower;
};

Texture2D<uint> RenderMaterialIDs; //written to in my Fill Gbuffer stage
StructuredBuffer<RenderMaterial> RenderMaterials; //Filled on the CPU with all the current RenderMaterials, loaded from disk.

//Loading material from buffer
uint MatID;
MatID = RenderMaterialIDs.Load(uint3(globalIdx.x, globalIdx.y, 0));
RenderMaterial CurrentMaterial = RenderMaterials[MatID];

// Using material data
float alpha2 = CurrentMaterial.roughness* CurrentMaterial.roughness;
float G = G_Smith(CurrentMaterial.roughness, nDotV, nDotL);
fresnelTerm = fresnelTerm * CurrentMaterial.fresneladjust;

float3 spec=CurrentMaterial.GGX ? LightingFuncGGX_OPT3 : CookTorrence

```

I Use a tilebased deferred renderer

# Answer
> 0 votes
Bindless Texturing for Deferred Rendering and Decals

https://therealmjp.github.io/posts/bindless-texturing-for-deferred-rendering-and-decals/

render uv and material id to gbuffer,

then use bindless texture to get all material info in one pass.

---
Tags: opengl, shaders, deferred-rendering
---


# Question
Title: glClearColor prevents text from rendering with freetype using SDL2
I'm trying to add text rendering to my rendering project and am following the OpenGL tutorial at https://learnopengl.com/In-Practice/Text-Rendering I'm using SDL2 as my backend so had to make some adjustments to the provided examples in the tutorial. The strange thing is that when I comment out the 'glClearColor(GL\_COLOR\_BUFFER\_BIT)' line the text rendering works except because I never clear the screen the rendering is all flickery and weird cause I never clear the other buffer. But when I do clear the screen the window looks fine but there is no text.

Edit: Following the suggestion from @TomTsagk in the comments I added GL\_DEPTH\_BUFFER\_BIT to the glClear call and it cause “Hello World!” To momentarily flash when the window opened by still no luck.

Edit 2: The depth buffer was the issue! But because I was never resetting the x-coordinates to render at, it would flash off screen before I could see it.

Here is an extracted minimal example:

```
#include <iostream>
#include <string>
#include <map>

#include "SDL.h"
#undef main

#include "glad/glad.h"

#include "ft2build.h"
#include FT_FREETYPE_H

using sdl_gl_context = void*;

struct Character {

    unsigned int texture_id;
    glm::ivec2 size;
    glm::ivec2 bearing;
    unsigned int advance;

};

std::map<char , Character> characters{};

int main(int argc, char* argv[]) {

    SDL_Window* window = nullptr;

    if (SDL_Init(SDL_INIT_VIDEO) != 0) {
        std::cout << "SDL2 failed to initialize" << std::endl;
        return 1;
    }

    Uint32 flags = SDL_WINDOW_OPENGL;

    window = SDL_CreateWindow("Tests" , SDL_WINDOWPOS_CENTERED , SDL_WINDOWPOS_CENTERED , 1920 , 1080 , flags);
    if (window == nullptr) {
        std::cout << "SDL2 failed to create window" << std::endl;
        return 1;
    }

    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK , SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 6);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER , 1);
    SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE , 8);
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS , 1);
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES , 24);

    SDL_SetWindowMinimumSize(window , 200 , 200);

    sdl_gl_context context = SDL_GL_CreateContext(window);
    if (context == nullptr) {
        std::cout << "SDL2 failed to create OpenGL context" << std::endl;
        return 1;
    }

    SDL_GL_SetSwapInterval(1);

    if (gladLoadGLLoader(SDL_GL_GetProcAddress) == 0) {
        std::cout << "Failed to initialize GLAD" << std::endl;
        return 1;
    }

    glEnable(GL_CULL_FACE);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    glEnable(GL_MULTISAMPLE);

    glClearColor(0.2f , 0.3f , 0.3f , 1.f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

    YE::rendering::Shader shader("shaders/text_shader.vert" , "shaders/text_shader.frag");
    glm::mat4 projection = glm::ortho(0.f , 1920.f , 0.f , 1080.f);

    shader.Bind();
    shader.SetUniformMat4("proj" , projection);

    FT_Library ft;
    if (FT_Init_FreeType(&ft)) {
        std::cout << "Failed to initialize FreeType" << std::endl;
        return 1;
    }

    FT_Face face;
    if (FT_New_Face(ft , "res/fonts/Arial.ttf" , 0 , &face)) {
        std::cout << "Failed to load font" << std::endl;
        return 1;
    } else {
        FT_Set_Pixel_Sizes(face , 0 , 48);
        glPixelStorei(GL_UNPACK_ALIGNMENT , 1);

        for (unsigned char c = 0; c < 128; c++) {
            if (FT_Load_Char(face , c , FT_LOAD_RENDER)) {
                std::cout << "Failed to load glyph" << std::endl;
                continue;
            }

            unsigned int texture;
            glGenTextures(1 , &texture);
            glBindTexture(GL_TEXTURE_2D , texture);
            glTexImage2D(GL_TEXTURE_2D , 0 , GL_RED , face->glyph->bitmap.width , face->glyph->bitmap.rows ,
                         0 , GL_RED , GL_UNSIGNED_BYTE , face->glyph->bitmap.buffer);

            glTexParameteri(GL_TEXTURE_2D , GL_TEXTURE_WRAP_S , GL_CLAMP_TO_EDGE);
            glTexParameteri(GL_TEXTURE_2D , GL_TEXTURE_WRAP_T , GL_CLAMP_TO_EDGE);
            glTexParameteri(GL_TEXTURE_2D , GL_TEXTURE_MIN_FILTER , GL_LINEAR);
            glTexParameteri(GL_TEXTURE_2D , GL_TEXTURE_MAG_FILTER , GL_LINEAR);

            Character character = {
                texture ,
                glm::ivec2(face->glyph->bitmap.width , face->glyph->bitmap.rows) ,
                glm::ivec2(face->glyph->bitmap_left , face->glyph->bitmap_top) ,
                static_cast<unsigned int>(face->glyph->advance.x)
            };
            characters.insert(std::pair<char , Character>(c , character));
        }
        glBindTexture(GL_TEXTURE_2D , 0);
    }
    FT_Done_Face(face);
    FT_Done_FreeType(ft);

    uint32_t vao , vbo;
    glGenVertexArrays(1 , &vao);
    glGenBuffers(1 , &vbo);
    glBindVertexArray(vao);
    glBindBuffer(GL_ARRAY_BUFFER , vbo);
    glBufferData(GL_ARRAY_BUFFER , sizeof(float) * 6 * 4 , nullptr , GL_DYNAMIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0 , 4 , GL_FLOAT , GL_FALSE , 4 * sizeof(float) , 0);
    glBindBuffer(GL_ARRAY_BUFFER , 0);
    glBindVertexArray(0);

    float x = 960.f;
    float y = 510.f;
    float scale = 1.f;

    std::string text = "Hello World!";

    bool running = true;
    while (running) {

        SDL_Event e;

        while (SDL_PollEvent(&e)) {
            switch (e.type) {
                case SDL_WINDOWEVENT:
                    switch (e.window.event) {
                        case SDL_WINDOWEVENT_CLOSE: running = false; break;
                        default: break;
                    }
                break;
                break;
                case SDL_KEYDOWN:
                    switch (e.key.keysym.sym) {
                        case SDLK_ESCAPE: running = false; break;
                        default: break;
                    }
                break;
                default: break;
            }
        }

        // glClear(GL_COLOR_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

        shader.Bind();
        shader.SetUniformVec3("text_color" , { 1.f , 1.f , 1.f });
        glActiveTexture(GL_TEXTURE0);
        glBindVertexArray(vao);

        std::string::const_iterator c;
        for (c = text.begin(); c != text.end(); c++) {
            Character ch = characters[*c];

            float xpos = x + ch.bearing.x * scale;
            float ypos = y - (ch.size.y - ch.bearing.y) * scale;

            float w = ch.size.x * scale;
            float h = ch.size.y * scale;

            float vertices[6][4] = {
                { xpos ,    ypos + h ,   0.f , 0.f } ,
                { xpos ,     ypos ,       0.f , 1.f } ,
                { xpos + w , ypos ,       1.f , 1.f } ,

                { xpos ,     ypos + h ,   0.f , 0.f } ,
                { xpos + w , ypos ,       1.f , 1.f } ,
                { xpos + w , ypos + h ,   1.f , 0.f } ,
            };

            glBindTexture(GL_TEXTURE_2D , ch.texture_id);
            glBindBuffer(GL_ARRAY_BUFFER , vbo);
            glBufferSubData(GL_ARRAY_BUFFER , 0 , sizeof(vertices) , vertices);
            glBindBuffer(GL_ARRAY_BUFFER , 0);
            glDrawArrays(GL_TRIANGLES , 0 , 6);

            x += (ch.advance >> 6) * scale;
        }
        glBindVertexArray(0);
        glBindTexture(GL_TEXTURE_2D , 0);
        shader.Unbind();

        SDL_GL_SwapWindow(window);
        SDL_PumpEvents();

    }

    SDL_GL_DeleteContext(context);
    SDL_DestroyWindow(window);
    SDL_Quit();

}

```

For reference here is when I call glClearColor(GL\_COLOR\_BUFFER\_BIT) in the normal spot

And here is when I comment it out except you have to imagine a horrible flickering

# Answer
> 1 votes
### I think that's a Depth Buffer issue

Looking at your code, I suspect the error is you are not clearing the Depth Buffer every frame.

Replace the following line:

```
// glClear(GL_COLOR_BUFFER_BIT);

```

With

```
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

```

### Why does it happen?

If that's indeed what the problem is, it happens because on the first frame you draw the text on the screen, but because you don't clear the depth buffer, on the next frame the program things the new text is about to be drawn on the same spot as another object (the text of the previous frame) and it skips rendering it as it thinks it won't be visible.

By clearing the Depth buffer, you are basically telling the system, at the beginning of the frame, there's no objects in the scene, so when the text is about to be drawn again, it shouldn't be skipped, as the depth buffer doesn't have any other object on the same position.

## Also: The text's position is not reset

The variable `x` is initialised before the loop:

```
float x = 960.f;

```

Then inside the loop at some point the variable `x`'s value changes:

```
x += (ch.advance >> 6) * scale;

```

However the value of `x` doesn't reset each frame, causing it's value to keep increasing, rendering the text off-screen.

To solve this, you can re-init the variable of `x` at the beginning of each frame:

```
while (running) {
    x = 960.f;
    // ...

```

---
Tags: opengl, sdl2
---


# Question
Title: Animating A 2D Stylized Cloud Programmatically
* I am tiling the following background cloud image horizontally.
* I would like to give it more character by making the top of the image deform.
* I would preferably like the puffs on top to bulge bigger and shrink.
* I'd also like the puffs to slightly jiggle as they deform.
* Is there a good way that I can accomplish this or something similar through code or with a shader?

Thanks for taking the time!

# Answer
Here's a classic and pretty cheap trick you can use called "indirect texturing".

The idea is that we'll read from one texture to calculate a new sampling coordinate, then use that calculated sampling coordinate to read from your cloud texture. This lets us distort the image in all sorts of ways.

First though, we need to do a little preparation. Since the cloud peaks just kiss the top edge of the image, a distorted sample near there could easily cross the wrap-over point and start reading from the bottom of the image that's all solid clouds, which won't look good. So we'll shift the clouds down so the peaks run across the middle of the image, and we have a nice buffer of empty sky above / solid cloud below. While I'm at it, I changed the image to black and white - I'm only going to use it as an alpha mask, and fill in the colour in the shader (saves some file size and texture bandwidth, since we only need 8 bits per pixel).

We'll also need a tiling noise texture to use as a source for the random-looking but slowly-varying undulations we want - something with some blurry cloudy greyscale values. I used this example from Filter Forge for a quick test.

I chose R8 texture format for both textures since I only need a single grey channel. The default texture compression can introduce some nasty artifacts for indirect texturing, where what should be smooth gradients turn into jagged stair steps, so check your texture import settings if you see that.

Then we can write a shader something like this:

```
Shader "Unlit/CloudWarble"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _Noise ("Noise", 2D) = "white" {}
        _Intensity ("Intensity", Range(0, 1)) = 0.23
        _Color ("Colour", Color) = (0.8471, 0.8667, 0.9412, 1)
    }
    SubShader
    {
        Tags { "RenderType"="Transparent" "Queue"="Transparent" }
        LOD 100

        Blend SrcAlpha OneMinusSrcAlpha
        ZWrite Off

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;

            sampler2D _Noise;
            float4 _Noise_ST;

            float _Intensity;

            fixed4 _Color;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                // Compensate for difference in scale between noise swatch and colour swatch
                // and control the scale of the effect from an overall sway to jagged jitters
                float2 noiseUV = TRANSFORM_TEX(i.uv, _Noise);

                // Our first sample will vary the x offset.
                float2 p = noiseUV;
                 // Scroll the noise texture vertically over time to animate the effect.
                p.y += 1.1f * _Time.x;

                // Fetch sample offset from the noise indirect texture.
                float2 shift;
                shift.x = tex2D(_Noise, p).r;

                // Shift our second sample to decorrelate the y from the x.
                p.x += 0.5f;
                // Scroll the other way at a coprime rate, to disguise the temporal pattern.
                p.y = noiseUV.y - 0.7f * _Time.x;

                // Complete the offset, and re-center it (from 0 - 1 to -0.5 - +0.5)
                shift.y = tex2D(_Noise, p).r;
                shift -= 0.5f;

                // Shift our sample coordinate.
                float2 shifted = i.uv + _Intensity * shift;

                // Colour the clouds and take the alpha from the distorted cloud texture.
                fixed4 col = _Color;
                col.a *= tex2D(_MainTex, shifted).r;

                return col;
            }
            ENDCG
        }
    }
}

```

I set up the material like so:

Some notes on the magic numbers I chose (just fiddling by eye):

* Main Texture y scale is less than 1, "zooming in" on the texture slightly so the vertical wrap-around line is shifted out of frame by a safety margin, so that our indirect distortion doesn't peek across that edge.
* y offset is slightly above 0 to shift the texture down and scroll the bottom wrap-around line out of frame.
* x scale is y scale times the aspect ratio of the display quad relative to the cloud texture (here my quad is 8x as long as it is wide, while the texture is 4x, so 8/4 = 2, and 2 * 0.7 = 1.4)
* The Noise scale controls how dense the distortion variation is. The exact values depend on how blobby or grainy your noise texture is. For very small scale values, the distortion ends up almost the same everywhere, and you just get a sway back and forth. As you increase the scale, some parts of the clouds move separate from others. At high values, you'll see lumps and jitters along a single arc, so that's usually a sign you want to back down.
* Because the cloud image is 4x as wide as it is tall, but the noise image is usually square, the noise's x scale is one quarter its y scale to compensate.
> 2 votes

---
Tags: unity, shaders, graphics
---


# Question
Title: Should I use a full shader solution or geometry for vector rendering in OpenGL?
I am trying to create a vector rendering library for OpenGL in Rust. Currently, the goal is to produce nanovg-like rendering. I have found two approaches to doing my rendering:

* The pure shader approach, where I just render a single fullscreen quad in OpenGL, and use shaders draw all my vector shapes
* The pure geometry approach, where I create a canvas, add all my shapes, triangulate the vertices on CPU, then upload the vertices to GPU and render with a basic vertex and fragment shader

For instance, using the pure shader approach, I would potentially use some GLSL code that looks like this:

```
uniform vec2 u_resolution;

vec3 circle(vec2 uv, vec2 center, float radius, vec3 color) {
    float x = sqrt(pow(uv.x - center.x, 2.) + pow(uv.y - center.y, 2.));
    if (x < radius) {
        return color;
    } else {
        return vec3(1., 1., 1.);
    }
}

vec3 rectangle(vec2 uv, vec2 p1, vec2 p2, vec3 color)
{
    if (uv.x > p1.x && uv.x < p2.x && uv.y > p1.y && uv.y < p2.y)
    {
        return color;
    } else {
        return vec3(1.0, 1.0, 1.0);
    }
}

void main() {
    vec2 uv = gl_FragCoord.xy/u_resolution.xy;
    vec3 color1 = circle(uv, vec2(0.3, 0.5), 0.2, vec3(1.0, 0.0, 1.0));
    vec3 color2 = rectangle(uv, vec2(0.3, 0.2), vec2(0.7, 0.5), vec3(0.5, 0.2, 1.0));
    vec3 color = mix(color1, color2, color1);

    gl_FragColor = vec4(color,1.0);
}

```

whereas with the pure geometry approach, I would use some code that looks like this:

```
fn main() {
    let canvas = Canvas::new();
    canvas.addCircle(0.1, 0.2, 0.3);
    canvas.addRect(0.5, 0.2, 4.0, 5.0);
    let vertices = triangulate(canvas.to_vertices());
    // Some general OpenGL code to render some vertices etc.
}

```

However, both approaches seem to have issues - the pure shader approach is very difficult to add a large number of shapes, and the pure geometry approach is hard to get working and possibly not as efficient. Does anyone have any suggestions for an alternate approach?

# Answer
> 1 votes
If you want to be able to scale up to hundreds of shapes or complex shapes like Bézier splines and text glyphs, **geometry is the way to go**. You do not want to write shader functions to describe the shape of each character in an entire font, let alone multiple fonts or multilingual support. And you don't want to have to re-compile the e entire shader every tima a shape needs to change, including all the code for the shapes that didn't change.

Using geometry, each render pays only for the fragments that actually get drawn to, rather than evaluating an increasingly expensive shading function for every empty pixel on the screen. Most shapes won't change every frame/repaint, so the vertices calculated previously can be re-used, keeping the repaint efficient. For large canvases you can also take advantage of culling to avoid revisiting/repainting shapes outside the visible or modified region.

You're not wrong that the geometry approach involves a lot of work, but that work is an investment in scalability. There are also some tricks you can use to render exact, anti-aliased curves within a triangle, rather than densely subdividing curves down to straight-line segments, so the geometry complexity does not get out of hand. Rendering Vector Art on the GPU from GPU Gems 3 is a great resource about this.

Image from GPU Gems 3

---
Tags: opengl, shaders, vector-art
---


# Question
Title: Arrows that deal more damage to targets moving towards them and less to targets moving away
In real life if you shoot an arrow towards a target that is running towards you.

The targets velocity increases the damage that arrow's velocity would cause.

If the target is moving away from the arrow, they will receive less damage from that same arrow.

More powerful bows shoot their arrows faster, and faster arrows not only do more damage but also travel further

And if you shoot an arrow from a horse, the speed of the running horse increases the velocity of the arrow, thus the arrow does more damage.

But I'm mostly interested to know how to account for the target moving away or towards the arrow without using some tab target system, how would one do that?

And most importantly can it be done using shaders to use less CPU? Because two guys shooting each other isn't that heavy, but a rain of arrows like in the movie the 300 Spartans...well that seems more demanding

# Answer
> 2 votes
As TomTsagk said, your damage value will come from subtracting the velocity of the target from the velocity of the arrow. The new value will have a magnitude equal to your damage.

If the arrow was moving the exact same speed and direction as the target, it will subtract to zero and there will be no damage.

If they were moving the same speed toward each other, it will be twice as much damage as if the target had been standing still.

If the target chased the arrow so fast that they ran into it from behind, there would still be damage, because the magnitude of a vector is always positive. You may need to take care so that the tail of the arrow cannot instantly hit the shooter.

In Godot, there is an easy `.length()` method to automatically calculate the magnitude of a vector. Whether you are using Vector2 or Vector3, it is the same:

```
Vector2 arrowStrike2D = (arrowVelocity2D - targetVelocity2D).length();
Vector3 arrowStrike3D = (arrowVelocity3D - targetVelocity3D).length();

```

That is c#. For GDScript, you would not include the semicolons at the end.

For more helpful methods like `.length()` check out the Vector3 page of the Godot documentation here.

# Answer
> 1 votes
### 2D

In a 2D game if the target is moving away from the arrow, you could do something as simple as take the arrow's velocity, reduce it by the velocity of the target, and use that to calculate damage.

This could look like this (very simplistic example):

```
arrow.velocity = 10; // arrow moves 10 pixels to the right each frame
target.velocity = 6; // target moves 6 pixels to the right each frame

// ...

// at a later point when detecting collisions
impactVelocity = arrow.velocity -target.velocity; // impact velocity would be 4 (10 - 6)

```

So you can then use the `impactVelocity` to calculate damage.

### 3D

I see you've used the `3D` tag. In that case, you might need to do some more math. You can calculate the target's velocity and direction, then based on how much the target is moving away from the arrow, substract that velocity from the arrow's velocity to calculate damage.

This might be a bit more complex to explain here, as the answer can differ greatly for each project. Following the logic for 2D, you can search online on how to calculate an object's direction based on their velocity, and create a custom solution that works for your game.

Hopefully this was enough information to help guide you to the next step.

---
Tags: 3d, opengl-es2, combat, godot-3
---