# Question
Title: How can I morph between images in real time?
So, I need to be able to make a picture slowly transition into another picture, not as a transparency fade, but as a morph.

And I need that in real time.

---

More on "morphs":

When you outline two areas in two separate images which are supposed to turn into each other over a number of animation frames; and then their colors and outlines slowly blend until one image becomes another.

That is what I need.

I was initially hesitant to ask this, because I was under the impression that it has traditionally been a brutal algorithm to force your computer to perform.

# Answer
> it has traditionally been a brutal algorithm to force your computer to perform.

This may have been true when the Elastic Reality software you link to was created in the mid-90s. Back then CPUs were measured in MHz. Today, even your phone is likely 10-20x faster than this, with double to sextuple the cores, not even counting the graphics acceleration hardware. Computers today are more than up to the challenge.

This also isn't something you need a specialized engine feature to support. Modern graphics pipelines are built to be extremely flexible, so you can create this kind of effect for yourself with just a little shader work.

Here's a simple example I cooked up, just to test how far we could get with a fairly naive approach:

(Using a couple of images I had handy - photo of me taken at GDC by James Everett, photo of my roommates' cat by me )

As usual, we'll place pairs of point markers to designate corresponding feature points in each image. More full-featured solutions will work with line segments or Bézier curves, but we can get a pretty decent look with just points for starters.

From these points, I generated a displacement map that encodes the travel each pixel needs to undergo: the red and green channels store the horizontal & vertical displacement for the pixel that starts at this location in the source image, respectively, and the blue and alpha channels store the displacement for the pixel that arrives at this location in the destination image.

Now the work the shader has to do at display time is dead simple. All it needs is the source and destination images, the morph displacement map above, and a progress parameter to set how far through the morph it should display for the current frame. Then each frame, for each rendered pixel, it will:

1. Sample this pixel's location in the displacement map, and decode it from the 0-1 colour space to the -1 to 1 displacement range.
2. Backtrack along the displacement vectors to find which pixel in the source image should have arrived to here. Sample the source image at that backtracked point.
3. Scan ahead along the displacement vectors to find which pixel in the destination image should come from here. Sample the destination image at that look-ahead point.
4. Cross-fade between these two displaced texture lookups.

A sharp reader will note this is a pretty crude approximation. The displacement vectors we look up are only strictly correct at the very beginning and very end of the morph. In-between, we're just counting on the morph map being smooth enough that the vectors we read halfway between our source and destination are "pretty close" to the direction this pixel needs to be moving at this moment in the blend.

If you tried to do a very aggressive shape change this way, the artifacts would likely become very noticeable. But for blending a face to another face at a similar angle, it does pretty OK.

The exact shader code (or graph) will depend on the engine or tool stack you're using, but here's an example of this strategy in Unity ShaderLab:

```
Shader "Unlit/Morpher"
{
    Properties
    {
        _MainTex ("Source", 2D) = "white" {}
        _MainTex2("Destination", 2D) = "white" {}
        _Morph("Morph Map", 2D) = "white" {}
        _MaxTravel("Max Travel", Vector) = (1, 1, 1, 1)
        _Progress ("Morph Progress", Range(0, 1)) = 0
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        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;
            sampler2D _MainTex2;
            sampler2D _Morph;

            float4 _MainTex_ST;
            float4 _MaxTravel;

            float _Progress;

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

            // Simple sigmoid / smoothstep function.
            float sigmoid(float t) {
                return 3 * t*t - 2 * t*t*t;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                // Enable to animate automatically over time, rather than a manual parameter input.
                //_Progress = 0.5f * (1.0f + sin(_Time.x * 10.0f));

                // Decode the displacement vector into the correct range.
                float4 displacement = (tex2D(_Morph, i.uv) - 128.5f/256.0f) * 2.0f * _MaxTravel.xyxy;

                // Biased progress curve that starts and ends slower,
                // and transitions faster in the middle.
                float sig = sigmoid(_Progress);

                // At the start of our morph, the source vectors are more accurate.
                // At the end, the destination vectors are more accurate.
                // So we'll transition from using one set to the other.
                float2 travel = lerp(displacement.xy, displacement.zw, sig);

                // Estimate which source pixel should have arrived to here.
                float2 sourcePos = i.uv - travel * _Progress;

                // Then repeat the estimation in reverse to find our matching destination pixel.
                float2 destPos = i.uv + travel * (1.0f - _Progress);

                // Sample the source and destination textures.
                fixed4 col = tex2D(_MainTex, sourcePos);
                fixed4 col2 = tex2D(_MainTex2, destPos);

                // Cross-fade between the two samples.
                return lerp(col, col2, sig);
            }
            ENDCG
        }
    }
}

```

You can see there's not a lot to this shader. We could probably have hundreds of these rendering simultaneously, even on a modest GPU - the limiting factor is likely to be our texture memory bandwidth for fetching the source/destination photo pixels, not the morphing computations.

That's because we did all the hard work in advance when we built the displacement map.

The strategy for that is:

1. Loop over all the source and destination points, and build a list of displacement vectors that take each source to its destination.

In my version, I also keep track of the maximum displacement in this pass, so I can scale everything relative to this and make maximum use of the limited precision in my colour displacement map.
2. Loop over each pixel in your displacement map.

* For each pixel, loop over all your feature point pairs.
    * Compute the distance of this pixel from the source point of the pair.
    * Turn this distance into a weight that's extremely high at the point itself, and low elsewhere. (I use the inverse squared distance, plus a little epsilon to avoid division by zero)
    * Scale the pair's displacement vector by this weight, and add it to an accumulated sum. Also accumulate the weight itself.
    * After you've processed all the point pairs, divide the accumulated weighted displacement vectors by the accumulated weight. Now you have a weighted average.
    * Convert the vector into the range 0-1 (or 0-255), and store its x & y values in the red and green channels of your texture.
    * Repeat for the blue and alpha channels, except now it's the distance from the destination point in each pair that's responsible for computing the weight.
3. Save/upload your modified texture.

You can see we've got some 3-deep nested loops here, so there's a not insignificant amount of work going on. But even with this naive algorithm running single-threaded, I'm able to process the 48 point pairs to a 256x256 displacement map in less than a second - good enough for design-time texture creation. The effect still holds up even with a tiny 16x16 map, which takes just 3 ms to prepare.

If you needed to, you could divide up parts of the displacement map to different background threads to compute in parallel, or even push the whole thing to the GPU.

More sophisticated approaches to this problem might try subdividing the mesh we're using to display the photos, and displacing the vertices around similar to a 3D morph target. Or using more sophisticated shaders to loop over a list of pairwise displacement primitives and compute a more accurate displacement vector at render time. But this should at least show the spirit of how you can start to produce this kind of effect in the game tech of your choice.
> 8 votes

---
Tags: algorithm, graphic-effects, art, image-effects
---


# Question
Title: Variable not set before reading it error in GameMaker Studio 2
I am following along with a guide. I'm trying to reference code from an instance in my room, but whenever I try to run the script I get this error:

> ERROR in action number 1 of Create Event for object objSmileyFace:
>
> Variable objHealth.(100004, -2147483648) not set before reading it.
>
> at gml\_Object\_objSmileyFace\_Create\_0 (line 4) - objHealth.playerHealth = objHealth.playerHealth + 10;
>
> gml\_Object\_objSmileyFace\_Create\_0 (line 4)

It says objHealth is not set, which is not true. What am I doing wrong?

# Answer
> 2 votes
The `objSmileyFace` object is likely created before the `objHealth` exist.

If you're going to the room where these are defined, check the instance layer and see if both objects are present. and if `objHealth` is called before `objSmileyFace`. (priority depends on the order in the instance layer)

---
Tags: game-maker
---


# Question
Title: Utilize remote PC to Boost UE4 Editor Performance
As the title suggests, I would like to know **how I can take advantage of a desktop PC at my workplace to help boost the performance of the editor on my laptop at home.**

General editor actions such as shader compilation, light building, and terrain generation require large amounts of CPU power and RAM, both of which are much better suited for a desktop PC. **It would be great if there is a service that can allow me to offload the tasks from my laptop to the remote PC.** Unfortunately, directly remoting into that PC does not work for my case.

I am aware of a system known as UnrealSwarm, but have had difficulty finding recent documentation and substantial resources showing it can effectively run jobs other than lightmass rendering.

Please let me know how I can solve my problem!

Thanks in advance!

# Answer
> 0 votes
Swarm is only for building lights since it is often a long, CPU intensive process so Swarm "borrows" spare CPU cycles from other machines it's installed on to speed up the process.

I don't know of any option for general editor work you can use to achieve what you're trying to do besides installing the editor directly onto your work computer and using a remote desktop connection.

---
Tags: shaders, rendering, unreal-4, pc
---


# Question
Title: How can I add word wrap to EditorGUILayout.TextArea?
How can I add word wrap to the editor textarea? I'm trying to mimic the \[TextArea\] attribute (word wrap, automatically increase height when needed)

For some reason GUILayout.TextArea() works fine, but EditorGUILayout.TextArea() doesn't have any word wrap. Here's my code:

```
obj.edibleFlavorText = EditorGUILayout.TextArea(obj.edibleFlavorText, GUILayout.MinHeight(textAreaHeight));

```

I've tried:

* Adding GUILayout.ExpandHeight(true) to its options
* Adding GUI.skin.textArea.wordWrap = true to the start of my editor script

# Answer
> 2 votes
In essence, You need to make sure that the style that is used has wordwrap set to true.

The problem with what you tried is that the style you edited isn't used by the TextArea.

Which style is used is actually a weird one, as I expected EditorStyles.textArea but for some reason, unity uses EditorStyles.textField as the default style instead...(which has wordwrap set to false).

So to fix it, just force it to use the correct style :p

```
EditorGUILayout.TextArea(obj.edibleFlavorText, EditorStyles.textArea);

```

On a side note, If you need to alter a style for one field, I wouldn't advise to change the built in GUI styles as doing that will change the style for ALL components that use that style (unless that is what you're after).

Instead, I would advise to create a copy of an existing style, modify it and use it for the component you want to edit.

So for example

```
        GUIStyle myStyle = new GUIStyle(EditorStyles.textField);
        myStyle.wordWrap = true;
        value = EditorGUILayout.TextArea(value, myStyle);

```

---
Tags: unity, gui, editors, imgui
---


title: World to screen coordinates

text:
# Question
Title: World to screen coordinates
I am trying to translate world coordinates to screen coordiantes, and I am using the following line:

```
Vector3 Vec = cam.WorldToScreenPoint(Input.mousePosition);

```

for some reason the value of `Vec` is (0,0,0). Why is that?

# Answer
If you want to go from screen space (mouse position) into world space, then you're using the wrong method.

If you want to place an object at a particular depth from the camera, you can use this:

```
Vector3 GetMousePositionInWorld(float depth) {
    Vector3 position = Input.mousePosition;
    position.z = depth;
    return Camera.main.ScreenToWorldPoint(position);
}

```

Just be sure you specify a non-zero depth. If you're using a perspective camera, 0 depth from the camera means every mouse position maps to the location of the camera itself (the tip of the view pyramid).

If you want to place an object where the mouse "touches" an object in your scene, you can do this with a raycast or spherecast.

```
Vector3 GetMousePositionOn3DCollider(float maxDistance) {
    var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

    if(Physics.Raycast(ray, out RaycastHit hitInfo, maxDistance)) {
        return hitInfo.point;
    }

    return ray.GetPoint(maxDistance);
}

```
> 1 votes

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


# Question
Title: With Google Admob, how do I handle two different rewards for a rewarded ad?
I'm implementing reward based video ads in my game using Google Admob. There are two functions that provide the reward. One is a ReceiveLife() function where once the player dies, if they click on the revive button the game restarts and the score is set to score before the player dies instead of 0. The other function is ReceivePoints(), where if the player clicks on the add points button, they are rewarded with 100 extra points. I looked at the documentation provided in google admob regarding loading multiple rewarded ads, but I'm unsure of how to go about calling these two functions in the "HandleRewardedAdClosed" function. Here is the code that works for only function (ReceiveLife()):

```
public class AdScript : MonoBehaviour
{
    string Video_Ad_Id = "ca-app-pub-3940256099942544/5224354917";
    private RewardedAd rewardedAd;

    void Start()
    {
        MobileAds.Initialize(initStatus => { });
        RequestRewardBasedVideo();
    }

    public void RequestRewardBasedVideo()
    {
        this.rewardedAd = new RewardedAd(Video_Ad_Id);
        this.rewardedAd.OnUserEarnedReward += HandleUserEarnedReward;
        this.rewardedAd.OnAdClosed += HandleRewardedAdClosed;
        // Other event hooks...
        AdRequest request = new AdRequest.Builder().Build();
        this.rewardedAd.LoadAd(request);
    }

    public void ShowVideoRewardAd()
    {
        if (this.rewardedAd.IsLoaded())
            this.rewardedAd.Show();
    }

    public void HandleRewardedAdClosed(object sender, EventArgs args)
    {
        this.RequestRewardBasedVideo();
    }

    public void HandleUserEarnedReward(object sender, Reward args)
    {
        GameManager.instance.ReceiveLife();
    }
}

```

How do I call two rewarded functions in the HandleUserEarnedReward() function above. Can someone please help?

# Answer
> 1 votes
Your example has a single `RewardedAd` instance. You'll need two if you want to follow Google's documentation. Then when you have two, you can assign different callbacks to each. Something like this:

```
public class AdScript : MonoBehaviour
{
string Video_Ad_Id = "ca-app-pub-3940256099942544/5224354917";
private RewardedAd extraLifeRewardedAd;
private RewardedAd receivePointsRewardedAd;

void Start()
{
    MobileAds.Initialize(initStatus => { });
    extraLifeRewardedAd = RequestRewardBasedVideo(ReceiveExtraLife);
    receivePointsRewardedAd = RequestRewardBasedVideo(ReceivePoints);
}

public void RequestRewardBasedVideo(EventHandler<Reward> rewardCallback)
{
    RewardedAd rewardedAd = new RewardedAd(Video_Ad_Id);
    rewardedAd.OnAdLoaded += HandleRewardedAdLoaded;
    rewardedAd.OnAdFailedToLoad += HandleRewardedAdFailedToLoad;
    rewardedAd.OnAdOpening += HandleRewardedAdOpening;
    rewardedAd.OnAdFailedToShow += HandleRewardedAdFailedToShow;
    rewardedAd.OnUserEarnedReward += rewardCallback;
    rewardedAd.OnAdClosed += HandleRewardedAdClosed;
    RequestAd(rewardedAd);
    return rewardedAd;
}

private void RequestAd(RewardedAd rewardedAd) {
    AdRequest request = new AdRequest.Builder().Build();
    rewardedAd.LoadAd(request);
}

public void ShowReceiveLifeVideoRewardAd()
{
    if (this.extraLifeRewardedAd.IsLoaded())
    {
        this.extraLifeRewardedAd.Show();
    }
}

public void ShowExtraPointsVideoRewardAd()
{
    if (this.receivePointsRewardedAd.IsLoaded())
    {
        this.receivePointsRewardedAd.Show();
    }
}
.
.
.
.
public void HandleRewardedAdClosed(object sender, EventArgs args)
{
    RequestAd((RewardBasedVideoAd)sender);
}

public void ReceiveExtraLife(object sender, Reward args)
{
    GameManager.instance.ReceiveLife();
}

public void ReceivePoints(object sender, Reward args)
{
    GameManager.instance.ReceivePoints();
}

```

An alternative would be to have to different instances of this script, since it is a MonoBehaviour, and use a UnityEvent to dispatch the callback to the correct target, but that's getting a bit more complicated. It would be easily extensible to have anything happen upon receiving a reward, but since you only have these two things, this is probably sufficient.

---
Tags: unity, admob
---


# Question
Title: Why does my game look different on my mobile device than in the editor?
I am new to Unreal Engine. My game in mobile looks totally different than in Unreal Engine editor.

**In Editor:**

**In Mobile:**

Is this a symptom of something obvious? How can I make it so that what I'll see in the editor will be the same thing that I'll see on my mobile device?

# Answer
> 2 votes
It is probably because your project is using a post processing effect that mobile either doesn't support or an asset is missing. When I was using UE4 usually if there is something wrong with materials when exporting to mobile the console would tell me.

This guy had a similar issue: https://answers.unrealengine.com/questions/561835/index.html

---
Tags: rendering, lighting, unreal-4, mobile
---


# Question
Title: Using Euler angles to rotate object 360 degrees
I'm trying to create script that rotates object in given axis by set amount of degrees.

That's my 2 core methods

```
public Vector3 rotation;

public void RotateDegreesFast ()
{
    transform.DOLocalRotate (GetTargetRotation (), rotationTime);
}

private Vector3 GetTargetRotation ()
{
    Vector3 newRotation = new Vector3 (
        rotation.x + transform.localEulerAngles.x,
        rotation.y + transform.localEulerAngles.y,
        rotation.z + transform.localEulerAngles.z)

    return newRotation;
}

```

I was using this script for a little while, it was working perfectly in Y and Z axis. Now I try to rotate object 45 degrees in X axis (`rotation = new Vector3(45f, 0f, 0f)`). It works until rotation in x value equals 135. `Transform.localEulerAngles.x` is returning 45 instead of 135. So it's stuck between 90 and 135 degrees. I was trying to use `transform.localRotation.eulerAngles.x` instead, but it doesn't work as well.

I am aware this works that way because specific Euler angle can be represented in many ways. I also know that DOTween has DOLocalRotateQuaternion method, but the thing is that this component is often reused by a designer that sets value of `rotation` variable in the inspector. It's way easier to use Euler angles for him.

# Answer
> 2 votes
Final code is easier than the one I posted. I just didn't think about doing it this way.

```
public Vector3 rotation;

public void RotateDegreesFast ()
{
    Quaternion newRotation = transform.localRotation * Quaternion.Euler(rotation);
    transform.DOLocalRotateQuaternion(newRotation, rotationTime);
}

```

---
Tags: unity, rotation, quaternion, euler-angles
---


# Question
Title: How to leave trails that are equidistant apart from each other
I want bunch of circles to follow the player while keeping a distance apart. So far I have this:

```
local p = {
  x=0,
  y=0,
  life={
    {x=0,y=0},
    {x=0,y=0},
    {x=0,y=0},
    {x=0,y=0}
  }
}

local last={x=p.x,y=p.y}
for l in all(p.life) do
  l.x = lerp(last.x,l.x,0.5)
  l.y = lerp(last.y,l.y,0.5)
  circfill(l.x,l.y,2,7)
  last={x=l.x,y=l.y}
end

```

But this makes it so the circles collapse into each other and the player. I want the circles to have a distance between themselves and the player.

I've also tried this:

```
  l.x = lerp(last.x*0.8,l.x,0.5)

```

This leaves a distance as I want but the trail is always on the upper left, barely following player.

I want the trail to stay always behind the player.

Probably I can achieve this by stop following if the distance is less than threshold.

# Answer
> 2 votes
I did it by adding a condition before modifying the position of the trail:

```
if vdist(last,l) < 10 then
  // adjust position
end

```

it works now.

---
Tags: javascript, pico-8
---


# Question
Title: How do I record scripted rotation changes in animation file?
I can create an animation file by clicking "Animation", then selecting a gameobject, then press record and then change bone rotations in the Inspector. The animation window will be notified about the bone rotation changes and add this to the animation file like this:

This works fine as long as the Inspector is used to change the bone rotations.

Bone rotations done by a script are not recorded.

Is there a trick to record these bone rotations via script anyways? For example using something like (pseudo-code) this? -\>

```
rShoulder.rotation.dirty = true;

```

For your interest, I have attached the script that I use to rotate the bones and which are not recorded. This script works perfectly fine, but it doesn't trigger animation changes:

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

public class MyPlayer : MonoBehaviour
{
    public Transform Target;

    private void OnGUI()
    {
        if (GUI.Button(new Rect(0, 70, 50, 30), "Transfer rotations to other model with same rig"))
        {
            List<Transform> nTheseTransforms = new List<Transform>();
            Helpers.GetAllChildren(this.transform, ref nTheseTransforms);

            List<Transform> nTargetTransforms = new List<Transform>();
            Helpers.GetAllChildren(Target, ref nTargetTransforms);

            foreach (Transform nThisTransform in nTheseTransforms)
            {
                foreach (Transform nTargetTransform in nTargetTransforms)
                {
                    if (nThisTransform.name == nTargetTransform.name)
                    {
                        nTargetTransform.localRotation = nThisTransform.localRotation;
                        break;
                    }
                }
            }
        }
    }
    public static void GetAllChildren(Transform parent, ref List<Transform> transforms)
    {
        foreach (Transform t in parent)
        {
            transforms.Add(t);
            GetAllChildren(t, ref transforms);
        }
    }

}

```

# Answer
DMGregory kindly pointed to me towards the solution.

The Animation window uses the Undo system to record the changes. The trick is to call

```
Undo.RecordObject(...)

```

on the object that is about to be changed.

At first I tried it with Undo.RecordObject(nTargetTransform, "Rotation"). This didn't have any effect, so I thought this approach would simply not work.

Then I read a code sample here, and they used the argument "Inspector", and that worked. The bone rotations done by script were now being recorded.

Here is the full, working code:

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

public class MyPlayer : MonoBehaviour
{
    public Transform Target;

    private void OnGUI()
    {
        if (GUI.Button(new Rect(0, 70, 50, 30), "Transfer rotations to other model with same rig"))
        {
            List<Transform> nTheseTransforms = new List<Transform>();
            Helpers.GetAllChildren(this.transform, ref nTheseTransforms);

            List<Transform> nTargetTransforms = new List<Transform>();
            Helpers.GetAllChildren(Target, ref nTargetTransforms);

            foreach (Transform nThisTransform in nTheseTransforms)
            {
                foreach (Transform nTargetTransform in nTargetTransforms)
                {
                    if (nThisTransform.name == nTargetTransform.name)
                    {
                        Undo.RecordObject(nTargetTransform, "Inspector");
                        nTargetTransform.localRotation = nThisTransform.localRotation;
                        break;
                    }
                }
            }
        }
    }
    public static void GetAllChildren(Transform parent, ref List<Transform> transforms)
    {
        foreach (Transform t in parent)
        {
            transforms.Add(t);
            GetAllChildren(t, ref transforms);
        }
    }
}

```
> 1 votes

---
Tags: unity, animation
---


# Question
Title: How do I include a blend tree in my controller?
I want my player to aim up and down with a pistol. I have stored an "aim up" pose in one anim file, and I have stored an "aim down" pose in another anim file. I want to blend between these 2 poses according to the mouse pointer on the screen:

* If the mouse pointer is at the bottom of the screen, the blend tree should only play the "aim down" pose
* If the mouse pointer is at the top of the screen, the blend tree should only play the "aim up" pose
* If the mouse pointer is at the middle of the screen, the blend tree should play a 50/50 mix of the "aim down" and of the "aim up" pose

To do that, I have added a 1D blend tree to my animator.

It looks like this:

I have tested the blend tree. When I scrub through the "timeline" using the red line, it works as expected:

Now I wanted to test it out in my game, but I don't see how to set the blend weight of this 1D blend tree.

The docs say that the blend tree is controlled by the animation parameters.

As far as I can see, Unity automatically created one for me when I added the blend tree. The name seems to be "Blend", as can be seen in the screenshot:

The following however has no visual effect for me:

```
_animator.SetFloat("Blend", 1f);

```

To check if this parameter even exists, I have changed its value to 0.3 in the animator.

Then in my code, I check the value like this, and it does return 0.3:

```
float fCur = _animator.GetFloat("Blend");

```

So this is proof that the parameter does exist. However, when I set a new value like...

```
_animator.SetFloat("Blend", 0.56f);

```

... then this value is accepted, but it doesn't have any visual effect, and it doesn't show in the animator's paramters.

Can anybody tell me how I could achieve what I want?

Edit:

I have tested it in a new, stripped-down project. In this new project, I have the blend tree as the default state in the animator, and everything works.

So the fact that my blend tree is NOT the default state in the other project seems to be the problem. This is what it looks like:

I will first try to investigate more on this.

# Answer
> 0 votes
Instead of just putting the BlendTree into the animator and leaving it absolutely disconnected, the blend tree needs to be "conditioned", too.

I have to remove the "PistolAim" state and use the BlendTree instead.

This is what it has to look like instead:

---
Tags: unity, animation, mecanim
---


title: Fully destructibility in 2D

text:
# Question
Title: Fully destructibility in 2D
I would like to create a small game about battles in the Middle Ages. Imagine a procedurally generated 2d map with rivers, fields, and a small castle.

Two sides. One player will attack the castle, and the second player defends it.

The whole game will be with a view - top down. I like this look (and maybe it will simplify the work).

Imagine a player's cannon approaching the castle and attacking it.The cannon fires (e.g., into a tower) and the tower starts to fall apart. How to make this process more interesting? With various effects (for example, to the place where the gun fell off a piece of wall, and on the roof of the tower there was a crack).

I like the process of destruction in AE defenite edition, but it looks the same for all types of buildings (sooner or later they will turn it into the same bunch).

The example what I'm mean when say 2d castle in top down view:

How to break this castle into chips?

**ADD some visual guide:**

enter image description here

# Answer
# Physics

Try to think about what happens when a cannon ball traveling through the air hits something. The ball will have a certain mass and velocity, and thus a certain amount of kinetic energy that can potentially do damage.

What happens with the cannon ball itself after a collision? Does it bounce, fall down, break apart, roll, catch fire or explode? It could bounce (for example, if it hits the ground at a grazing angle), but if it hits a stone wall it is likely to just lose all its kinetic energy, fall down, and maybe roll away.

What happens at the point of impact? A stone wall reacts differently from a wooden roof. And there is a small chance that you hit a person or some piece of equipment. As mentioned by Zibelas, all these things might need to be handled differently.

As for materials that crack when hit by a cannon ball, you could perform a detailed simulation of how the material reacts, but I don't think that will fit with your visual style, and will be a lot of work to code and to run. Instead make some simplifications. Keep some basic physics in mind: a cannon ball has a limited amount of kinetic energy that it can impact. When this energy is transfered into the material, there are several ways that this energy can be distributed, including:

* The object as a whole can inherit the kinetic energy, and thus start moving
* The energy can be fully dissapted as heat
* A crack can be created

Usually, it will be a combination of all of the above. Ok, now looking just at cracks, depending on the material there is a preference for the direction of a crack, and once a crack starts, it will likely continue in the same direction. But typical materials have impurities, and there will be points where it becomes more favourable to change the direction of a crack. To simulate this, I would use the following algorithm:

* From the point of impact, spend a fraction of the energy for a crack that continues approximately in the direction of impact. The amount of energy spent determines the length of that crack.
* Then, make a random choice at the end of that crack:
    1. Change the direction of the crack
    2. Split into two branches, each going in their own direction
* Then repeatedly advance all the cracks until you have spent all energy.

You can tweak the parameters, such as the chance to bifurcate a crack, until you find it generates a pleasing crack pattern.

Apart from that, you want to check whether a crack line intersects an existing crack or if it hits the edge of the object that is cracking. In that case, there will be a piece of material that has now become completely loose. You can decide to give it a bit of kinetic energy from your remaining energy budget, and send it flying.

# Rendering

It seems like you can just draw the crack lines using a black line with similar properties as the outlines used in the drawing of the castle. But cracks just don't suddenly appear in one go. Creating a convincing animation might be hard. However, think again of the physics of a cannon ball impact: there will be dust and fine particles that will be disturbed, and could form a small smoke-like cloud. This cloud will dissipate in a few seconds, and might move along the direction of the wind. The cloud will hide the crack formation, so you don't have to worry about that. You can also make a few small particles erupt from the point of impact to give it a more dynamic look. It should be easy to add some randomization to these things, so they will look different every time.
> 5 votes

---
Tags: 2d, algorithm, game-mechanics, procedural-destruction
---


title: Unity In-game pause menu not working?

text:
# Question
Title: Unity In-game pause menu not working?
I have followed a tutorial to implement a pause screen for my platformer game. I followed it thoroughly but could not get it working. When I press the escape button which I assigned under the project manager under the name "Pause", it just doesn't do anything. I checked with the Scene view as well, nothing appears. Any help would be appreciated.

Edit: The script is a component of the Main Camera, not the Canvas or the PauseUI itself.

```
 public GameObject PauseUI;

 private bool paused = false;

void Start()
{
    PauseUI.SetActive(false);
}

void Update()
{
   if(Input.GetButtonDown("Pause"))
   {
       paused = !paused;
   }

   if(paused)
   {
       PauseUI.SetActive(true);
       Time.timeScale = 0;
   }

   if(!paused)
   {
       PauseUI.SetActive(false);
       Time.timeScale = 1;
   }
}

```

# Answer
The reason why Pause is not working is, that as input for Pause in the input manager you set Joystick Axis as Type but you want "Key or Mouse Button".
> 1 votes

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


# Question
Title: I'm trying to write a randomly patrolling AI for my 2D Platformer
I'm trying to write a randomly patrolling AI for my 2D Platformer. The AI already has a ground checker function which checks if there are tiles nearby or not. What I want to do is randomize its actions and create an illusion of a somewhat "sentient" enemy. What I tried to create below is using the built in RNG to make the enemy either jump, change direction, or keep moving.

The problem is, it doesn't seem to work properly. The enemy just jumps every second I want it to change behaviour. The change direction functions, however, don't occur as frequently. I need to know what I've done wrong here. Thanks.

```
void Update()
{
      //RNG
      behaviour = Random.Range(0,3);
      jumpSpeed = Random.Range(1,5);

      //clock
      timer += Time.deltaTime;
}

  //time
    private float waitTime = 2.0f;
    private float timer = 0.0f;

 void MoveRandomizer()
{
    if((Mathf.Round(timer%waitTime)) == 0)
    {
        if(behaviour == 0)
        {
        movingRight = false;

        }
        if(behaviour == 1)
        {
        movingRight = true;

        }
        if(behaviour == 2)
        {
        rb.velocity = new Vector2(rb.velocity.x, jumpSpeed);
        }
    }

}

```

# Answer
Compared to doing some custom timing with math, you could use InvokeRepeating (https://docs.unity3d.com/ScriptReference/MonoBehaviour.InvokeRepeating.html). Your code would change to something like this and gets called repeatedly.

```
private float waitTime = 2.0f;

void Start()
{
    InvokeRepeating("RandomMove", 0f, waitTime);
}

void RandomMove()
{
    int behaviour = Random.Range(0,3);
    switch (behaviour)
    {
        case 0: movingRight = false;
            break;
        case 1: movingRight = true;
            break;
        case 2:
            rb.velocity = new Vector2(rb.velocity.x, Random.Range(1,5));
            break;
    }
}

```

But to make it more realistic, you should not have an even distribution of actions. Does it make sense that a guard would - with an equal chance - move forward or back? Or do a jump for every third step? I would not even have a behaviour for left/ right. Consider a change for something like

* do nothing (stop at position/ idle animation/ look around)
* move forward
* turn around
* jump

Now realistically most of the time the guard would move forward, lets start with 75% of the time. If it reaches a corner/ wall it will turn around with 100% chance, else it has maybe 10% while walking to turn around. Some with stopping, start with 10%. In 5% of the case the guard will jump. What does this change? You are not rolling anymore your behaviour in a range of \[0, 3\] but \[0, 101\]. And you would now compare it against the range. Afterwards you can tweak the ranges to make it more realistic and/ or add more behaviours. You don't need to add them to 100%, it just makes it easier (in this example all could be divided by 5 for a 15/2/2/1 distribution)
> 1 votes

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


# Question
Title: Convert GPS coordinates into Unity world space?
I am developing an AR application where a number of historical buildings are spawned around the player depending on his position when a target / QR Code is recognized.

I know the Lat/Lon of these buildings and I have the Lat/Lon of the player. I have already implemented the Harvesine algorithm and can calculate the relative bearing of the buildings:

```
public static double Harvesine(double lat1, double lon1, double lat2, double lon2)
{
    double R = 6371000; // metres
    double omega1 = ((lat1 / 180) * Mathf.PI);
    double omega2 = ((lat2 / 180) * Mathf.PI);
    double variacionomega1 = (((lat2 - lat1) / 180) * Mathf.PI);
    double variacionomega2 = (((lon2 - lon1) / 180) * Mathf.PI);
    double a = Math.Sin(variacionomega1 / 2) * Math.Sin(variacionomega1 / 2) +
                Math.Cos(omega1) * Math.Cos(omega2) *
                Math.Sin(variacionomega2 / 2) * Math.Sin(variacionomega2 / 2);
    double c = 2 * Math.Asin(Math.Sqrt(a));

    double d = R * c;

    return d;
}

public static double Bearing(double lat1, double lon1, double lat2, double lon2)
{
    double radians;
    double x = Math.Cos(lat2*Mathf.Deg2Rad) * Math.Sin((lon2 - lon1) * Mathf.Deg2Rad);
    double y = Math.Cos(lat1 * Math.PI / 180) * Math.Sin(lat2 * Math.PI / 180) - Math.Sin(lat1 * Math.PI / 180) * Math.Cos(lat2 * Math.PI / 180) * Math.Cos((lon2 - lon1) * Math.PI / 180);

    radians = Math.Atan2(x, y) * 180 / Math.PI;

    return radians;
}

```

From here, how can I spawn the building relative to the player position? I have the distance (Harvesine) and the angle (Bearing), how can I get the Vector3 location?

# Answer
Presumably you considered just converting your angle and distance from polar coordinates into a Cartesian vector in the usual way?

```
public static Vector3 FromPolar(float angleRadians, float radius) {
    return new Vector3(Mathf.Sin(angleRadians), 0 Mathf.Cos(angleRadians)) * radius;
}

```

You can now add that offset to the player position to spawn the building at that displacement from the player.
> 2 votes

---
Tags: unity, coordinates, trigonometry, geolocation, gps
---


# Question
Title: How to use an overlapping shader so that it uses layers sort from sprite renderer and its transparent
Im using the shader from question

, but once I put it in the game, and my character gets close to it, it will be hidden by the shadow of the tree, which is transparent.

Any way to make the shader transparent and/or maybe use the sprite renderer sort layer system

I have been trying to use stencil configurable shader with no luck Thank you for your help

Not sure what combination of these should work:

The character is using a normal sprite renderer.

# Answer
Ok I solved the problem giving the character these properties:

And the tree shades these values:

As well as making the tree shades the same sorting layer as the character

In order to do this I had to insert the stencil section from here:

https://forum.unity.com/threads/configurable-shaders-open-source-project.518966/

Also I put none in the mask interaction of the character as this is what was hiding the character, not sure if its a bug, but this link also mention it: https://forum.unity.com/threads/shader-stencil-and-sprite-masks-not-working-together.756041/
> 1 votes

---
Tags: unity, 2d, shaders
---


# Question
Title: Unity Visual Effect: Play() has no effect
I am making my first visual effects, and I make effect, when my ship is flying. So I am want to play it only when the ship is actually moving. I would suppose it's easy, you call Play(), it will play. You play Stop() it will stop. But when I call play, nothing happens.

```
public void Update()
{
    _ship.Rotate(Input.GetAxis("Horizontal"));

    var move = Input.GetAxis("Vertical");
    _ship.Move(move);
    if (move > 0)
    {
        FlyEffect.Play();
        FlyEffect.SetVector3("Velocity", new Vector3(0, -_ship.Speed * move, 0));
    }
    else
    {
        FlyEffect.Stop();
    }
}

```

When I let in Initial Event Name OnPlay, it is playing as it should be. But nothing from the script... What I am missing here?

# Answer
Ok... At first I was expecting there is some inner attribute on `VisualEffect`, which will tell me if it's playing or not... But didn't find anything in that way. So then I was thinking it is not so much big problem, when you just call play...

But apparently is... As @DMGregory suggests, I just call the Play() once, added custom variable to hold state, if it is playing.

```
public void Update()
{
    _ship.Rotate(Input.GetAxis("Horizontal"));

    var move = Input.GetAxis("Vertical");
    _ship.Move(move);
    if (move > 0)
    {
        if (!_isPlaying)
        {
            FlyEffect.Play();
            _isPlaying = true;
        }
        FlyEffect.SetVector3("Velocity", new Vector3(0, -_ship.Speed * move, 0));
    }
    else
    {
        if (_isPlaying)
        {
            FlyEffect.Stop();
            _isPlaying = false;
        }
    }
}

```
> 2 votes

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


title: More natural camera movement

text:
# Question
Title: More natural camera movement
I have a camera that currently smoothly (ease in and out) linearly interpolates between two positions. The camera also moves in response to user input.

While this movement is nice and smooth it does not feel natural. My goal is to add some sort of feeling of inertia or natural movement or hand-heldedness to it.

Therefore I have been trying to generate a formula that simulates more natural camera movement on top of the interpolation and user control. Thus far I have not had success.

In one try I pretended that the camera had a stick going out of it and that at the end a ball was attached to a spring attached so said stick. This ball was then focused on adding some direction animation to the system... however I could never get this right. The camera would be shaky/oscillating and user movements looked really awful.

I also tried having the direction point towards a slower animated pole.

No such luck.

Why do these methods of generating a more natural 3D camera movements not work? What is usually used to make this work.

# Answer
Think of the physics of holding a camera. Is it a heavy or a light-weight camera? A heavy one will require more energy to move and rotate, so it will naturally move slower, and thus smoother.

Assuming you have a hand-held camera, you are standing somewhere and pointing it at some position. Then there are two things you can do: you can start walking or running with the camera in some direction, while keeping the orientation of the camera, or you can stand still and rotate the camera until it points to something else. So there's translation of the camera's origin, and a rotation of the camera's pointing vector.

Both of these parameters will not change instantly, and as you have discovered, also not with a linear interpolation. The reason linear interpolation is bad is that during the motion it is too smooth to be natural, and right at the beginning and end of the motion there is a discontinuity. Instead of linear interpolation, you want to use a function that has a more natural smoothness. What you want to do is limit the acceleration of the change in the parameter, or to put it more mathematically, limit its second derivative.

Instead of trying to model it as a mathematical function, I would keep track of the current value of the position and rotation parameters, and the speed at which they are currently changing. Then, before rendering the next frame, you want to calculate a new speed, and then update the current value using the speed times the duration of the frame. To update the speed, just think of what you would do yourself when walking around with a camera: you will have some maximum speed you cannot exceed, and while you are not yet at the right position, you will increase the speed to do to the desired position faster (until you hit the maximum speed), and if you are almost at the target position you will decrease the speed. The latter might be hard to do correctly, but that's fine, a little overshoot might make it look more natural.

Add some noise to the speed variable at every time step to avoid having a camera that looks perfectly still. This will result in Brownian motion. The strength of it can be controlled with a constant that you tweak until you get the desired result. Or you can make that a variable parameter as well, for example increase it to simulate the person holding the camera being scared. The feedback loop mentioned above will ensure the camera will, on average, stay centered on the target.
> 2 votes

# Answer
You can try the Cinemachine (which can be found in the Package manager). Use its noise Component

Hope it helps. Let me know.
> 0 votes

---
Tags: camera
---


# Question
Title: How do I control multiple Pawns without possesing them (RTS style)?
I am making a multiplayer RTS but I have a problem controlling spawned units (let's call them Vessels), specifically moving them around with `AI MoveTo bp`.

Vessels can be created by both Clients and Server and are visible for everyone but neither clients nor Server can move Spanwed Vessels.

Only Vessels placed on the map beforehand can be moved and ONLY by the Server.

Also, the server sees all Client CameraPawn movements and clients see Server CameraPawn movements BUT clients don't see each other's CameraPawn Movements (if this is related somehow...)

1. How can I control a pawn in multiplayer from all clients for starters?
2. How can I limit control to a specific controller?
3. Why "preplaced" Vessels work(move) for Server only?

# Answer
> 1 votes
I finally solved my problem and I guess I misunderstood some things. It appears that the server must do everything, regardless of whether the code appears to be executed on clients or not...

I ended up passing the location and pawn I wanted to move to a function that executed on the Server and there I ran the entire code.

Simply put, I just could not see it :)

@Stephen Thanks for the reply :D

# Answer
> 0 votes
If your spawned vessels aren't moving but those placed previously are then it's likely one of two things is happening.

Either the BP is set to Auto AI possess placed in level only and not spawned or placed in world:

The other option would be that you haven't correctly assigned the AI Controller when spawning. The easiest way to check this would be that after the spawn actor from class call, get the AI Controller and print it out. If it's not the controller you were expecting then it's not assigning correctly.

To limit control to a specific controller, you'll need to create a new variable which you'll need to make public and Expose on Spawn. This will put a new pin on your Spawn Actor class you can plug into for a unique reference to whichever controller spawned the vessel and can be checked against when attempting to select / move the vessel.

---
Tags: multiplayer, unreal-4, rts, mmorts
---


title: Distance Cost for 3D A* Algorithm

text:
# Question
Title: Distance Cost for 3D A* Algorithm
I'm currently implementing an A\* Algorithm for my Unity project. I found this entry on stackoverflow, but its not telling me how to solve my problem.

https://stackoverflow.com/questions/32205891/a-star-algorithm-in-a-3d-configuration-space

I'm not sure about the math required to calculate the distance cost correctly. How to properly implement this in 3-dimensional space?

In 2D space it is clear how to implement:

```
public static int CalculateDistanceCost(int3 a, int3 b)
{
    int xDistance = math.abs(a.x - b.x);
    int yDistance = math.abs(a.y - b.y);
    int remaining = math.abs(xDistance - yDistance);

    return 14 * math.min(xDistance, yDistance) + 10 * remaining;
}

```

However in 3d space it is unclear to me how to calculate it:

```
public struct AStarMath
{
    public static int CalculateDistanceCost(int3 a, int3 b)
    {
        int xDistance = math.abs(a.x - b.x);
        int yDistance = math.abs(a.y - b.y);
        int zDistance = math.abs(a.z - b.z);
        int remaining = math.abs(xDistance - yDistance - zDistance);

        return 14 * math.min(math.min(xDistance, yDistance), zDistance) + 10 * remaining;
    }
}

```

My neighbour cells are set up as follows:

```
int3 neighbours = new int3[]
{
                            //X(width),y(height),z(depth)
    new int3(-1, -1, -1), //Left, Bottom, Front
    new int3(0,  -1, -1), //Middle, Bottom, Front
    new int3(+1, -1, -1), //Right, Bottom, Front

    new int3(-1, 0, -1),  //Left, Middle, Front
    new int3(0,  0, -1),  //Middle, Middle, Front
    new int3(+1, 0, -1),  //Right, Middle, Front

    new int3(-1, +1, -1), //Left, Top, Front
    new int3(0,  +1, -1), //Middle, Top, Front
    new int3(+1, +1, -1), //Right, Top, Front

    new int3(-1, -1, 0),  //Left, Bottom, Middle
    new int3(0,  -1, 0),  //Middle, Bottom, Middle
    new int3(+1, -1, 0),  //Right, Bottom, Middle

    new int3(-1, 0,  0),  //Left, Middle, Middle
    //Middle, Middle, Middle (0,0,0) -> dont add, were already here
    new int3(+1, 0,  0),  //Right, Middle, Middle

    new int3(+1, +1, 0),  //Left, Top, Middle
    new int3(0,  +1, 0),  //Middle, Top, Middle
    new int3(+1, +1, 0),  //Right, Top, Middle

    new int3(-1, -1,+1),  //Left, Bottom, Back
    new int3(0,  -1,+1),  //Middle, Bottom, Back
    new int3(+1, -1,+1),  //Right, Bottom, Back

    new int3(-1,  0,+1),  //Left, Middle, Back
    new int3(0,   0,+1),  //Middle, Middle, Back
    new int3(+1,  0,+1),  //Right, Middle, Back

    new int3(-1, +1,+1),  //Left, Top, Back
    new int3(0,  +1,+1),  //Middle, Top, Back
    new int3(+1, +1,+1),  //Right, Top, Back
};

```

As you can see in this image, my enemy (magenta) now takes a weird path, but will always find a path towards target (blue).

# Answer
> 4 votes
The code you have here has nothing to do with A\*. It's just a way to get an integer approximation of 10 times the Euclidean distance between the two points.

You can think of it as breaking down your travel into a diagonal portion, `min(xDistance, yDistance)`, and an axis-aligned portion, `remaining`.

It scales the axis-aligned portion by 10 and the diagonal portion by 14 to approximate the \\$1:\sqrt 2 \approx 1:1.414...\\$ ratio between the width of a square and its diagonal.

You can make an analog of this in 3D, we just have three components to sum up:

* The diagonal component along all three axes x, y, and z (scaled by \\$\sqrt 3 \approx 1.732...\\$)
* The diagonal component along the two remaining axes, after the smallest distance has been taken care of (scaled by \\$\sqrt 2 \approx 1.414...\\$ as before)
* The remaining axis-aligned distance

Here's one way to compute these:

```
minimum = min(xDistance, yDistance, zDistance)
maximum = max(xDistance, yDistance, zDistance)

tripleAxis = minimum

doubleAxis = xDistance + yDistance + zDistance
           - maximum - 2 * minimum

singleAxis = maximum - doubleAxis - tripleAxis

approximation = 10 * singleAxis
              + 14 * doubleAxis
              + 17 * tripleAxis

```

If your pathfinding agents are actually allowed to make only these three specific moves:

* moving to a face neighbour at a cost of 10,
* moving to an edge neighbour at a cost of 14,
* moving to a corner neighbour at a cost of 17

...then this heuristic is admissible (never over-estimates the cost), and a tight lower bound on the potential cost to reach the goal. Just be aware that if your agents actually use different costs or have different moves available, then this heuristic could give you an incorrect estimate and affect the speed or accuracy of your pathfinding.

---
Tags: unity, c#, path-finding
---


# Question
Title: Minimap Render texture Mouse Hover Detect on 3d Object in world space
I have a **resizeable minimap** which is based on **render texture**. A camera rendering 3d space on Render Texture and then I used the texture as minimap. Now, I have a specific requirement to identify mouse hover on an object in Minimap(render texture). It may sound silly but I have to show some object information on minimap on mouse hover like a tooltip.

In **3d space or world space**, I have several objects and they are showing on minimap. Now if any user mouse-hover on the same object on minimap then I want to show tooltip. Is this possible to get 3d space information from render texture?

# Answer
Your minimap is just another buffer you render to. Same as the screenbuffer, it holds no information other than the pixel rgba values.

What you need is a translation between minimap coordinates to worldspace coordinates. So that e.g. the, say, 400x400 px the minimap takes up on your monitor, map to the 1000x1000 area of worldspace you display on that minimap.

So with the above values we select minimap-pixel 200/100, we get world-space 500/250.
> 1 votes

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


title: space map generation

text:
# Question
Title: space map generation
I am at the beginning of the creation of a space 4x and first of all i need to generate a galaxy of stars linked by connecting lines that changes in each new game, I'll add a few pictures to show what i want

So how can i have a simple 2d map with connected points like these images ? I thought to program each line with a random length and a random angle or program polygons by polygons but it is still unclear.

# Answer
You can scatter points using...

* uniform random coordinates (prone to uneven clusters and gaps)
* or a shaken or jittered grid, where you start with a regular lattice of points, then add a small randomized offset to each (prevents big gaps/clusters, but can reveal its structure)
* or a Poisson distribution (some clever algorithms to generate this can be found here)

Red Blob Games has a page that lets you play with different jittered grid vs Poisson distributions to get a sense of the trade-offs in these algorithms.

If you find your result is too uneven, you can form the Voronoi diagram of your points — generating the convex polygon that's closer to each point than any other — and move each of your points toward the centroid of its polygon. That tends to average out the spacing a little, while keeping things organic.

If you find your result is too even, you can randomly delete some points to introduce gaps, or randomly insert a few with weaker spacing criteria to create clusters.

You can also vary the spacing of your grid or Poisson samples based on an underlying density map that you generate first using noise.

Now for the connections:

To ensure that all stars are connected to the network, so you can't have an island inaccessible from the rest of the galaxy, you can use a spanning tree algorithm.

A minimum spanning tree will give you the skeleton of a constellation that touches all the stars, using the shortest links it can. Then we elaborate on that base, without violating the connectedness guarantee.

* If you use Prim's algorithm (which adds links one by one), you can add a few extra links after the algorithm finishes to create cycles and alternative pathways.
* If you use Kruskal's algorithm (which starts with a dense graph and removes links one by one), you can stop the algorithm early before it's weeded out more than x% of the redundant links, or give it a probability of keeping redundant links as it goes.
> 4 votes

---
Tags: c++, procedural-generation, geometry, trigonometry, graph
---


# Question
Title: Online multiplayer. Provoke lagged move on local player
I am developing an online multiplayer 2D videogame with Unity as a client and a server programmed in c ++.

I do the synchronization of movement through an interpolation so that the movement is smoothed, but I have a doubt that I cannot find an answer anywhere.

In any multiplayer game when the client has a bad connection (lag) the character moves awkwardly and not fluidly, but in reality I don't understand why this behavior happens, currently in my game even though the client has a bad connection, it moves from fluid form because movement management is done locally and what is sent to the server is the player's position.

**How can I produce this in my game?**

Thank you very much and sorry for my level of English. Thank you

# Answer
Server lag happens due to the fact that the server has to verify data that is *critical* for gameplay. Usually in Online Games this data has mostly to do with:

* positioning of actors
* combat (who attacked whom, how much damage did they deal/take, ...)
* player interactions (e.g. trading)

That means all the data that has the potential to influence the gamestate of other clients, needs to be verified by and synchronized by the gameserver(s). So after doing all the changes locally, they are sent (hashed and/or otherwise compressed) to the server, where the server does their own thing and tells the client either:

a) yep that's cool
b) nope that's wrong: here's what you should actually see

In addition to this, the client constantly will receive data from the server about the state of all other entities not controlled by the client itself.

---

Loads of data gets sent back-and-forth every second or likely even less. That data takes time to get to the server and back (roundtrip). If that time is longer than a tick (or maybe a few, really depends on your architecture..), the client has to make predictions. If these predictions are wrong, the local data needs to be adjusted to the real values received from the server.
> 0 votes

---
Tags: unity, c++, multiplayer, online
---


# Question
Title: Calling function every n second javascript game
I making a game and I want to call a function that runs every random second to spawn something every time. I've seen some posts that said to use the `setInterval()` function to keep track of the time but I don't know where to implement it because I'm using the `requestAnimationFrame()` to loop the game. I also tried to implement it in the update function of the classes but it doesn't seem to work.

This is my main with the loop

```
import Game from '/src/game.js';

let canvas = document.getElementById('main');
let ctx = canvas.getContext('2d');

const WIDTH_SCREEN = 800;
const HEIGTH_SCREEN = 600;

let game = new Game(WIDTH_SCREEN, HEIGTH_SCREEN);
game.start();

function loop() {
    ctx.clearRect(0, 0, WIDTH_SCREEN, HEIGTH_SCREEN);

    game.update(ctx);

    requestAnimationFrame(loop);
}

window.addEventListener("keydown", (event) => game.controller.keyListener(event));
window.addEventListener("keyup", (event) => game.controller.keyListener(event));
requestAnimationFrame(loop);

```

# Answer
> 1 votes
You can pass an optional `time` parameter to your `window.requestAnimationFrame()` callback (`loop()` in this case), and it will pass in the current amount of time (in milliseconds) since the first frame. You can create a timer object to take advantage of that:

```
const Timer = (event, interval = 0) => {
    let last = 0;
    let total = 0;
    return {
        set interval(newInterval)
        {
            interval = newInterval;
        },
        update(time = 0) {
            total += time - last;
            if (total >= interval) {
                event(this);
                total = 0;
            }
            last = time;
        }
    };
};

```

Now you can do this:

```
const fooLogger = Timer((timer) => {
    console.log('foo!');
    timer.interval = 1000 + Math.floor(Math.random() * 1000);
}, 1500);
function loop(time) {
    requestAnimationFrame(loop);
    fooLogger.update(time);
}
requestAnimationFrame(loop);

```

And this should log "foo!" every 1 - 2 seconds. Update: The question specified a variable interval, that has been added.

---
Tags: javascript, game-loop, timer
---


# Question
Title: Swept AABB Collision Detection Conflict with Tile-sized Gaps
# Background

The sweeping method for detecting and resolving collision has proven to be very versatile to implement collision for our game, and I have this GameDev.net article to thank for that: https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/swept-aabb-collision-detection-and-response-r3084/

The article was very helpful and I learned a lot from it. It did have some bugs in its example code (thankfully we don't have them ourselves), but the concept was the important part. I suggest you read it since it's a very important reference for this post.

# The Conflict

The problem I am presented is an unwanted, yet expected behavior. Basically the player is unable to fall into tile-sized gaps if the player is also tile-sized (unless there is something at the end of the hole to block the player).

While the code works in accordance to the GameDev article (I have a demo further down this post), there is a subtle issue with the method of "sliding".

Sliding is a method of collision resolution so that the entity does not stick to the surface of the other physics bodies. It basically allows the player to walk on the ground and slide along walls when jumping on them without being stuck on the surface. This image from the article describes it better than I do:

This is an ideal solution, but restricts the tile-sized player from falling into tile-sized holes and instead allows the player walk over it.

As you can see, you would expect the player to fall into those holes, but Lo and behold he walks right past them! I have tested with various walking velocities, even lower than one pixel per frame and the player still walks past them.

In addition, I'd like to clarify that this is not a problem with just one axis, since the player can't jump into tile-sized holes either.

Note that the player is still capable of falling into those holes, there just needs to be a blockade to allow it.

...and the same goes for walking into one.

# The Root of The Problem

I suggest you read some of the code in the demo I have provided, since the following code snipped is relevant for this section:

```
resolveCollisionOrMove(deltaTime, movement = this.vel, remainingTime = 1, collisionStack = this.collisionStack) {
    // Sort collisions in the correct order: First by distance, then by
    // time of impact to correct the order a bit.
    collisionStack.sort((a, b) => a.distance - b.distance);
    collisionStack.sort((a, b) => a.collisionTime - b.collisionTime);
    let hit = collisionStack.shift();

    // If a collision is detected at all, resolve for the closest AABB. Otherwise add velocity to position.
    if (hit) {
        this.center.x += movement.x * hit.collisionTime * deltaTime;
        this.center.y += movement.y * hit.collisionTime * deltaTime;

        // Calculate the correct time of impact for the remaining
        // collisions or to apply movement
        let time = remainingTime - hit.collisionTime;

        // Calculate the collision normal (vector used to slide the object that collided)
        let dotProduct = p5.Vector.dot(movement, hit.normal) * time;
        hit.normal.mult(dotProduct);

        // Handle events after each respective side that collided
        this.onCollision(hit.side);

        if (time > 0) {
            // If the time of impact happened to be above zero, then recalculate
            // collision for all other potential collisions with respect to the normal vector
            let stack = [];
            for (let sweep of collisionStack) {
                // Pass the normal vector as the movement vector for the next possible collision
                if (this.createMovementBoundary(deltaTime, hit.normal).overlaps(sweep.aabb)) {
                    let newSweep = this.calculateSweepData(sweep.aabb, hit.normal, deltaTime);
                    stack.push(newSweep);
                }
            }

            // Keep resolving collisions for the other potential collisions
            this.resolveCollisionOrMove(deltaTime, hit.normal, time, stack);
        }
    } else {
        this.center.add(p5.Vector.mult(movement, deltaTime));
    }
}

```

I presume this is a problem caused by the collision normal calculated for the sliding effect. Assume the player walks towards a tile-sized hole from the left (the hole is now to the right of the player). My collision resolution algorithm takes into account other potential collisions based on the sliding vector applied to the player upon the closest detected collision. This means the tile before the hole is what collides with the player first, which in turn applies a movement vector (the slide) with a y-component of zero. This makes the collision algorithm ignore the tile to the left of the hole as a potential collision since according to the logic, the player does not collide with its left side.

The green line is the normal vector used for sliding (which is used in the next collision calculation) while the red one is the actual velocity applied to the player before resolving collision...

The issue is I don't know how to solve this problem without breaking the code. I know this problem can be solved by simply reducing the player size. That is not something I'm willing to accept as a solution since it limits many gameplay mechanics which I won't get into here.

# The Code

Here is the link to a JSFiddle I made where all the magic happens: https://jsfiddle.net/uwg0m9zp/

I've written it in JavaScript in a single HTML file where I use the p5.js library for simplifying input, graphics and vector calculation. Most of the p5.js function calls are not important for this problem, except for the vector mathematics, but if the structure of the code confuses you just look up the documentation (or ask in the comments): https://p5js.org/

## Demo instructions

This demo features a blue rectangle who is our player. He can walk, fly and have collision with the purple tiles in the map.

The controls are:

* A: Walk Left
* D: Walk Right
* Space: Fly

Use these controls to walk/fly into the tile gaps

# Final words

I hope I explained my problem well. Please do not hesitate to ask questions if I came across a bit confusing. Note that I have also tested to see if this is a float imprecision problem (using epsilon, etc.) and had no luck.

Thanks for reading this and for any help in advance!

# Answer
> 2 votes
After countless hours of finding the problem through trial and error and asking around on Discord servers and, of course, here, my friend and I found a very versatile solution for a particularly irritating problem.

Credit is due to Kevin Reid who took his precious time to answer this post. He made a well written answer that explained a crucial concept within this solution. I also want to thank a fellow I talked to on the SFML Discord server who was very helpful to show us how we should approach this problem.

# What did we learn?

There is one simple thing that I was afraid of which, funny enough, solved it all: adding a special case.

Special cases, special cases, **special cases**! I was very afraid of breaking the flow of an algorithm I never came up with in the first place (sweeping), but all it needed was to add something extra to check for these tile-sized hole situations while still keeping in touch with how the algorithm "thinks".

This solution takes into account not only holes of equal size to a tile, but pretty much any size of any entity that is about to walk into one.

### Detecting such a case

I will explain the detection with a simple example that can be applied to movement in any axis. Assume the player walks from left to right and is approaching a hole that is of equal horizontal size to him in this particular frame. The broadphase portion of the algorithm will always detect potential collision with the two following tiles:

* the one the player is currently walking on
* the one (potentially) next to the hole

This is useful information since the collision resolution portion of the algorithm resolves collision in the order of the closest tile to the player.

```
fixEqualSizedHoleCollision(hit, potentialMovement, time, collisionStack) {
     if (collisionStack.length > 0) {
         // The tile/entity the player currently stands on
         let standingOn = hit.aabb;

         // The tile/entity assumed to be next to the player-sized hole
         let nextToHole = collisionStack[0].aabb;
                ...

```

*By the way, I call this function in the collision resolution portion in my new demo (further down this answer)*

Since I pop out the first potential collision, I pass it in as a parameter for this function so that the following potential collision is the first one in the stack.

Now what we need to do is check if these tiles are actually under the player in the first place! This can be done by checking if both of these tiles are half a vertical player size plus half a tile size away from the player on the y-axis. This diagram illustrates this best

The green lines are what represents the distance I was talking about. All of those green lines need to be equal to determine if these tiles are exactly beneath the player on the y-axis.

You may have noticed a red line too! This will be used to determine if there is even a player-sized hole at all. Simply make sure the x-distance between the two tiles are the exact same as the player's horizontal size. And bingo! Now we know if there is a hole.

### Resolution

Resolving the case was surprisingly less complicated than the detection. Simply stop the player so that it can perfectly fit into the hole, stop all x-movement and slide it downwards with the same magnitude as the gravity. Stopping the player can be simulated with a "barrier" that is right on top of the tile next to the hole.

The green line is now the player's new movement vector and the white box is the simulated barrier which stops the player in its tracks! Here is the part of the code which solves that:

```
barrierOffset.x = (this.extents.x - nextToHole.extents.x) * -movementDir;
if (areBothUnderMe && isHoleBetween) {
    // Create a simulated barrier that will block the player and make him fall
    // into the hole.
    let barrier = new AABB(nextToHole.center.copy(), this.extents.copy());
    barrier.center.sub(barrierOffset);
    this.center.x = barrier.center.x + (barrier.extents.x + this.extents.x) * (-movementDir);
    hit.normal.x = 0; // The player should now fall into the hole and no longer walk
    hit.normal.y = potentialMovement.y; // The sliding should now be applied to the hole wall
}

```

### The New Demo

Here is the new link to a JSFiddle with the new code: https://jsfiddle.net/2bnv510x/

There are some new additions to the previous one. First of all, you can pass in to tile-sized holes (obviously) and secondly I've added two large entities a tile-size apart from each other. I also added some new controls that let you change your velocity:

* Shift: Move super slow
* Q: Move super fast

Enjoy!

# Final Words

I would like to thank everyone who helped us with this problem. We learned a lot from this problem, and I hope anyone reading this does too.

What got me posting in the first place was the lack of information on swept AABB collision detection and barely information on this problem at all. So I want this post to help anyone who struggles with the same problem.

# Answer
> 4 votes
Since you have a tiled world and an exactly tile-sized character, a **first step** to sort out this problem can be to *recognize when the character aligns with a tile.* In the falling-into-a-hole case, this occurs when

* The Y coordinate is integer (assuming your tiles are side length 1), which should be true whenever sliding on a tile-aligned obstacle is happening.
* The X coordinate computed by sliding, rounded down to an integer, changes to be a different integer than it was at the beginning of *the sliding portion of* the movement.

Jumping is the same with the coordinates reversed.

When you recognize that your collision calculation has happened upon a tile-alignment, *break the movement into two parts:*

Now, you can pretend you're doing a physics step that starts at the dotted box position in this diagram, handle the situation however you like, and if the answer is *not* "fall down the hole" (for example, in the case where there isn't a hole!), continue to apply the second part of the motion (solid framed box in the diagram) to preserve velocity.

---

The second part of the problem is interesting: how do we decide the character should fall down the hole? If we look at the moment it's aligned with the tile, it could go right or it could go down, and its velocity vector is mostly aligned with going right with a *infinitesimal* contribution of gravity pointing down (infinitesimal because it's been in freefall for zero time; or perhaps in simulation, one frame's worth of velocity). Similarly, in the jumping case, the velocity is upward and there's a sideways force but no sideways velocity. A resolution based on the alignment of the velocity vector will consistently give the answer you don't want!

So, for the gameplay you want, you should detect the case where all of these conditions are met:

* character is aligned with tile (as discussed above),
* velocity is pointing in a certain direction and gravity or player-input force is pointing perpendicularly
* and there is open space in that perpendicular direction;

and **always choose to take the perpendicular path!** You can implement this by proceeding as if there was a blocking tile that stops the character moving the regular direction (might be tricky in the jumping case), or you could simplify the implementation and yet add flair by giving the character an extra kick into the hole (one frame of position shift + some velocity in that direction), maybe even with a special animation.

---
Tags: collision-detection, platformer, collision-resolution, aabb
---


# Question
Title: I am getting different results when using 'Maximize on play '?
so i'll be straight to point. when i move my character without using 'max on play' it works fine just as i wanted it to be. but when i switch to 'max on play' my character moves very fast. i am using `addForce()` to make me character move in `Update()`.

after some googling i found that as i am working with physics i need to use `FixedUpdate();` But when i tried with fixed update i felt like it was not registering the keystrokes as it would in `Update()`. i would really appreciate if someone would help me out here.

**Edit - Movement Script Added**

```
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    [SerializeField] float jump_speed;
    [SerializeField] float walk_speed;
    [SerializeField] float max_speed;
    Rigidbody2D rb;
    int jump_counter;
    Animator animator;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();
        jump_counter = 0;
        animator.SetBool("isIdle", true);
        animator.SetBool("isWalkingLeft", false);
        animator.SetBool("isWalkingRight", false);
    }
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space)  && jump_counter <=1)
        {
            rb.AddForce(transform.up * jump_speed);
            jump_counter++;
        }
       else if (Input.GetKey(KeyCode.D))
        {
            rb.AddForce(transform.right * walk_speed);
            PlayWalkingRightAnimation();
        }
       else if (Input.GetKey(KeyCode.A))
        {
            rb.AddForce(-transform.right * walk_speed);
            PlayWalkingLeftAnimation();
        }
        else
        {
            if(jump_counter<=0) PlayIdleAnimation();
        }
    }
    void FixedUpdate()
{
     rb.velocity = Vector2.ClampMagnitude(rb.velocity, max_speed);

}
    private void OnCollisionEnter2D(Collision2D collision)
    {
        jump_counter = 0;
    }

    void PlayWalkingLeftAnimation()
    {
        animator.SetBool("isWalkingLeft", true);
        animator.SetBool("isWalkingRight", false);
        animator.SetBool("isIdle", false);
    }
    void PlayWalkingRightAnimation()
    {
        animator.SetBool("isWalkingRight", true);
        animator.SetBool("isWalkingLeft", false);
        animator.SetBool("isIdle", false);
    }
    void PlayIdleAnimation()
    {
        animator.SetBool("isWalkingLeft", false);
        animator.SetBool("isWalkingRight", false);
        animator.SetBool("isIdle", true);
    }

}

```

I have added whole script hope this helps understand my problems.

# Answer
I found a workaround for the problem. also i am not sure if its a good thing to do.

what i did essentially was limit my framerate in the game by using these two lines in

```
void Awake()
    {
        QualitySettings.vSyncCount = 0;
        Application.targetFrameRate = framerate;// i've set it to 60;
    }

```

after implementing this, it seems pretty much same on both maximize on play and normal game view.
> 0 votes

# Answer
To register KeyStrokes you need to Do it in Update().

And All the Physics related calculation in thee Fixed Update

Here's a sample Code

```
 private void Update()
{

//Register Key Strokes

    if (Input.GetKeyDown("a"))
    {
        MoveLeft();
    }
    else if (Input.GetKeyDown("d"))
    {
        MoveRight();
    }
}

private void FixedUpdate()
{
    //Player Movement
        _rb.velocity=(Vector3.forward*playerSpeed)*Time.deltaTime;

}//Fixed Update

void MoveLeft()
{
    transform.position=new Vector3(transform.position.x-1,transform.position.y,transform.position.z);// snappy
}//Move Left

void MoveRight()
{
    transform.position=new Vector3(transform.position.x+1 ,transform.position.y,transform.position.z);//snappy

}//Move Right

```

Hope this Helps
> 0 votes

---
Tags: unity, physics, input
---


# Question
Title: Can I report someone for cloning my game?
I recently found out that someone cloned my game from 2018 (2d, pixel art, here: https://www.youtube.com/watch?v=fiTJn5PULnA) that was on iOS, made it in 3d for android (here: https://play.google.com/store/apps/details?id=com.goquest.angrywife). Copied name, mechanics, everything, even some of the optional gadgets.

I paused my apple dev subscription at the end of 2019 so my game is not available for download anymore, but this guy released it in mid 2019, when it was.

I was wondering if I can somehow take action and have google remove the game from the listing.

# Answer
I believe this would be from futile to impossible. Unfortunately it's quite common to see clones of other games. Unless that person is using exact copies of your assets from your game this game won't be considered "stolen".

You can try to lawyer up, but consider amount of clones out there, even with same name, but released on different platform.
> 1 votes

---
Tags: ios
---


# Question
Title: Get world position of random point inside bounds
I am trying to get a random world position inside my targets collider, so that I can fire an arrow at it.

I have tried a bunch of different solution but can't seem to get it right, for example (this code is on my target):

```
//Inside Awake
colliders = GetComponentsInChildren<Collider>(); //I want this to work on a unit with a single capsule collider and a building with 8 different box colliders

public Vector3 GetRandomPoint()
{
    Bounds b = new Bounds();

    for (int i = 0; i < colliders.Length; i++)
    {
        b.Encapsulate(colliders[i].bounds);
    }

    float minX = gameObject.transform.position.x - gameObject.transform.localScale.x * bounds.size.x * 0.5f;
    float minZ = gameObject.transform.position.z - gameObject.transform.localScale.z * bounds.size.z * 0.5f;

    return new Vector3(Random.Range (minX, -minX),
                           gameObject.transform.position.y,
                           Random.Range (minZ, -minZ));
    }

```

In the scenario I'm having issues with right now, the trageet simply has a single capsule collider.

This return a point quite far away from my target, but I cant find the issue.

EDIT:

Here is another one I tried without success:

```
public Vector3 GetRandomPoint()
    {
        Bounds b = new Bounds();

        for (int i = 0; i < colliders.Length; i++)
        {
            b.Encapsulate(colliders[i].bounds);
        }

        var target = new Vector3(
            UnityEngine.Random.Range(b.min.x, b.max.x),
            UnityEngine.Random.Range(b.min.y, b.max.y),
            UnityEngine.Random.Range(b.min.z, b.max.z)
        );

        return b.ClosestPoint(target);
    }

```

# Answer
As instructed by @DMGregory, using `new Bounds` will use world origin, if I instead just use the first collider in the list, it works as intended:

```
public Vector3 GetRandomPoint()
    {
        Bounds b = colliders[0].bounds;

        for (int i = 1; i < colliders.Length; i++)
        {
            b.Encapsulate(colliders[i].bounds);
        }

        var target = new Vector3(
            UnityEngine.Random.Range(b.min.x, b.max.x),
            UnityEngine.Random.Range(b.min.y, b.max.y),
            UnityEngine.Random.Range(b.min.z, b.max.z)
        );

        return b.ClosestPoint(target);
    }

```
> 2 votes

---
Tags: unity
---


# Question
Title: Unity doesn't change particle color when render is set to mesh?
I've got a particle system with Render Mode set to Mesh. Then I applied a material to it, which is just white with the default shader. Now I can't change the start color nor the color over lifetime etc. As far as I know that shouldn't happen, right? I'm using Unity 5.5.0f3

This is what my PS looks like with the material :

This is what I achieved with 3 particle systems with 3 different materials, but actually, I don't want these materials. Instead, I want to set the start color property of the particle system to apply some color. The material solution restricts me in terms of random start color and stuff like this.

# Answer
I'm not sure why you say "The material solution restricts me in terms of random start color and stuff like this."

You can get random start colours into a material just fine. As I said in my first comment, all you need to do is use (or create) a material that uses the mesh's **vertex colours**.

For example, you can `Create->Shader->Standard Surface Shader` (since it appears you want lighting to apply to your meshes), and then make two small modifications:

```
    CGPROGRAM
    #pragma surface surf Standard fullforwardshadows
    #pragma target 3.0

    sampler2D _MainTex;

    struct Input {
        float2 uv_MainTex;

        // Modification 1: add a vertex colour parameter to the Input struct.
        float4 vertexColor : COLOR;
    };

    half _Glossiness;
    half _Metallic;
    fixed4 _Color;

    void surf (Input IN, inout SurfaceOutputStandard o) {
        fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;

        // Modification 2: multiply the albedo by this vertex colour.
        c *= IN.vertexColor;

        o.Albedo = c.rgb;
        o.Metallic = _Metallic;
        o.Smoothness = _Glossiness;
        o.Alpha = c.a;
    }
    ENDCG

```

Create a material using this shader and assign it to your particle system. Now you can play with colours in the particle system as much as you want!
> 7 votes

# Answer
(Sorry for my english, I'm not native) I had the same problem, and what i did was:

1. Create New Material (i named my new material "ParticlePlane").
2. Change the Shader in the new material. I assigned Particles/Standar Surface
3. Then in the particle system, in the Renderer module, in the Material property i put my new created material and that's all.

After doing those 3 things, the Color over lifetime module started to work correctly.

Hope it helps somebody.

Regards.
> 1 votes

# Answer
```
GameObject _particle= Instantiate(Resources.Load("SplashDust")) as GameObject;

ParticleSystemRenderer _rend = _particle.GetComponentInChildren<ParticleSystemRenderer>();
_rend.material.color = Color.red;

```
> -2 votes

---
Tags: unity, particles
---


# Question
Title: Should I use a database to store ~10 000 names in a sports game?
I'm working on a single player sports game for a year or so and this doubt came up: how should I treat/store big amounts of data, like player names.

Let's take an arbitrary number as example: 10000 names, 5000 first names and 5000 surnames. These names would be equally divided between 100 countries, which give us 50 first names and 50 surnames per country.

Should I have a local database with these names (or even these countries) considering this data will be needed to generate new players names during the course of the game? Would that introduce limitations, considering I want to make my game moddable by players, as much as possible?

These doubts can be extended to other, more complex game entities, such as:

* Players - each one with their own face, attributes, team etc...
* Teams - each one with its own crest, kit, squad etc...

In my previous research about that, the SQLite popped up as a seemingly viable solution. It happens that I have almost no experience with DB's (specially in games) and would like to know if this is a good direction before start to study and try to implement it.

# Answer
When the data is static while the game is running or small enough to fit into RAM, then databases have very little benefit compared to the technical complexity they add. You can just as well store all that data in text files (TextAssets). When the game starts, then you parse those files, store all that data in adequate data-structures and then access those data-structures at runtime.

When you would like to maintain the data in a more organized way within the Unity editor, then ScriptableObjects are your friends. This is a feature which allows you to create custom Unity asset types which you can then create, manage, edit and use like any other Unity asset. You could, for example, create a ScriptableObject class "Country" which has three text assets, a "nameFileMale", "nameFileFemale" and a "nameFileLastname", plus all the other data you have about a counry. You can then create one of these assets for every country in your game and assign the threee text files which list the names for that country.

And just by the way: Did you know that C# can do SQL queries on arrays and other containers which implement IEnumerable?
> 1 votes

---
Tags: unity, databases, asset-workflow
---


# Question
Title: Why was 24-bit color support introduced twice in GPUs?
I was doing research, trying to answer the question "Which was the first GPU to support 24-bit color". I know all color since 1992 is 24-bit, even in games like Doom. I mean 16 million simultaneous colors on the screen, not just 256 unique colors from a 24-bit palette.

I started digging, and naturally I came across the ATI Mach 32. Later I find out that RIVA TNT also "added" support for truecolor. So I'm left wondering, is 24-bit color support some ancient technology that was forgotten after 1992 and rediscovered in the year 1998? Or are they talking about something different?

I have two guesses, but I'd love to know the real explanation:

1. Truecolor support in RIVA TNT meant it's hardware accelerated, as in the sprites are stored in the VRAM, as opposed to the Mach 32, where the VRAM is just a frame buffer so acceleration would be considered software.
2. Nvidia meant 32-bit color texture, not even talking about frame buffer pixel depth.

Anyone know what both Nvidia and ATI really meant?

# Answer
The Mach32 chip uses 24bit color, with 32 bits alignment, and it is not intended for 3D graphics. For what I read, using Mach32 cards required a resident software in DOS that slowed DOS down *(I'm guessing this is true of every card)*.

Cards using the Mach32 chip add VRAM. *I believe the chip does not have a texture sprite cache. I would like to see an schematic of the chip.*

On the other hand RIVA TNT is capable of fully accelerated 3D graphics with 32bit color pipeline. Also, unlike Mach32 card, RIVA TNT supports DirectX 5.0 and OpenGL 1.2.

---

More about on Mach32:

More about on Riva TNT:
> 1 votes

---
Tags: gpu, nvidia
---


title: Unity conversion of Gameobjects to ECS

text:
# Question
Title: Unity conversion of Gameobjects to ECS
I have not worked with ECS before, so I was following the tutorial by Unity's Mike Geig on Youtube to convert gameObjects to ECS from Unite Copenhagen, and this code does nothing, and there are no errors:

```
using Unity.Entities;
using Unity.Transforms;
using UnityEngine;

public class SpawnAsteroidECS : MonoBehaviour
{
    public GameObject AsteroidPrefab;

    EntityManager manager;
    Entity AsteroidEntityPrefab;

    void Start()
    {
        manager = World.Active.EntityManager;
        AsteroidEntityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(AsteroidPrefab, World.Active);
    }

    void Update()
    {
        if (Input.GetKey(KeyCode.Mouse0))
        {
            for (int i = 0; i < 100; i++)
                SpawnTheAsteroids();
        }
    }

    private void SpawnTheAsteroids()
    {
        Entity asteroid = manager.Instantiate(AsteroidEntityPrefab);

        manager.SetComponentData(asteroid, new Translation { Value = transform.position });
        manager.SetComponentData(asteroid, new Rotation { Value = Quaternion.identity });
        print("Done");
    }
}

```

What am I not doing?

EDIT: The entity debugger does show that there are entities, but i dont actually see it in the game.

# Answer
Its look like that you have not installed the "**Hybrid Renderer**" Package.

When you want to convert Game objects to Entities then you have to also install "**Hybrid Renderer**" from package manager.

1. Open up package manager from **Windows -\> Package manager.**
2. Enable **"Show Preview Packages"** from **Advance** tab.
3. Then search "hy" then Install "**Hybrid Renderer**".

> Same thing happen to me and from some where on internet i found this and it resolved my issue immediately.I am sorry i don't have link to it but it workes.

I hope this will help.
> 3 votes

# Answer
I was stuck with this problem for a long time, it seems that for Unity 2020.1.2f1 that I am running, "Hybrid Renderer" did not show up in the Package Manager. Looking at the docs made me think it was now a part of "Universal RP" but installing that did not make a difference. It was first when I manually added `"com.unity.rendering.hybrid": "0.8.0-preview.19",` to the manifest file that the entities started to render.

Btw, Entites did not show up either in PM, but by installing "Havok Physics for Unity" then it was downloaded as an dependency..
> 0 votes

---
Tags: unity, c#, entity-component-system, unity-dots
---


# Question
Title: UnityWebRequest won't work unless a breakpoint is triggered before hand
```
public void GetLeaderBoard() //Load all game data
{   UnityWebRequest myWr = UnityWebRequest.Get(Url(false));
    myWr.SendWebRequest();
    var text = myWr.downloadHandler.text;
    MonoBehaviour.print(text);
    return;
}

```

text is populated by an empty string unless I stop at a break point **before** I encounter it. The MVC application that's giving me the data is being debugged on a separate solution, also it's going through something called IIS Express, which like runs it or something. My best guess is that something on my other application doesn't have enough time to send the data unless I stop execution with a breakpoint; however, this doesn't make any sense as myWr.downloadHandler.text is actually being populated with the data (according to the watch I have on, when it stops at the breakpoint on the return), so my other app should be out of the picture at this point.

**Edit:** So I got it working apparently the whole function needed to be part of a coroutine like so:

```
public IEnumerator GetLeaderBoard() //Load all game data
{
    using (UnityWebRequest myWr = UnityWebRequest.Get(Url(false)))
    {   yield return myWr.SendWebRequest();
        if (myWr.isNetworkError) MonoBehaviour.print("Recieved error: " + myWr.error);
        else
        {   var text = myWr.downloadHandler.text;
            MonoBehaviour.print(text);
        }
    }

```

I'll leave the question open if anybody has any explanation for the values I was getting in my watch though (if the downloadHandler was getting data shouldn't it have populated my text field?).

# Answer
> 1 votes
You need to `IEnumerator` to yield return and wait for request to complete. Call this method inside coroutine.

**Method:**

```
public IEnumerator GetLeaderBoard()
{
    UnityWebRequest myWr = UnityWebRequest.Get("http://your-url"));
    yield return myWr.SendWebRequest();

    if (myWr.isNetworkError || myWr.isHttpError)
    {
        Debug.Log(myWr.error);
    }
    else
    {
        // Show results as text
        Debug.Log(myWr.downloadHandler.text);
        var text = myWr.downloadHandler.text;
        // Do stuff here.. Instantiate GameObject or modify data
    }

}

```

**Usage:**

```
 StartCoroutine(GetLeaderBoard());

```

---
Tags: debugging, mvc, webapp
---


# Question
Title: Simple way to serialize save game data whilst allowing for future features
Is there a simple way to 'serialize' the game data of my game, but protected it from being unloadable if I add new fields? I have all the data in a single class, GameData.java, and I want to avoid having to manually read/write each field from it. If I serialise it using standard java function, but add new fields to the class, it will render it unserializable.

I'd like to be able to save the class and the reload it from a file, and it use default values for any new fields that are missing from the save file. XML may be a solution, but is there an existing library to automate the process?

Thanks!

# Answer
I use the libGdx Json functionality to save my game state to JSON;

```
public class GameInstance
{
    //Some fields, constructors, utilities

    public void saveState(GameState state)
    {
        String save = json.prettyPrint(state);

        //Save to the file using FileHandle
    }

    public void loadState(FileHandle file)
    {
        String stateText = file.toString();
        json.setIgnoreUnknownFields(true);
        state = json.fromJson(stateText);
    }
}

```

In my GameState I store the version of my app;

```
public class GameState
{
    //some fields
    public final String versionID = "0.1.1";

    //game access functions
}

```

Before I access the modified field, I check to see if the versionID is correct and will allow me to read it. This allows me to write simple fallback mechanics that help provide as much of the new functionality as possible.

# EDIT:

I keep a field-changes.txt file that I use to log changes that I make in my fields for each class. I almost never remove a field entirely for compatability reasons. When I do I try to add functions that can work out a suitable replacement value.

Now, without libGdx you can just use the Jackson JSON API(link to tutorial on how to use Jackson). The details can be found in this Stack Overflow question. In short, there is apparently an annotation that you can use that has this purpose in mind specifically.

The accepted answer says you should do this;

```
import org.codehaus.jackson.annotate.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Foo
{
    //...
}

```

Also check out the next best answer. **Either way, the idea is still the same; to store the version of your GameState in each saved state and refactor the code to use the old data in alternative ways that makes the newest functionality possible.**

Note: I only use libGdx and its Json library. Alternatively, if you wanted to use its Json library you could go and get the Json sourcecode. You would also need to copy the libGdx-specific collections and primitive collections to your project and fix the setup. You would have to do some minor editing to make it work.
> 3 votes

# Answer
To parse the Json in java we use jsonparser. To use jsonparser in java we have to add below dependency in our `pom.xml` file.

```
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

```

Now suppose you have to parse the below complex json.

```
{
    "name": "vasu",
    "age": 26,
    "email": "vasu@gmail.com",
    "educationDetail": {
        "college": "GEHU Dehradun",
        "course": "B.Tech",
        "Branch": "CSE"
    },
    "matrixEducation": [{
        "10ClassBoard": "Pass 10 class from UP Board"
    }, {
        "12ClassBoard": "pass 12 class from UP Board"
    }]
}

```

So for this we create a JsonParser and make below code to parse data using this parser.

```
private JSONParser parser = new JSONParser();
   JSONObject jObj = (JSONObject) parser.parse(payload);
            String name = jObj.get("name").toString();
            String age = jObj.get("age").toString();
            String email = jObj.get("email").toString();

            JSONObject educationObj = (JSONObject) jObj.get("educationDetail");
            String collegeName = educationObj.get("college").toString();
            String course = educationObj.get("course").toString();
            String branch = educationObj.get("Branch").toString();

            JSONArray matrixDetail = (JSONArray) jObj.get("matrixEducation");

            JSONObject highSchoolObj = (JSONObject)matrixDetail.get(0);
            String highSchoolboard = highSchoolObj.get("10ClassBoard").toString();

            JSONObject interSchoolObj = (JSONObject)matrixDetail.get(1);
            String interSchoolboard = interSchoolObj.get("12ClassBoard").toString();

```

Checkout complete example on jsonparser on below URL

https://www.javadream.in/jsonparser-in-java/
> -1 votes

---
Tags: java
---