title: Google Play Console error problem

text:
# Question
Title: Google Play Console error problem
I am trying to upload my game (finally) to the google play store but I am faced with one final problem that I have attempted to fix but have of course failed! The error message that pops up is as follows:

* The following APKs or App Bundles are available to 64-bit devices, but they only have 32-bit native code: 1.

With this I assume I need to convert my unity game from 32-bit to 64-bit, but how?

This is the error that pops up in the console:

Failed running /Applications/Unity/Hub/Editor/2018.4.20f1/Unity.app/Contents/il2cpp/build/il2cppcore/il2cppcore.dll --convert-to-cpp --emit-null-checks --enable-array-bounds-check --dotnetprofile="unityaot" --compile-cpp --libil2cpp-static --platform="Android" --architecture="ARMv7" --configuration="Release" --outputpath="/Users/myname/game/Temp/StagingArea/assets/bin/Data/Native/armeabi-v7a/libil2cpp.so" --cachedirectory="/Users/myname/game/Assets/../Library/il2cpp\_android\_armeabi-v7a/il2cpp\_cache" --additional-include-directories="/Applications/Unity/Hub/Editor/2018.4.20f1/PlaybackEngines/AndroidPlayer/Tools/bdwgc/include" --additional-include-directories="/Applications/Unity/Hub/Editor/2018.4.20f1/PlaybackEngines/AndroidPlayer/Tools/libil2cpp/include" --tool-chain-path="/Applications/Unity/Hub/Editor/2018.4.20f1/PlaybackEngines/AndroidPlayer/android-ndk-r16b" --map-file-parser="/Applications/Unity/Hub/Editor/2018.4.20f1/Unity.app/Contents/Tools/MapFileParser/MapFileParser" --directory="/Users/myname/game/Temp/StagingArea/assets/bin/Data/Managed" --generatedcppdir="/Users/myname/game/Temp/StagingArea/Il2Cpp/il2cppOutput"

stdout: Building libil2cpp.so with AndroidToolChain Output directory: /Users/myname/game/Temp/StagingArea/assets/bin/Data/Native/armeabi-v7a Cache directory: /Users/myname/game/Library/il2cpp\_android\_armeabi-v7a/il2cpp\_cache il2cpp.exe didn't catch exception: Unity.IL2CPP.Building.BuilderFailedException:

Invocation was: Executable: /Applications/Unity/Hub/Editor/2018.4.20f1/PlaybackEngines/AndroidPlayer/android-ndk-r16b/toolchains/llvm/prebuilt/darwin-x86\_64/bin/clang++ Arguments: -DNET\_4\_0 -DUNITY\_AOT -DGC\_NOT\_DLL -DRUNTIME\_IL2CPP -DLINUX -DANDROID -DPLATFORM\_ANDROID -D\__linux\__ -D\__STDC\_FORMAT\_MACROS -I"/Applications/Unity/Hub/Editor/2018.4.20f1/PlaybackEngines/AndroidPlayer/Tools/bdwgc/include" -I"/Applications/Unity/Hub/Editor/2018.4.20f1/PlaybackEngines/AndroidPlayer/Tools/libil2cpp/include" -I"/Applications/Unity/Hub/Editor/2018.4.20f1/Unity.app/Contents/il2cpp/libil2cpp" -I"/Applications/Unity/Hub/Editor/2018.4.20f1/Unity.app/Contents/il2cpp/external/boehmgc/include" -I"/Users/myname/game/Temp/StagingArea/Il2Cpp/il2cppOutput" -I"." -I"/Applications/Unity/Hub/Editor/2018.4.20f1/PlaybackEngines/AndroidPlayer/android-ndk-r16b/sources/cxx-stl/gnu-libstdc++/4.9/include" -I"/Applications/Unity/Hub/Editor/2018.4.20f1/PlaybackEngines/AndroidPlayer/android-ndk-r16b/sources/cxx-stl/gnu-libstdc++/4.9/include/backward" -I"/Applications/Unity/Hub/Editor/2018.4.20f1/PlaybackEngines/AndroidPlayer/android-ndk-r16b/sources/cxx-stl/gnu-libstdc++/4.9/libs/armeabi-v7a/include" -c -g -DNDEBUG -funwind-tables -fno-limit-debug-info -fdata-sections -ffunction-sections -Wa,--noexecstack -fno-rtti -std=c++98 -fno-strict-aliasing -fvisibility=hidden -fvisibility-inlines-hidden -fno-strict-overflow -fPIC -Os --sysroot "/Applications/Unity/Hub/Editor/2018.4.20f1/PlaybackEngines/AndroidPlayer/android-ndk-r16b/sysroot" -gcc-toolchain "/Applications/Unity/Hub/Editor/2018.4.20f1/PlaybackEngines/AndroidPlayer/android-ndk-r16b/toolchains/arm-linux-androideabi-4.9/prebuilt/darwin-x86\_64" -target armv7-none-linux-androideabi -isystem "/Applications/Unity/Hub/Editor/2018.4.20f1/PlaybackEngines/AndroidPlayer/android-ndk-r16b/sysroot/usr/include/arm-linux-androideabi" -D\__ANDROID\_API\__=16 -march=armv7-a -mfloat-abi=softfp -mfpu=neon-fp16 -Wno-unused-value "/Users/myname/game/Temp/StagingArea/Il2Cpp/il2cppOutput/Il2CppTypeDefinitions.cpp" -o "/Users/myname/game/Library/il2cpp\_android\_armeabi-v7a/il2cpp\_cache/2106D4301BA2814B400A09E4DE4FEE7C.o"

at Unity.IL2CPP.Building.CppProgramBuilder.BuildAllCppFiles(IEnumerable\`1 sourceFilesToCompile, IBuildStatisticsCollector statisticsCollector) at Unity.IL2CPP.Building.CppProgramBuilder.Build(IBuildStatistics& statistics) at il2cpp.Program.DoRun(String\[\] args) at il2cpp.Program.Run(String\[\] args) at il2cpp.Program.Main(String\[\] args) stderr:

Unhandled Exception: Unity.IL2CPP.Building.BuilderFailedException:

Invocation was: Executable: /Applications/Unity/Hub/Editor/2018.4.20f1/PlaybackEngines/AndroidPlayer/android-ndk-r16b/toolchains/llvm/prebuilt/darwin-x86\_64/bin/clang++ Arguments: -DNET\_4\_0 -DUNITY\_AOT -DGC\_NOT\_DLL -DRUNTIME\_IL2CPP -DLINUX -DANDROID -DPLATFORM\_ANDROID -D\__linux\__ -D\__STDC\_FORMAT\_MACROS -I"/Applications/Unity/Hub/Editor/2018.4.20f1/PlaybackEngines/AndroidPlayer/Tools/bdwgc/include" -I"/Applications/Unity/Hub/Editor/2018.4.20f1/PlaybackEngines/AndroidPlayer/Tools/libil2cpp/include" -I"/Applications/Unity/Hub/Editor/2018.4.20f1/Unity.app/Contents/il2cpp/libil2cpp" -I"/Applications/Unity/Hub/Editor/2018.4.20f1/Unity.app/Contents/il2cpp/external/boehmgc/include" -I"/Users/myname/game/Temp/StagingArea/Il2Cpp/il2cppOutput" -I"." -I"/Applications/Unity/Hub/Editor/2018.4.20f1/PlaybackEngines/AndroidPlayer/android-ndk-r16b/sources/cxx-stl/gnu-libstdc++/4.9/include" -I"/Applications/Unity/Hub/Editor/2018.4.20f1/PlaybackEngines/AndroidPlayer/android-ndk-r16b/sources/cxx-stl/gnu-libstdc++/4.9/include/backward" -I"/Applications/Unity/Hub/Editor/2018.4.20f1/PlaybackEngines/AndroidPlayer/android-ndk-r16b/sources/cxx-stl/gnu-libstdc++/4.9/libs/armeabi-v7a/include" -c -g -DNDEBUG -funwind-tables -fno-limit-debug-info -fdata-sections -ffunction-sections -Wa,--noexecstack -fno-rtti -std=c++98 -fno-strict-aliasing -fvisibility=hidden -fvisibility-inlines-hidden -fno-strict-overflow -fPIC -Os --sysroot "/Applications/Unity/Hub/Editor/2018.4.20f1/PlaybackEngines/AndroidPlayer/android-ndk-r16b/sysroot" -gcc-toolchain "/Applications/Unity/Hub/Editor/2018.4.20f1/PlaybackEngines/AndroidPlayer/android-ndk-r16b/toolchains/arm-linux-androideabi-4.9/prebuilt/darwin-x86\_64" -target armv7-none-linux-androideabi -isystem "/Applications/Unity/Hub/Editor/2018.4.20f1/PlaybackEngines/AndroidPlayer/android-ndk-r16b/sysroot/usr/include/arm-linux-androideabi" -D\__ANDROID\_API\__=16 -march=armv7-a -mfloat-abi=softfp -mfpu=neon-fp16 -Wno-unused-value

# Answer
Searching for this error message reveals this thread as the very first search hit, where we find this reply from a Unity rep:

> Like mentioned in other threads, **deselect x86 architecture in Player Settings**

The second result reminds you to **select IL2CPP as your Scripting Backend** and make sure you've **ticked the ARM64 box** which is currently disabled in your screenshot because you're using Mono.

Based on the replies, you may also need to clear out your library and package folders after changing this setting and re-build, to clear out any remaining 32-bit content that was cached.

Please remember to do a basic search like this when you run into trouble, especially for standard error messages. More often than not, you'll find someone has already shared an answer to your problem.
> 1 votes

# Answer
This video solution has definitely helped ----\> https://www.youtube.com/watch?v=LuBoM1Y8mp0
> 0 votes

---
Tags: unity, android, google-play, build-process
---


# Question
Title: Improving shading of procedurally generated pixel art sprites
I've been working on a sprite generator and I'm having a hard time figuring out how to add shading automatically.

Here are some examples of the generated sprites

Currently what I'm doing is checking where a flat color meets a dark boundary, and then applying either a highlight or a shadow depending on the direction.

This is of course really boring. I've tried searching for other methods, but all I could find were AI examples. Does anyone know of any particularity simple yet clever ways of adding shading automatically?

I've thought of expanding the check up to 5 cells, and using a set of pre-determined patterns to generate the shading, but I'm just not too sure

# Answer
Shading is about indicating the 3D shape of the object, so to shade an object well you have to generate its 3D shape. On your first pass, instead of making a flat colored shape, you could make a heightmap, then in your shading pass you can color and shade the heightmap based on adjacent pixels.
> 1 votes

# Answer
For those of you following or facing a similar problem, I believe I found a relatively easy solution. Considering that I'm travelling around 360 degrees to make a shape, I can use the angle to calculate the particular shading at that point (based on the direction). The same logic is commonly used to apply normal maps

While they don't look perfect, the code can probably be tweaked to produce better results.

Here is an example of the shaded sprites:

```
for (every vertex){

    var angle = angle(current, previous);

    var scalar = angle/TWO_PI

    fill(0, 0, scalar*100); //HSB

    vertex(current);

}

```
> 1 votes

---
Tags: sprites, procedural-generation, shading
---


title: Making a licensed game you want to make

text:
# Question
Title: Making a licensed game you want to make
If I, for example, wanted to make a Spongebob game and was not asked to to do so by the company that owns the character, what would I have to do in order to get the rights to make the game?

# Answer
> 5 votes
Most often, you *don't*.

Game licensing is often a "don't call us, we'll call you" sort of affair.

If the owner of the intellectual property hasn't already decided they want a new game made with it, and started seeking out developers to do so, they're unlikely to be moved to do so by a random request out of left field.

You don't know the company's internal plans. They might be deliberately taking a break from games using the IP to avoid franchise fatigue. They might be targeting different regions, audiences, or platforms than you have in mind. They might already have another studio working on a game that's currently unannounced. They might have already signed an exclusivity deal for the video game rights that won't free up in the near future, even if no games are currently being made. So unless they come to you first, you have no evidence that a deal is even in the realm of possibility.

You're even less likely to secure such a deal if you're an unknown developer without a proven track record of high-quality, top-selling games to give them confidence you're a sound investment to make with their IP.

So, the best thing you can do is make your own original games, or work-for-hire contracts responding to IP owners who publish a request for proposals or contact you directly.

Once you have an established portfolio of high-quality work in a similar area, you have a much better chance of being contacted to work on the kinds of games you're interested in, or getting past the front door if you want to go out on a limb and pitch a game no one asked you for.

---
Tags: licensing
---


title: Getcomponent<thisScript>() vs this

text:
# Question
Title: Getcomponent<thisScript>() vs this
I am referencing singleton script's object from another script and I wonder what is difference between this two, or if even work the second one properly?

```
GameManager.Instance.selectedBuildSite = GetComponent<BuildSite>();

```

VS

```
GameManager.Instance.selectedBuildSite = this;

```

The code is written inside BuildSite class which inherits monobehaviour

# Answer
> 4 votes
There is never a reason to search for a reference to a component if you already have a reference to the component you want to use.

`this` inside a non-static class method refers to the instance of the class currently running that method. So here, `this` is the specific `BuildSite` component that's running this method.

`GetComponent<BuildSite>()` will search all the components attached to `this.gameObject` until it finds one that is a `BuildSite` and return that. That search can be costly, so we don't want to pay that cost unnecessarily.

The only time when that might give a different result than `this` when run from inside your `BuildSite` script is if you have two `BuildSite` components attached to your object - which would probably be an error for your case, or at the very least, you'd want to enforce some logic about which one should be chosen, rather than leaving it up to the whims of which one the search finds first.

**tl;dr:** if `this` is what you want to reference, just say `this`.

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


# Question
Title: In unity i have this code that has to make a lot of allocation but no new variables are creates, but still the RAM usage just keeps climbing
So I have this code that has four for-loops inside each other, so there are a lot of actions, but no new Space should be needed. Still, when trying to run this, Unity stops responding and in the Task-Manager I just see the RAM-Usage steadily climbing up while the CPU-Usage is pretty much constantly on 10%.

This is the Code:

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

public class SceneGenerator : MonoBehaviour
{

    public GameObject spawnee;

    // Start is called before the first frame update
    void Start()
    {
        pos4d mpos = new pos4d();
        float r = 1;

        pos4d campos = new pos4d();
        campos.s = 3;

        pos4d viewpos = new pos4d();
        viewpos.s = 3.5f;

        //pos4d[,,] grid = new pos4d[10,10,10];
        pos4d dir = new pos4d();
        pos4d raypoint = new pos4d();

        for (int i = 0;i < 10;i++) {
            for (int j = 0;j < 10;j++) {
                for (int k = 0;k < 10;k++) {
                    /*
                    grid[i,j,k] = new pos4d();
                    grid[i,j,k].x = i/10-0.5f;
                    grid[i,j,k].y = j/10-0.5f;
                    grid[i,j,k].z = k/10-0.5f;
                    grid[i,j,k].s = 3;
                    */

                    dir.x = (i/10-0.5f - viewpos.x)/10;
                    dir.y = (j/10-0.5f - viewpos.y)/10;
                    dir.z = (k/10-0.5f - viewpos.z)/10;
                    dir.s = (3 - viewpos.s)/10;

                    raypoint.x = i/10-0.5f;
                    raypoint.y = j/10-0.5f;
                    raypoint.z = k/10-0.5f;
                    raypoint.s = 3;

                    for (int step = 0;step < 1000;step++) {
                        Debug.Log("" + (i+j+k+step));
                        if (Mathf.Sqrt(Mathf.Pow(raypoint.x - mpos.x,2) + Mathf.Pow(raypoint.y - mpos.y,2) + Mathf.Pow(raypoint.z - mpos.z,2) + Mathf.Pow(raypoint.s - mpos.s,2)) <= r) {
                            Instantiate(spawnee,new Vector3(i/10-0.5f,j/10-0.5f,k/10-0.5f),Quaternion.identity);
                            break;
                        }
                        raypoint.x += dir.x;
                        raypoint.x += dir.y;
                        raypoint.x += dir.z;
                        raypoint.x += dir.s;
                    }
                }
            }
        }
    }

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

    }
}

public class pos4d {
    public float x = 0;
    public float y = 0;
    public float z = 0;
    public float s = 0;
}
```

# Answer
> 2 votes
`Instantiate` seems to be the culprit here. You're trying to instantiate THOUSANDS of new game objects in a single frame. I would recommend to delay the instantiate by batches of 100 per frame.

---

EDIT:

And I'm not even mentionning the thousands of new pos4d and new Vector3 that are called.

---
Tags: unity, memory
---


title: How to know when the cameras change?

text:
# Question
Title: How to know when the cameras change?
I'm working on a script that uses raycasting from the camera's perspective to see what the player is looking at. Pretty standard stuff. The only question is, how to reliably find the camera?

Everything I've seen says you don't want to use `Camera.main` in `Update()` because performance, so instead you should call it once in `Start()` and cache it in a field. And that's great, as long as you can guarantee that the main camera will never change. But what if it does?

What I'd like is to have some sort of OnCameraUpdated event I can subscribe to that will let me know when the main camera has changed, but I don't see anything like that on the `Camera` class. Is there any good way to find this out without polling for it?

# Answer
> 2 votes
If you can't rely on the code that's changing the camera to tell you, then about the best you can do is check to see if your cached camera has been disabled/destroyed, and trigger a new search only when that happens:

```
static Camera _cachedCurrentCamera;

void Update() {
    if(_cachedCamera == null || _cachedCamera.isActiveAndEnabled == false)
        _cachedCurrentCamera = Camera.main;
}

```

But you can expose a camera changed event handler of your own, for game code to call when they change the camera, if they want to avoid any searches at all. Then the ball is in their court to control their own performance, even if you can't force them to use it:

```
public static void OnCameraChanged(Camera newCamera) {
    _cachedCurrentCamera = newCamera;
}

```

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


# Question
Title: How to scale bitmap font without having it pixelated
How do i increase the size of a bitmap font without having it get pixelated, in libgdx?

# Answer
> 2 votes
There are some pretty good suggestions in the other answers here. I would like to add one that is more libgdx specific (so you hopefully don't have to reinvent the wheel).

BitmapFonts in libgdx are raster(bitmap) images and will pixelate just like any other raster image when scaled. The solution that I usually use is that if I want a font in different sizes, then I have to pre-create a font for each size. A great tool that does this that is packaged with libgdx is Hiero. Managing all these fonts can be easy if you use libgdx's AssetManager

The second option that libgdx uses is TTF fonts. TTF files are vector images so they scale perfectly. Unfortunately, the downside is that libgdx cheats a little bit because rather than keeping the TTF file in memory and drawing from it, you use the TTF file to create a bunch of `BitmapFonts` that are pre-scaled without pixelation and then you actually draw the `BitmapFont`. You have to add the FreeType extension to your project to do this. Once you do that, you can programatically create scaled fonts to your heart's content like so

```
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("fonts/myfont.ttf"));
FreeTypeFontParameter parameter = new FreeTypeFontParameter();
parameter.size = 12;
BitmapFont font12 = generator.generateFont(parameter); // font size 12 pixels
parameter.size = 32;
BitmapFont font32 = generator.generateFont(parameter); // font size 32
generator.dispose(); // don't forget to dispose to avoid memory leaks!

//Then use your fonts

```

Using TTF fonts is more processing, but the upside over BitmapFonts is that you can change the font sizes in the code all you want.

# Answer
> 1 votes
You will have to use **signed distance field** font rendering.

The generated font's pixels represents the distance from the edge rather than the opacity.

Where 0.5 (0x7F) is the edge of the font, 0.0 (0x00) is the outside, 1.0 (0xFF) is the inside.

How wide this extends is up to you, in the grey scale example image I'm using a 2-pixel distance so it reaches 0x00 2 pixels away from the edge and 0xFF 2 pixels inside the edge. It is possible to use a half-pixel border (ie: a regular anti-aliased font bitmap) to avoid writing your own font converter/generator but depending on the AA technique it may create wobbly edges.

To draw using a pixel shader you render \> 0.5 as opaque, \< 0.5 as transparent. On fixed-pipeline hardware the Alpha Test function does the trick

On the left is the distance field texture. On the right is the result. When interpolated the approximated curve is recreated by the nature of the interpolation (bottom part):

Below is a screenshot of a 24 pixel high distance field font scaled up to 256 pixel high rendered on 3D hardware. You can see some slight distortion of the corners but no pixelation.

Also, make sure to not compress the texture. It needs to be stored as a 8bits per channel or at worst 4bits per channel. A texture compressed using ETC, DXT or other compression will loose too much precision to recreate the edges properly.

A common trick is to use all 4 channels (red, green, blue, alpha) to encode different characters as 4 grey-scale textures inside a single texture. This is what it looks like:

# Answer
> 1 votes
I stumbled upon this answer after getting frustated for 2 days and get this really simple solution. Though I wonder why is there no proper documentation for this most basic task.

If you want to scale bitmap font using hiero, you can use:

```
    BitmapFont font = new BitmapFont(Gdx.files.internal("data/myfont.fnt"));
    font.getData().setScale(0.15f);

```

Or, you can even use gdx-freetype if you want to scale font during runtime as:

```
public BitmapFont generatefont() {
    FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("data/myfont.otf"));
    FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
    parameter.size = 32;
    parameter.magFilter = Texture.TextureFilter.Linear;
    parameter.minFilter = Texture.TextureFilter.Linear;
    BitmapFont font32 = generator.generateFont(parameter); // font size 32 pixels
    font32.getData().setScale(0.15f);
    generator.dispose();
    return font32;
}

```

Both gives pretty fair result.

# Answer
> 0 votes
You could avoid the blur effect when upscaling by using a high-resolution image font and drawing it downscaled. Example: if your font is supposed to be drawn with a 24px size, use a sample at 48px and draw the text with a scale ratio of 0.5, because downscaling won't make aliasing noticeable.

This does work fine as long as your font image strip doesn't take too much space to be saved. Also, having different scale sample of the same font can be handy not to cause too much overhead on the rendering - downscaling a 60px font to a factor of 0.25 is slower than having the same font in 15px, the latter can be just drawn at its original size.

---
Tags: java, libgdx, game-design
---


# Question
Title: Baked vs realtime global illumination in unity
I use unity. So far I know that the baked GI is less GPU processing when the game is played so if possible, I need to use baked GI.

Newbie question: I'm using unity and just curious in the light setting, is there any situation or in what condition that we can turn on both realtime and baked GI at the same time? Or is it only practical to turn on one of them?

# Answer
> 1 votes
First of all, the setting "Realtime Global Illumination" in the Unity Lighting Window is deprecated. It only applies to the legacy rendering pipeline. It has no effect on the new scriptable render pipelines (URP, HDRP or a custom one).

Here is an example scene rendered with the build-in pipeline. The two lights are identical except that the left one is baked and the right one is real-time.

Here is the scene with Baked GI on and Realtime GI off:

As you can see, there are notable differences. The right one generates a specular highlight on the sphere in the center while the left one doesn't. Also note that the walls, ceiling and floor on the left side is slightly brighter. This is because GI simulates indirect light which bounces off of bright surfaces.

Here is the same scene, but with Realtime Global Illumination on but Baked Global Illumination off:

Now both lights are simulated in real-time, so they look identical. The whole scene is slightly brighter because both lights generate light bounces.

Now when you enable both systems at the same time you get this:

A much brighter image which has the differences caused by combining realtime and baked lights in a baked scene. Apparently Unity adds the light from both systems. So you got the cost of both systems and the disadvantages of both systems.

So no, you should not do this.

---
Tags: unity, realtime, lightmap, global-illumination
---


# Question
Title: Implement spherical mapping for texture coordinates
I am using a texture of a world map and I am trying to put that image on a sphere made up of many triangles. Each triangle has points a,b,c with their own (x,y,z) coordinates.

I am trying to use the coordinate system conversions formula from Wikipedia. This is my world to spherical coordinates function:

```
function worldToSpherical(p) {

  const r = Math.sqrt(Math.pow(p[0],2)+ Math.pow(p[1],2) + Math.pow(p[2],2));
  const u = Math.atan2(p[1],p[0]);
  const i = Math.atan2(Math.sqrt(Math.pow(p[0],2)+Math.pow(p[1],2)),p[2]);

  const s =  r * Math.sin(i) * Math.cos(u);
  const t =  r * Math.sin(i) * Math.sin(u);
  return [s, t];

}

```

But this is what my output looks like:

It seems to be wrapping around twice. Am I using the wrong formula, or using it wrong?

# Answer
> 0 votes
You just went to a lot of trouble to undo the trig on your `u` and `i` variables! Don't re-trig them with `cos` and `sin`! Just compress the range from the radian angles to your 0...1 texture coordinate space.

```
function worldToSpherical(p) {

   const radius = Math.sqrt(p[0]*p[0] + p[1]*p[1] + p[2]*p[2]);
   const longitudeRadians = Math.atan2(p[1], p[0]);
   const latitudeRadians = Math.asin(p[2]/radius);

   // Convert range -PI...PI to 0...1
   const s =  longitudeRadians/(2 * Math.PI) + 0.5;

   // Convert range -PI/2...PI/2 to 0...1
   const t =  latitudeRadians/Math.PI + 0.5;
   return [s, t];
}

```

---
Tags: textures, javascript, glsl
---


# Question
Title: Persisting unlocked characters in Player Prefs
I am working on a character selection menu in Unity.

If you have enough coins, you can buy your desired character. Once player buys one, that character must not be locked on game restart, the number of coins must not be changed again, and the lock image (a GameObject I defined under name "wood" and acts as a lock) must disappear.

Everything works fine when I buy one character, but when I buy another one, the previous one returns to locked mode, but its image (wood) has already disappeared (I mean, I should have enough coins to re-buy an already bought character).

I guess there must be something wrong with this code `isPlanesold = PlayerPrefs.GetInt("isPlanesold");` because it changes as a character is bought.

Here is my script:

```
int isPlanesold;
public static int chnum; //character number that must be referenced on another scene
public Button WhitePlane;
public Button YellowPlane;
public GameObject wood1;
public GameObject wood2;

void Start () {

        PlayerPrefs.SetString ("BluePlane", "on");
        if (PlayerPrefs.GetString ("WhitePlane") == "on") {
            wood1.SetActive (false);
        }
        if (PlayerPrefs.GetString ("YellowPlane") == "on") {
            wood2.SetActive (false);
        }

                UIManager2.coin_score = PlayerPrefs.GetInt ("Score");
        isPlanesold = PlayerPrefs.GetInt ("isPlanesold");

}

            public void BuyWhitePlane () {

        if (isPlanesold == 1) {
            PlayerPrefs.SetInt ("isPlanesold", 1);
            chnum = 2;
            PlayerPrefs.Save ();
            SceneManager.LoadScene ("Menu2");
        } else if (UIManager2.coin_score >= 1) {
            PlayerPrefs.SetInt ("isPlanesold", 1);
            chnum = 2;
            PlayerPrefs.SetInt ("Score", UIManager2.coin_score--);
            PlayerPrefs.SetInt ("Score", UIManager2.coin_score);
            PlayerPrefs.Save ();
            PlayerPrefs.SetString ("WhitePlane", "on");
            SceneManager.LoadScene ("Menu2");

            }
        else
        {
            Debug.Log ("You Don't Have The Score");

        }

    }

    public void BuyYellowPlane () {

        if (isPlanesold == 2) {
            PlayerPrefs.SetInt ("isPlanesold", 2);
            chnum = 3;
            PlayerPrefs.Save ();
            SceneManager.LoadScene ("Menu2");
        } else if (UIManager2.coin_score >= 2) {
            PlayerPrefs.SetInt ("isPlanesold", 2);
            chnum = 3;
            PlayerPrefs.SetInt ("Score", UIManager2.coin_score -= 2);
            PlayerPrefs.SetInt ("Score", UIManager2.coin_score);
            PlayerPrefs.Save ();
            PlayerPrefs.SetString ("YellowPlane", "on");
            SceneManager.LoadScene ("Menu2");

        }
        else
        {
            Debug.Log ("You Don't Have The Score");

        }

    }

```

`PlayerPrefs.SetString ("BluePlane", "on");` refers to a character that's unlocked by default.

# Answer
I'd factor the idea of a purchasable item into its own class, so you don't have to copy and paste code for each purchasable. Instead you can add this component to each button representing an item you want to buy:

```
public class Purchasable : MonoBehaviour {

    public enum PurchasableID : int {
        BluePlane,
        WhitePlane,
        YellowPlane
    }

    [System.Serializable]
    public class PurchaseEvent : UnityEvent<PurchasableID> {}

    public PurchasableID id;

    // 0 will stand for "Unlocked by default"
    public int coinCost = 0;

    public GameObject disabledImage;

    public PurchaseEvent OnPurchase;
    public PurchaseEvent OnUse;

    public bool IsUnlocked() {
        return coinCost == 0 || PlayerPrefs.GetInt("Unlocked" + id.ToString(), 0) > 0;
    }

    void Start() {
        // If we've been unlocked already, hide our disabled image on start-up.
        if(disabledImage != null && IsUnlocked())
            disabledImage.SetActive(false);
    }

    // Wire up your purchase buttons to call this method when clicked.
    public void BuyOrUse() {
        if(IsUnlocked())
        {   // Already bought this one, so let's just use it!
            OnUse.Invoke(id);
        }
        else if (Wallet.instance.TryPay(coinCost))
        {   // We can afford it, so buy it and mark it unlocked.
            PlayerPrefs.SetInt("Unlocked" + id.ToString(), 1);
            PlayerPrefs.Save();
            disabledImage.SetActive(false);
            OnPurchase.Invoke(id);
        }
        else
        {   // Nope, can't afford it. Maybe play a failure sound here.
            Debug.Log ("You Don't Have The Score");
        }
    }
}

```

Here I also factored out a Wallet type to manage your coin score, ensuring it's saved properly when earning/spending. I set it up as a singleton for ease of referencing, while also letting you peek at your current coin balance in the Inspector, or change the value there for debugging.

```
public class Wallet : MonoBehaviour {

    public static Wallet instance;

    [SerializeField]
    private int _coinBalance = 0;
    public int coinBalance { get { return _coinBalance; } }

    void Awake() {
        if(instance != null)
        {
            Debug.LogWarning("You've spawned two Wallets in the same scene!");
            Destroy(this);
            return;
        }

        instance = this;
        _coinBalance = PlayerPrefs.GetInt("coinScore", 0);
    }

    public bool TryPay(int cost) {
        // If we can't afford it, report back "No."
        if(cost > _coinBalance)
            return false;

        // If we can afford it, update our balance, and reply back "Yes."
        _coinBalance -= cost;

        // Technically this is redundant, since whatever we bought will likely call
        // its own save. If you trust in that, you can delete this line. ;)
        PlayerPrefs.SetInt("coinScore", _coinBalance);

        return true;
    }

    // Increment our coin score and save the progress.
    public void Earn(int earnings) {
        _coinBalance += earnings;
        PlayerPrefs.SetInt("coinScore", _coinBalance);
    }
}

```

Now your UI Manager can have a function like this:

```
public void SelectCharacter(Purchasable.PurchasableID character) {
    characterNumber = (int)character;
    SceneManager.LoadScene ("Menu2");
}

```

And you can wire up your purchasables' OnBuy / OnUse methods to call this.

The reason I set these up as separate events is that someday you might have purchasable objects that aren't characters, but upgrades, or skins, or other things that still need the core purchase logic, but need to trigger a different action when the player uses them. This gives you that flexibility, without writing new code for that case when it arises.
> 0 votes

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


# Question
Title: How to avoid many import iterations while generating sub assets?
I have a `ScriptedImporter` that generates other assets in the same directory.

Whenever it happens, import progress bar pops in again, this time like `Importing (iteration N)`.

I've tried to use AssetDatabase.DisallowAutoRefresh to circumvent this behavior but that failed.

**Question:**

How to prevent subsequent import iterations and rather group them to happen all at once ?

# Answer
> 1 votes
By directly putting things in `AssetImportContext` this problem will go.

**Advantages:**

* asset is a script and not a blank icon anymore
* it's importing faster
* assets are **read-only**, very interesting :D
* everything is in one place
* less assets to deal with

**Disadvantages:**

* all sub assets are in asset, pretty hard to navigate in project browser
* assets needs unique names, quite easy actually
* things like textures lose fully featured importer

A cool trick is to make a ZIP file in which you put whatever you want but then give it another extension so you can differentiate file formats.

I came up with this to decorate `ScriptableObject`s trees:

```
[PublicAPI]
public interface IAsset
{
    [NotNull]
    string Name { get; set; } // this can be customized but should be unique then

    [NotNull]
    [ItemNotNull]
    IEnumerable<IAsset> GetDescendants(); // to traverse tree

    [NotNull]
    string GetPrefix(); // for generating name automatically
}

public static class IAssetExtensions
{
    public static void AddSelfAndDescendants(
        [NotNull] this AssetImportContext context, [NotNull] IAsset asset, IAssetFlags flags = IAssetFlags.Default)
    {
        if (context is null)
            throw new ArgumentNullException(nameof(context));

        if (asset is null)
            throw new ArgumentNullException(nameof(asset));

        var generator = new UniqueNameGenerator();

        var queue = new Queue<IAsset>(new[] {asset});

        while (queue.Any())
        {
            var dequeue = queue.Dequeue();

            if (dequeue is IAsset iAsset)
            {
                var descendants = iAsset.GetDescendants();

                foreach (var descendant in descendants)
                {
                    queue.Enqueue(descendant);
                }
            }

            if (flags.HasFlagFast(IAssetFlags.Rename) && string.IsNullOrWhiteSpace(dequeue.Name))
                dequeue.Name = generator.GetName(dequeue.GetPrefix());

            context.AddObjectToAsset(dequeue.Name, dequeue as Object);
        }

        context.SetMainObject(asset as Object);
    }
}

public sealed class UniqueNameGenerator
{
    public UniqueNameGenerator([CanBeNull] IDictionary<string, int> dictionary = null)
    {
        Dictionary = dictionary ?? new Dictionary<string, int>();
    }

    [NotNull]
    private IDictionary<string, int> Dictionary { get; }

    [NotNull]
    public string GetName([NotNull] string prefix)
    {
        if (string.IsNullOrWhiteSpace(prefix))
            throw new ArgumentException("Value cannot be null or whitespace.", nameof(prefix));

        if (!Dictionary.ContainsKey(prefix))
            Dictionary.Add(prefix, default);

        var suffix = Dictionary[prefix];
        var unique = $"{prefix} {suffix}";

        Dictionary[prefix]++;

        return unique;
    }
}

```

Summarized but you get the general idea.

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


# Question
Title: Asset is up to date but does not have a correct hash assigned in GuidPersistentManager
I have a `ScriptedImporter` that generates a few extra assets, this works fine except when I re-import it after version upgrade, I get the following message:

```
Asset with guid 'bbe94cef9d5f3464ab6ba6913e6747a2' and path '...' is up to date, but does not have a correct target hash assigned to it in the GuidPersistentManager
UnityEngine.UnitySynchronizationContext:ExecuteTasks()

```

Inside that `ScriptedImporter` I've tried `File.Delete`, `AssetDatabase.Refresh`, `AssetDatabase.ImportAsset` but neither helped out, only when I delete it manually it does work.

Furthermore, that error message is quite useless as basically Unity handles it but still notifies you.

Note that the asset generated is next to the format being imported, this is because if for instance you create a texture and add it to the `AssetImportContext` then it becomes readonly in the Inspector and cannot be tweaked further. So basically I generate a PNG file in same folder which then has the usual `TextureImporter` that can be edited as will.

**Question:**

How to avoid incorrect GUID errors when re-importing an asset generated by a `ScriptedImporter`?

Alternatively, how to solve this incorrect GUID clash when overwriting an asset?

# Answer
That pseudo code works somewhat but is slow, this is when the asset exists and you want to avoid that error by updating its:

```
RemoveContentFromAsset(asset); // AssetDatabase.RemoveObjectFromAsset recursive
EditorUtility.CopySerialized(track, asset);
AddContentToAsset(asset); // AssetDatabase.AddObjectToAsset recursive
AssetDatabase.SaveAssets();
// this will refresh project browser and fix empty sub asset editor but is slow
// EditorUtility.RequestScriptReload(); // stupid project browser won't refresh view otherwise

```

But I've opted this way instead:

How to avoid many import iterations while generating sub assets?
> 0 votes

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


# Question
Title: 2D engine design/architecture: transformations
**Hello!** I'm working on this hobby little 2D engine in JavaScript because I want to learn how all this things are implemented and architectured in general. Internet is full of resources but most things are mathematical or theoretical stuff, there is very little about implementation or architecture for small 2D engines like the one I'm working in. So, this is my context and at the end are some questions I hope you can help me with:

I have a **Body** object that has different properties like (pseudo-code):

```
Body {
    angle: float
    scale: float
    acceleration: 2d vector
    velocity: 2d vector
    position: 2d vector
    update: function()
}

```

A Body object also has a **Model** object, which has (pseudo-code):

```
Model {
    points: Array of [x, y] points
    fillColor: string (hex)
    transform: function(rotate, scale, translate)
}

```

*The transform function receives Angle, Scale and Translate, and returns a new transformed instance of the model.*

On every frame I will update the **Body** object to represent the current state: adding accelerator vector to velocity, velocity to location (and some similar stuff to update the angle and scale if required):

```
Body {
    update() {
        this.velocity.add(this.acceleration)
        this.location.add(this.velocity)
        this.acceleration.reset()
    }
}

```

Once the Body object is updated I must do a *world-transform* of the model so that I can start doing physics related stuff *(like collision detection/resolving, interaction forces between bodies, etc)*. After that I will do a *view-transform*, to transform the world-objects into the "perspective" of some other object.

At the moment this is my solution is based in keeing three instances of the Model object withing the Body object, like this:

```
Body {
    model: the original *Model* with no transformations
    model_world: result of *Model.transform(body.angle, body.scale, body.location)*
    model_view: the result of transforming **model_world** instance with viewport properties
}

```

**Questions:**

* Do you think there is a better way to handle model transformations? Like maybe one the do not require the Body object to mantain the three instances of the three transformations itself, perhaps.
* Can you please give me some suggestions on how to better organize this functionality for a simple 2D engine?

Thank you very much in advance!

# Answer
In my humble opinion, the way you are currently tackling this problem is quite smart! That said, my concern with your current method is that the amount of memory you will be using to store 3 unique transformations of an object will increase dramatically for each object you add to your game. In fact, I'm pretty sure later on you will wish you didn't keep the 3 transformations separate!

I looked back at some code I wrote previously, and the process I'm using is the same as you are. I am simply doing it sequentially and not using separate objects/models.

* Determine how much the object's position will increment before collisions
* Determine how much the object's position is allowed to increment based on its collisions
* Transform the object's position based on its allowed amount
* Render the object

You can optionally pass the object to your viewport transform and pass the result to the renderer. You ask how to organize this, so I will give you an example to illustrate my approach more clearly.

I have a player class - you may call it a body. This is it's update function:

```
update() {
    // update velocity
    if (*condition*) {
        this.decelerate(dt);
    }
    else if (*condition*) {
        this.velocity.x += controls.x * dt * this.acceleration;
    } else {
        ...
    }

    let x_offset = this.velocity.x;
    let y_offset = 0;
    // if jumping I set the y_offset

    // returns edges collided and a valid x and y increment
    const position = collision(this, this.map, x_offset, y_offset);

    // logic based on edges collided if needed

    // increment position
    this.x += position.x;
    this.y += position.y;

    // logic after you have the "world" model
}

```

I don't know how your main game loop works or how this integrates with your renderer, so I can't really give specifics on how to construct your view-transform, but I think you could create a function that just takes your objects, makes a transformation, and passes it to the renderer. Or maybe you just want to make a camera, I'm not too sure from your descriptions. Anyway, feel free to ask me any questions. I hope this helps some!
> 0 votes

---
Tags: 2d, javascript, models, transformation
---


title: Move with velocity based on rotation

text:
# Question
Title: Move with velocity based on rotation
So I have a simple script to move a character. The problem is that no matter where i'm looking at (my y rotation) it always makes me go the direction if I try to go forward, but I want it to go toward where i'm looking when I go forward or relative to where i'm looking for any direction. HOw can I do this ? (also I do not want to use a already existing fps controller) transform.forward works but only if I go forward or backward, not for left right or diagonal. (placed on player)

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

public class player : MonoBehaviour
{
public float speed;
Rigidbody rb;

void Start()
{
    rb = gameObject.GetComponent<Rigidbody>();
}

void Update()
{
    float x = Input.GetAxis("Horizontal");
    float z = Input.GetAxis("Vertical");
    rb.velocity = new Vector3(x*speed.rb.velocity.y,z*speed);
}
}

```

for my camera, I am using a script I found online: (placed on player)

```
using System;
using UnityEngine;

public class mouseLook : MonoBehaviour
{
public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
public RotationAxes axes = RotationAxes.MouseXAndY;
public float sensitivityX = 15F;
public float sensitivityY = 15F;
public float minimumX = -360F;
public float maximumX = 360F;
public float minimumY = -60F;
public float maximumY = 60F;
Rigidbody rigidbody;
float rotationY = 0F;

void Update ()
{
    if (axes == RotationAxes.MouseXAndY)
    {
        float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse
X") * sensitivityX;
        rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
        rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);
        transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
    }
    else if (axes == RotationAxes.MouseX)
    {
        transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0);
    }
    else
    {
        rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
        rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);
        transform.localEulerAngles = new Vector3(-rotationY,
transform.localEulerAngles.y, 0);
    }
}

void Start ()
{
    Cursor.lockState = CursorLockMode.Locked;
    rigidbody = gameObject.GetComponent<Rigidbody>();
    if(GetComponent<Rigidbody>())
    {
        GetComponent<Rigidbody>().freezeRotation = true;
    }
}
}

```

# Answer
You can use the object's transform to turn an arbitrary direction in local space to a direction in world space:

```
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");

// Some sticks/arrow keys will let both axes be 1 at once.
// ClampMagnitude ensures diagonals obey our max speed.
Vector3 localVelocity = Vector3.ClampMagnitude(new Vector3(x, 0, z), 1) * speed;

rb.velocity = transform.TransformDirection(localVelocity);

```

Note that, as written, this can cause the character to try to fly upward if looking to the sky. You can avoid that by instead forming a quaternion representing your "foot space" ground orientation (say, by getting the normal of the ground under you from a raycast), and rotating your local velocity by that quarternion. I show an example of something like that here.
> 1 votes

# Answer
One suggestion is to use `TransformDirection`:

```
Vector3 v = new Vector3(x, 0, z);
rb.velocity = transform.TransformDirection(v);

```

Another is to use `AddRelativeForce`:

```
rb.AddRelativeForce(v, ForceMode.Acceleration);

```

I would prefer the second option, but keep in mind that method is adding to the velocity instead of overriding it each update.

Also, you should only use the RigidBody methods inside FixedUpdate().
> 0 votes

# Answer
Just use `transform.`, you get a vector that is pointing relative to the object.

If you don't want object to fly up when its transform is looking into the sky, do this:

```
    float x = Input.GetAxis("Horizontal");
    float z = Input.GetAxis("Vertical");

    Vector3 forward = transform.forward;
    //here, make Y component of the vector 0, thus only using it for direction on the flat plane.
    forward.y = 0;

    rb.velocity = forward * speed * z + transform.right * speed * x;

```
> 0 votes

---
Tags: unity, 3d, movement, first-person-shooter
---


# Question
Title: combine two translation/rotation/scale triplets without matrices
Let t1/2, r1/2 and s1/2 be two sets of transformations. Translations are vec3, rotations are quaternions and scales are vec3. Lets assume that all common operations are defined (overloaded operators in c++).

How do I combine (in what order) the two sets of transformations into a third set t3, r3 and s3, such that mat4(t1, r1, s1) * mat4(t2, r2, s2) == mat4(t3, r3, s3), without actually converting to matrices?

Mat4 is composed as M = T * R * S. (OpenGL conventions, if it makes any difference)

Thanks

---

My original code:

```
transform transform::operator * (const transform &other) const
{
    transform r;
    r.orientation = orientation * other.orientation;
    r.scale = scale * other.scale;
    r.position = position + (other.position * orientation) * scale;
    return r;
}

```

this used to work when scale was just one number (uniform scale). But it does not work with non-uniform scale. I guess that one of the scales have to be rotated, but I am failing to find the correct way.

---

This is how I test it:

```
for (uint32 round = 0; round < 10; round++)
{
    vec3 pa = randomDirection3() * randomRange(-5, 20);
    vec3 pb = randomDirection3() * randomRange(-5, 20);
    quat oa = randomDirectionQuat();
    quat ob = randomDirectionQuat();
    vec3 sa = randomRange3(real(0.1), 10);
    vec3 sb = randomRange3(real(0.1), 10);
    transform ta(pa, oa, sa), tb(pb, ob, sb);
    test(mat4(ta * tb), mat4(ta) * mat4(tb));
}

```

# Answer
I believe this is how you do it:

```
transform transform::operator * (const transform &other) const
{
    // mat1 = T1 * R1 * S1; mat2 = T2 * R2 * S2
    // mat = mat1 * mat2; mat*v = mat1 * mat2 * v
    // assuming "this" is mat1, and other is mat2
    // alternatively "this" can be considered parent, and other child in a node hierarchy
    transform r;
    // R = R1 * R2
    r.orientation = orientation * other.orientation;
    // Note: I don't know how to implement inverse of quat in your lib
    // S = R2^-1 * (S1 * (R2 * S2))
    r.scale = inverse(other.orientation) * (scale * (other.orientation * other.scale));
    // T = T1 * (R1 * (S1 * T2))
    r.position = position + (orientation * (scale * other.position));
    return r;
}

```
> 1 votes

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


title: Ways to move a character in Unity

text:
# Question
Title: Ways to move a character in Unity
I am studying Unity, and so far I encountered three different ways to move a character. As far as I understand:

* Directly changing the transform - ignores both physics and colliders;
* Using a CharacterController component - ignores physics but considers colliders;
* Using a RigidBody component - considers both physics and colliders.

Are these descriptions correct? Which one should I use?

# Answer
> 2 votes
1. Changing the transform ignores colliders *at that moment*, but for clarity you should mention that this does not mean that it won't have any physical effect at all. When the physics engine does its next update after the transform manipulation resulted in two overlapping rigidbodies, then it will try to push those two colliders apart. Personally I like the distinction: "changing the position doesn't *move* an object, it *teleports* an object".
2. The distinction between rigidbody and transform is not so simple. There are many ways to use the rigidbody component which are worth examining in detail because they have subtle differences:
    * Changing `rigidbody.position` which is not much different from changing `transform.position`
    * Changing `rigidbody.velocity`
    * Using the `rigidbody.MovePosition` method
    * Using the `rigidbody.AddForce` method

A while ago I created a little demo where you can try out different movement methods and see their side-effects for yourself.

---
Tags: unity, movement
---


title: Light Attenuation Formula Derivation

text:
# Question
Title: Light Attenuation Formula Derivation
I understand that when sampling the brightness of a given point on the surface, a certain cutoff needs to be taken into consideration.

Other words, when the light is further away, the intensity decreases.

I came across the following formula that is used to compute the aforementioned:

```
attenuation = 1.0 / (1.0 + a * dist + b * dist * dist)

```

However, I have not been able to find out why and how this formula is derived.

From the formula what I can understand is that as the distance get larger, the result will become smaller; but how it is derived is beyond me.

If distance takes an important role in the above formula, which helps determine the intensity, could we simply ignore `a` and `b` from the formula and simply use:

```
attenuation = 1.0 / (1.0 + dist)

```

?

Does anyone know how the formula is derived and the importance the values `a` and `b` play within the formula?

Thanks.

# Answer
> 6 votes
**In real physics, light (like many other influences) falls off as the inverse square of distance from the source.**

You can visualize this by imagining a lightbulb giving off one instantaneous flash - the photons of light released form a hollow sphere expanding away from the bulb like a ripple in a pond. As the sphere expands, no new photons or energy are added to it, so the same amount of brightness is spread across a wider and wider area. If we sample the brightness at one distance (say 1 metre), then wait until the sphere has grown twice as big, its surface area is now four times as large, so the brightness at any one spot will be one quarter of what we saw before. At triple the distance, the sphere has nine times the area, so the brightness will be one ninth, etc.

(This is simplified, of course. Ask on the Physics StackExchange if you want all the messy details of waves and quantum stuff etc...)

So, by this theoretical line of thinking, `attenuation = 1.0 / (dist * dist)`

(Where our "reference brightness" for the light is measured one unit away, where attenuation = 1)

---

Okay, now we enter the practical world of cheats that make sense for computer hardware and help us do our jobs as game developers.

**Firstly: the formula above has a big problem: it has a singularity when distance is zero!**

Usually in physics we'd only model a light source as an infinitely small point like this if we're enough distance away that the approximation won't matter, but in games our point/spot lights are often literally infinitely small points, and if we're not careful, geometry in our scene could get quite close to them or even cross them, making the math become very ill-behaved (eg. as your firefly lands on a leaf, it makes a bright spot brighter than the Sun)

So, we fix that by adding an offset: `attenuation = 1.0 / (1.0 + dist * dist)`

Now even if distance approaches zero, `attenuation` will never exceed 1.0, and so the light will never shine brighter than the reference brightness we've set.

(Our reference brightness is now measured at the position of the light itself, rather than one unit away. If we want the same behaviour at the 1 unit mark, we'll need to double the reference brightness compared to the previous/physical version of the formula)

**Great. But it's not very customizable.**

When we're lighting a game, we often care more about control to be able to get the look we want, rather than strict obedience to physical laws. So we add a coefficient that lets us make the falloff a little sharper or a little shallower. In fact, let's add two coefficients so we can shape the falloff curve:

Now we get the familiar `1.0 / (1.0 + a * dist + b * dist * dist)`

So, why add that linear term? This answer suggests that it was useful in older games when rendering without proper gamma correction. The display gamma plus an inverse square falloff would combine to make the light falloff look too sharp. By using an inverse linear falloff (a ~ 1, b ~ 0) we can cheat it to look more correct, letting the display gamma do the squaring. In modern games though, we'd prefer to do proper gamma correction (in addition to things like HDR tonemapping) to make sure our colours look right, so nowadays we'd usually only play with these coefficients for stylistic reasons.

**tl;dr: a = 0, b = 1 is a pretty safe bet unless you want a more stylistic effect.**

# Answer
> 2 votes
This attenuation formula lets you express the light falloff from a spherical area light.

This article shows how to derive the coefficients to use for a light of radius r:

$$\begin{align} f\_{att} &= \frac 1 {\left( \frac d r + 1\right)^2}\\ & = \frac 1 {1 + \frac 2 r d + \frac 1 {r^2} d^2}\\ \\ a &= \frac 2 r, \quad b = \frac 1 {r^2} \end{align}$$

See the full article for more details on clipping the range of effect for these lights, and shader code.

---
Tags: opengl, lighting
---


# Question
Title: How to draw a 2D cross-section of a 3D object?
I am creating a game where I only want the user to see the 2D intersection of a plane with a 3D object. The goal of the game is to move this plane to a certain position and rotation, which gives a certain 2D shape. Here is a link to a website which illustrates the 2D slices of a 3D object. How do I approach this if I only want the player to see the slice.

Just to be clear, the solution does not necessarily have to be in 3D, since the ui for the player is going to be 2D anyway

# Answer
> 1 votes
One way you can do it is with a 2-pass custom shader. You can see it visualized here in purple (the grey ghost material is a separate effect I've drawn to help visualize the mesh shape we're cutting):

We'll give our shader a 4-vector representing our cross-section plane. The first 3 components will be the (unit) plane normal, and the fourth will be the distance of the plane from the origin.

We'll draw our shape in two passes, using the plane vector to cut away the part of the mesh between the cross section plane and the camera.

* In the first pass, we draw only front-facing triangles, and we draw them only to the depth buffer, leaving our scene colour unchanged.
* In the second pass, we draw only back-facing triangles (the inside of the mesh).

These will be blocked from drawing anywhere the front-facing triangles already drew to the depth buffer, except for the hole we cut with our cross-section plane. So the net effect is we'll see only the cross section drawn in the scene. :)

Here's a shader that does this (I repeat basically the same code in both passes, so you could make this a bit neater by putting the shared code in a `.cginc` include file and just referencing it):

```
Shader "Unlit/CrossSection"
{
    Properties
    {
        _Color ("Color", Color) = (0, 0, 0, 0)
        _Section("Section Plane", Vector) = (0, 1, 0, 0)
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" "Queue"="Transparent"}
        LOD 100

        Pass
        {
            CULL Back
            Blend Zero One

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

            struct v2f
            {
                float4 vertex : SV_POSITION;
                float sectionDepth : TEXCOORD0;
            };

            float4 _Section;

            v2f vert (float4 vertex : POSITION)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(vertex);

                float3 worldPosition = mul(unity_ObjectToWorld, vertex).xyz;
                float cameraSide = sign(_Section.w - dot(_WorldSpaceCameraPos, _Section.xyz));
                o.sectionDepth = cameraSide * (dot(worldPosition, _Section.xyz) - _Section.w);

                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                clip(i.sectionDepth);
                return 0;
            }
            ENDCG
        }

        Pass
        {
            CULL Front

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

            struct v2f
            {
                float4 vertex : SV_POSITION;
                float sectionDepth : TEXCOORD0;
            };

            fixed4 _Color;
            float4 _Section;

            v2f vert(float4 vertex : POSITION)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(vertex);

                float3 worldPosition = mul(unity_ObjectToWorld, vertex).xyz;
                float cameraSide = sign(_Section.w - dot(_WorldSpaceCameraPos, _Section.xyz));
                o.sectionDepth = cameraSide * (dot(worldPosition, _Section.xyz) - _Section.w);

                return o;
            }

            fixed4 frag(v2f i) : SV_Target
            {
                clip(i.sectionDepth);
                return _Color;
            }
            ENDCG
        }
    }
}

```

---
Tags: unity
---


# Question
Title: Bouncing from any object after collision JavaScript
I'm trying to make a ball bounce off some obstacles after a bounding box + pixel by pixel collision. Somehow, sometimes the ball is not going in the direction it is supposed to be.

If the ball is following the red arrow, it is supposed to follow the green arrow after that. What happens is that sometimes it just goes back around (orange arrow). The same happens when going up on this wall, or even in the left wall.

Here is the collision and reflection code

```
isPixelCollision(element) {

    var x = Math.round(this.pos.x),
        y = Math.round(this.pos.y),
        x2 = Math.round(element.pos.x),
        y2 = Math.round(element.pos.y);

    var w = this.width,
        h = this.height,
        w2 = element.width,
        h2 = element.height;

    // find the top left and bottom right corners of overlapping area
    var xMin = Math.max(x, x2),
        yMin = Math.max(y, y2),
        xMax = Math.min(x + w, x2 + w2),
        yMax = Math.min(y + h, y2 + h2);

    // Sanity collision check, we ensure that the top-left corner is both
    // above and to the left of the bottom-right corner.
    if (xMin >= xMax || yMin >= yMax) {
        return false;
    }

    var xDiff = xMax - xMin,
        yDiff = yMax - yMin;

    // get the pixels out from the images
    var pixels = this.imgData.data,
        pixels2 = element.imgData.data;

    // if the area is really small,
    // then just perform a normal image collision check
    if (xDiff < 4 && yDiff < 4) {
        for (var pixelX = xMin; pixelX < xMax; pixelX++) {
            for (var pixelY = yMin; pixelY < yMax; pixelY++) {
                if ((pixels[((pixelX - x) + (pixelY - y) * w) * 4 + 3] !== 0) && (pixels2[((pixelX - x2) + element.width * (element.actual - 1) + (pixelY - y2) * w2 * element.total) * 4 + 3] !== 0)) {
                    console.log("Small Collision\n");
                    var vector = {
                        x: (pixelX - Math.floor(this.pos.x + (this.width / 2))),
                        y: -(pixelY - Math.floor(this.pos.y + (this.height / 2)))
                    };
                    if (element.constructor.name != 'Light')
                        this.angle = (Math.atan2(vector.y, vector.x) - Math.PI) * (180 / Math.PI);
                    else {
                        this.speed += 50;

                    }
                    return true;
                }
            }
        }
    } else {

        var incX = xDiff / 3.0,
            incY = yDiff / 3.0;
        incX = (~~incX === incX) ? incX : (incX + 1 | 0);
        incY = (~~incY === incY) ? incY : (incY + 1 | 0);

        for (var offsetY = 0; offsetY < incY; offsetY++) {
            for (var offsetX = 0; offsetX < incX; offsetX++) {
                for (var pixelY = yMin + offsetY; pixelY < yMax; pixelY += incY) {
                    for (var pixelX = xMin + offsetX; pixelX < xMax; pixelX += incX) {
                        if ((pixels[((pixelX - x) + (pixelY - y) * w) * 4 + 3] !== 0) && (pixels2[((pixelX - x2) + element.width * (element.actual - 1) + (pixelY - y2) * w2 * element.total) * 4 + 3] !== 0)) {

                            var vector = {
                                x: (pixelX - Math.floor(this.pos.x + (this.width / 2))),
                                y: -(pixelY - Math.floor(this.pos.y + (this.height / 2)))
                            };

                            console.log("Big Collision");

                            if (element.constructor.name != 'Light')
                                this.angle = (Math.atan2(vector.y, vector.x) - Math.PI) * (180 / Math.PI);
                            else {
                                if (this.speed < 500) this.speed += 50;

                            }
                            return true;
                        }
                    }
                }
            }
        }
    }

    return false;
}

```

This is a more mathematical way of doing it that I tried, but works even worse than the one before

```
//Normal Vector
var normal = {
    x: (pixelX - (this.imgData.width / 2)),
    y: -(pixelY - (this.imgData.height / 2))
};
//Normalize the vetor
var norm = Math.sqrt(normal.x * normal.x + normal.y * normal.y);
if (norm != 0) {
    normal.x = normal.x / norm;
    normal.y = normal.y / norm;
}
var n_rad = Math.atan2(normal.y, normal.x);
var n_deg = (n_rad + Math.PI) * 180 / Math.PI;
console.log("Vetor Normal -> (" + normal.x + ", " + normal.y + ") , Angulo: " + n_deg);
//Velocity vector
var velocity = {
    x: Math.cos((this.angle * Math.PI / 180) - Math.PI),
    y: Math.sin((this.angle * Math.PI / 180) - Math.PI)
};
console.log("Vetor Velocidade -> (" + velocity.x + ", " + velocity.y + ") , Angulo: " + this.angle);
//Vetor Reflexao
var ndotv = normal.x * velocity.x + normal.y * velocity.y;
var reflection = {
    x: -2 * ndotv * normal.x + velocity.x,
    y: -2 * ndotv * normal.y + velocity.y
};
var r_rad = Math.atan2(reflection.y, reflection.x);
var r_deg = (r_rad + Math.PI) * 180 / Math.PI;
console.log("Vetor Reflexao -> (" + reflection.x + ", " + reflection.y + ") , Angulo: " + r_deg);
this.angle = r_deg;

```

# Answer
> 1 votes
What you need to do is to calculate the normal of the collision then reflect the impact vel across the collision normal: // r = v - 2 * dot(v, n) * n; r = result vel, v = impact vel, n = normal of collision.

# Answer
> 0 votes
You have to first check for collision. To do this, you'll need to check your ball's position with the walls:

```
//check collision with top wall
if (ball.y <= wall.topY + BALL_RADIUS) {
    ball.y = wall.topY + BALL_RADIUS; //change position to the point of collision
    velocity.y = -velocity.y; //reverse the velocity only on the Y axis
}

//check collision with right wall
if (ball.x >= wall.rightX + BALL_RADIUS) {
    ball.x = wall.rightX + BALL_RADIUS; //change position to the point of collision
    velocity.x = -velocity.x; //reverse the velocity only on the X axis
}

//check collision with bottom wall
if (ball.y >= wall.bottomY - BALL_RADIUS) {
    ball.y = wall.bottomY - BALL_RADIUS; //change position to the point of collision
    velocity.y = -velocity.y; //reverse the velocity only on the Y axis
}

//check collision with left wall
if (ball.x <= wall.leftX + BALL_RADIUS) {
    ball.x = wall.leftX + BALL_RADIUS; //change position to the point of collision
    velocity.x = -velocity.x; //reverse the velocity only on the X axis
}

```

---
Tags: collision-detection, javascript, html5
---


# Question
Title: In the new InputSystem of Unity, how to detect the keyboard and the mouse "as the same input device"?
I'm trying to use the PlayerInputManager of the new InputSystem (preview 7) and my keyboard and mouse are being detected as separate devices. I'm not saying that it is wrong, but it is not useful at all and I would like to know how to fix it.

As shown in this video, the PlayerInputManager has the ability of Instantiating new players when they press a button of their controller. This is almost exactly what I need, but it is not perfect.

All works fine using controllers but if someone wants to join using the keyboard/mouse, "they won't be able".

When a key is pressed in the keyboard, a player joins, and when the mouse is used, another player joins (despite the fact that in that game youn need both to control a character and neither one of the spawned characters would be playable).

So my question is: how can I configure the InputSystem so that only one player joins when either a keyboard or mouse is used and it reads the input from both devices?

Maybe it is simply a missing feature, but I think that it would be nice if you could achieve what I want because a lot of times the keyboard is used alongside a mouse.

Thanks in advance!

# Answer
This was solved in the unity forum in this post: https://forum.unity.com/threads/how-to-detect-the-keyboard-and-the-mouse-as-the-same-input-device.873934/#post-5749564

I copy the Rene-Damm's answer (to avoid the link from breaking):

For this to work, you'll need to use control schemes. Without control schemes, PlayerInput won't know which devices go together.

Use the button in the top left corner to add control schemes.

In the popup, add both a keyboard and mouse for the keyboard&mouse control scheme.

Use the control scheme matrix in the bindings properties pane to associate existing bindings with control schemes.
> 1 votes

---
Tags: unity, c#, multiplayer, input
---


# Question
Title: Stretching a tetragonal shape in a texture to a square object
I'd like to write a fragment shader that stretches a tetragonal shape in a texture to a square shaped game object of mine. My problem is best described with a picture, seen below. The shader receives a texture and the four corners of the red tetragon, and I'd like to stretch the tetragon as such that that's the only thing that'll appear on my square object, nothing outside of it. In this example, the texture coordinates u and v (0, 0) would be transformed into (x1, y1), and in a similar fashion, (1, 1) would become (x4, y4).

I don't know how I should go about this though. I've done my research, I believe bilinear interpolation could be what I'm looking for, but from what I can see, it would only work if my red tetragon was a rectangle, in other words if its four corners where (x1, y1), (x1, x2), (x2, y1) and (x2, y2), which is clearly not the case here as all my four coordinates are different. Any help from a little hint to a complete code solution would be welcome.

**Edit:** I did try implementing bilinear interpolation, however it did not work. Here are the equations from the wikipedia article that I tried modifying to my specific case:

What R1 and R2 correspond to can be also seen on the image on wikipedia, my math notation may not entirely be correct but I tried to make it as understandable as possible. This did not give me the result I was looking for, however. I tried setting the red tetragon to be a triangle by setting (x1, y1) to (0.5, 0.5) while the remaining three coordinates went in their corresponding corners), and while I was expecting the texture to be stretched in some way, the end result still was a crystal clear, non-stretched picture (due to my testing circumstances, I can't tell the exact difference to when I set (x1, y1) to (0, 0), but the results were extremely similar).

**Edit 2:** I'll also include the code from my fragment shader, for good measure.

```
in vec4 tex;
in vec3 normal;
out vec4 fragmentColor;

uniform struct {
    sampler2D colorTexture;
    vec2 p1;
    vec2 p2;
    vec2 p3;
    vec2 p4;
} material;

void main(void) {
    float x = tex.x / tex.w;
    float y = tex.y / tex.w;
    float x1 = material.p1.x;
    float x2 = material.p2.x;
    float x3 = material.p3.x;
    float x4 = material.p4.x;
    float y1 = material.p1.y;
    float y2 = material.p2.y;
    float y3 = material.p3.y;
    float y4 = material.p4.y;
    vec2 R1 = (x3 - x) / (x3 - x1) * material.p1 + (x - x1) / (x3 - x1) * material.p3;
    vec2 R2 = (x4 - x) / (x4 - x2) * material.p2 + (x - x2) / (x4 - x2) * material.p4;

    vec2 interpolatedPoint = (R2.y - y) / (R2.y - R1.y) * R1 + (y - R1.y) / (R2.y - R1.y) * R2;

    fragmentColor = texture(material.colorTexture, interpolatedPoint);
}

```

Here's what I see when I set p1 to (0, 0), p2 to (0, 1), p3 to (1, 0) and p4 to (1, 1)

And here's the same image but with p1 set to (0.5, 0.5)

The slight differences are only there because I had to position my camera manually, the two results are identical, even though in the second case I would expect to see an image that's clearly been stretched in some way.

# Answer
Assuming your x & y coordinates go from (0, 0) in the bottom-left to (1, 1) in the top-right, you should be able to simplify to something like this:

```
void main(void) {
    float x = tex.x / tex.w;
    float y = tex.y / tex.w;

    vec2 top = mix(material.p2, material.p4, x);
    vec2 bottom = mix(material.p1, material.p3, x);

    vec2 samplePoint = mix(bottom, top, y);

    fragmentColor = texture(material.colorTexture, interpolatedPoint);
}

```
> 0 votes

---
Tags: opengl, textures, reflection-rendering
---


# Question
Title: How to build TileMaps dynamically from a database?
The game I'm building allows users to create their own tile maps essentially, so I want the server to respond with tilemap coordinates if / when a user enters their custom world.

# Answer
> 0 votes
> my main issue is storing the data for complex tilemaps.

You can think of tilemaps as arrays. So, you can just use an 2D array of numbers, where each number on the array represent a kind of tile.

If you want to serialize an array, for local storage or for network transmission, you can start by placing the dimensions (unless these are standard), followed by the value of each tile, in binary format, going row by row.

To deserialize, given that you know the dimensions, you can break the stream of tile values into rows. Knowing the number of columns tells you where it should end.

A couple notable alternatives to this approach are:

* Storing the tile values as characters in a string. If you use new line to mark the end of a row, it will be easy to edit and visualize in virtually any text editor.
* Storing the tile values as pixels in an bitmap image. This time you can visualize and perhaps edit with an image editor. Plus, you can seamlessly take advantage of lossless image compression such as the one provided by png. *Plus, if you need to upload it to a shader, it is easy to use as a texture. Although, that is not your use case.* See the Godot class image.

---

Now, if your tilemap is sparse, or if it is too large. There might be value in breaking it into chunks, and having a larger structure.

Some solutions: \- An array of chunks. Very easy to query. \- A quadtree of chunks. Will use less memory for sparse tilemaps. \- Just a list of chunks with their coordinates. Easier to transmit.

Speaking of ease of transmit. You might want to have the game request chunks on demand based on the coordinates of the player. *And those chunks can be png files. Well, how easy that is depends on your server technology.*

If you also need to place other kinds of objects on the map, you may add them to same structure.

---

As you probably has seen in the documentation, you can use `set_cell` to write to tilempas in runtime. See How do I programatically lay tiles with the Godot engine?.

---
Tags: tilemap, tiles, server, databases, godot
---


title: How can I make an instantiation random?

text:
# Question
Title: How can I make an instantiation random?
I'm trying to do it so when I have an instantiated an item upon the game starting, it is random as to whether it actually instantiates or not. Here's the code I have so far:

```
public GameObject anyItem;
void Start()
{
    Instantiate(anyItem, new Vector3(0, 0, 0), Quaternion.identity);
    Instantiate(anyItem, new Vector3(11, 0, 0), Quaternion.identity);
}

```

How can I do it so these items (individually, not both together) are decided randomly as to whether they will actually be instantiated or not?

# Answer
> 1 votes
You can use `Random.Range(0, 100)` to get a random int from 0 to 100 for example. You then just need a probability for each GameObject you're trying to instantiate.

```
public GameObject anyItem;

void Start()
{
    // There is a 60% chance for a new object
    randomlyInstantiateAtPosition(60, new Vector3(0, 0, 0));
    // There is a 25% chance for a new object
    randomlyInstantiateAtPosition(25, new Vector3(11, 0, 0));
    // This one will always be made
    randomlyInstantiateAtPosition(100, new Vector3(22, 0, 0));
}

private void randomlyInstantiateAtPosition(int probability, Vector3 position) {
    if (Random.Range(0, 100) < probability) {
        Instantiate(anyItem, position, Quaternion.identity);
    }
}

```

Here's the documentation for `Random.Range`:

https://docs.unity3d.com/ScriptReference/Random.Range.html

---
Tags: unity, random
---


# Question
Title: How to make collisions occur between objects using the same script?
Well what I’m trying to do is have cars travelling on the road. The cars have a trigger at the front and a hitbox at the back of the cars. What I want to happen is when the trigger hits the hitbox it compares the Variables for speed of the two cars in the collision, i.e. the make the car at the back slow down or equal the speed of the car in the front. However, what I am having trouble with is referencing the speed of both cars and comparing them. This is due to them both being prefabs using the same script. Which I’m learning means that I’m just referencing the same script and not the actual values of the individual car. But how could I get round this? Is it possible to have collisions occurring between objects using the same script?

```

    private void OnTriggerStay2D(Collider2D collision)
    {
        Debug.Log("TriggerStay");

        GameObject collidedParent = collision.gameObject.transform.parent.gameObject; // get parent transform and then its gameobject
        Traffic Col_speed = collidedParent.GetComponent<Traffic>();

        if (speed > Col_speed.speed)
        {
            Accelerate = false;
            ApplyBreak = true;
        }
        else if (speed < Col_speed.speed)
        {
            Accelerate = false;
            ApplyBreak = false;
            speed = Col_speed.speed;
        }

        if (transform.position.y > collision.transform.position.y)
        {
            turn = turn + 1;
            Debug.Log(this.gameObject.name + "someMessage");

        }
        if (transform.position.y < collision.transform.position.y)
        {
            turn = turn - 1;
            Col_speed.turn = 0;
            Debug.Log(this.gameObject.name + "someMessage");

        }
    }
    private void OnTriggerExit2D(Collider2D collision)
    {
        turn = 0;
        Accelerate = true;
        ApplyBreak = false;
    }

}

```

# Answer
The point is that you are not actually referencing the scripts but its intances. Each of your script components it technically already an instance of the script which means it can have its own values. In other words: You can have many cars using the same scripts. They individually do what the scripts tell them. They are instances and thats why it's even possible to have multiple cars that do individual things.

Your line

```
Traffic Col_speed = collision.gameObject.GetComponent<Traffic>();

```

should already get the instance of the other (collding) car so the `Col_speed.speed` is the other cars speed.

I hope this clears things up but what is your actual issue? -\> describe what you expect but what happens instead, then the community can provide further help.

Edit:

As of your comments, to get the Traffic component from the parent you can do:

```
...
GameObject collidedParent = collision.gameObject.transform.parent.gameObject; // get parent transform and then its gameobject
Traffic Col_speed = collidedParent.GetComponent<Traffic>();
...

```

Note that this approach will stop working if you change the gameObject hierarchy.
> 1 votes

---
Tags: unity, collision-detection, car, prefabs
---


# Question
Title: Varibles Initialized in Awake are null in other script's Start
I have a component gameState Attached to one gameobject called GameState:

```
public class gameState : MonoBehaviour
    {
        public Context stateMachine;
        private void Awake()
        {
            PlayerGameobject p = GameObject.Find("Player").GetComponent<PlayerGameobject>();
            stateMachine = new Context(new Playing(), p);
        }

```

On another gameObject I have this component:

```
public class PlayerGameobject : MonoBehaviour
{
    void Start()
    {

        gameState = GameObject.Find("GameState").GetComponent<gameState>();
    }

}

```

When I try to use gameState within PlayerGameobject's Update method I find that stateMachine is null.

```
 if (gameState.stateMachine.CurrentState == "Playing"){}
      //       ^^^^ null

```

why is statemachine null? I initialized it in awake which should run before start. gameState is not null and other public variables assigned in Editor are not null.

# Answer
The provided code won't work properly since you name your class `gameState` and access `gameState.stateMachine` while `stateMachine` is not static. Make sure you access the `stateMachine` of the GameState instance.

Another guess: it might be possible that the `new Context(...)` in your gameState Awake causes an exception which leads to `stateMachine` being `null`. You would directly spot that in the console though.
> 0 votes

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


# Question
Title: Why there is no isGrounded and Move properties for the CharacterController?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(CharacterController))]

public class SC_FPSController : MonoBehaviour
{
    public float walkingSpeed = 7.5f;
    public float runningSpeed = 11.5f;
    public float jumpSpeed = 8.0f;
    public float gravity = 20.0f;
    public Camera playerCamera;
    public float lookSpeed = 2.0f;
    public float lookXLimit = 45.0f;

    CharacterController characterController;
    Vector3 moveDirection = Vector3.zero;
    float rotationX = 0;

    [HideInInspector]
    public bool canMove = true;

    void Start()
    {
        characterController = GetComponent<CharacterController>();

        // Lock cursor
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    void Update()
    {
        // We are grounded, so recalculate move direction based on axes
        Vector3 forward = transform.TransformDirection(Vector3.forward);
        Vector3 right = transform.TransformDirection(Vector3.right);
        // Press Left Shift to run
        bool isRunning = Input.GetKey(KeyCode.LeftShift);
        float curSpeedX = canMove ? (isRunning ? runningSpeed : walkingSpeed) * Input.GetAxis("Vertical") : 0;
        float curSpeedY = canMove ? (isRunning ? runningSpeed : walkingSpeed) * Input.GetAxis("Horizontal") : 0;
        float movementDirectionY = moveDirection.y;
        moveDirection = (forward * curSpeedX) + (right * curSpeedY);

        if (Input.GetButton("Jump") && canMove && characterController.isGrounded)
        {
            moveDirection.y = jumpSpeed;
        }
        else
        {
            moveDirection.y = movementDirectionY;
        }

        // Apply gravity. Gravity is multiplied by deltaTime twice (once here, and once below
        // when the moveDirection is multiplied by deltaTime). This is because gravity should be applied
        // as an acceleration (ms^-2)
        if (!characterController.isGrounded)
        {
            moveDirection.y -= gravity * Time.deltaTime;
        }

        // Move the controller
        characterController.Move(moveDirection * Time.deltaTime);

        // Player and Camera rotation
        if (canMove)
        {
            rotationX += -Input.GetAxis("Mouse Y") * lookSpeed;
            rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
            playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
            transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeed, 0);
        }
    }
}

```

On both I'm getting the same error :'CharacterController' does not contain a definition for 'isGrounded' and no accessible extension method 'isGrounded' accepting a first argument of type 'CharacterController' could be found (are you missing a using directive or an assembly reference?)

# Answer
Remove any of your self made classes that are called `CharacterController` or declare your `characterController` field as:

```
...
UnityEngine.CharacterController characterController;
...

```
> 1 votes

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


# Question
Title: 3D player movement with Unity's new input system
So, I trying to get used to the new Unity input system. "Back in the days" I just got the Vertical/Horizontal axis, put them into a Vector3, multiplied them by a certain value and then moves the player.

Now, with the new input system, that changed quite a bit. So, what I'm trying to do is, to get the input of a 2D Vector, earlier called DPAD in the new system. My approach was, like

```
private void Awake() {
    InputAction.performed += ctx => Movement(ctx.ReadValue<Vector2>());
    InputAction.canceled += ctx => Movement(ctx.ReadValue<Vector2>());
}

private void OnMovement(Vector2 _dir) {
    moveDirection = _dir;
}

//This performed in FixedUpdate
private void Move() {
    transform.position += moveDirection * moveSpeed * Time.deltaTime;
}

```

Buut, you know, kinda worked, but not really. The player did unintended things like keep moving or not reacting at all to my button press. Maybe I set something wrong up. You might help me please, thanks!

# Answer
> -3 votes
you have to do it like the old input.getaxis. like this: move (Vector2 direction) { t}

---
Tags: unity, movement, input, first-person-shooter
---


# Question
Title: Why does my tile palette not arrange nicely?
I made my own Hex Point Top Tile sprite sheet, ensuring it's pixel perfect and align well. Slicing in Sprite Editor has no problem too. However, when I drag the sprite sheet to a new Palette in the Tile Palette panel, the tiles show up with random spaces. See screenshot below:

What did I miss?

The sprite sheet is here, 30 x 30px offset, 24 x 24px padding, 66 x 66px tile size:

I'm using Unity 2019.3.10f1.

# Answer
> 1 votes
Your tiles don't fit the background grid. For your tall tiles, the bottom sprite boundary aligns with the low edge, but the top sprite boundary aligns with the high edge. On the right, I've marked the tile size you provided in blue, and the actual tile size in red.

Additionally, the hexagons on the bottom have a different shape than the hexagons on the top: on the left, I marked the bottom hexagon outline in blue and overlaid the top outline in red. They'll never fit together properly.

If you want to create proper hex grids, you'll need a fixed template shape that serves as the *base* of your hexagonal prisms, not the entire outline. You can make the actual tiles as tall as you want, as long as the base is always in the same shape and at the same position. Of course the bottom slope needs to be the same as the top slope too.

If you want your hexagons to be regular hexagons, then the vertical ratios of the template need to be 1:2:1 as depicted here:

The ratio of height to width is left up to you, it will correspond to a different apparent view angle.

---
Tags: unity, tilemap, hexagonal-grid
---


title: How to add a force to jump in unity

text:
# Question
Title: How to add a force to jump in unity
I have created a simple player control. I have used **"Vertical"** and **"Horizontal"** axes as input to move. There is a character controller and I used this to move my player. But I don't know how to add a force as jump with space input. I am new to game development. Please help me to learn this. This is my script,

```
public class PlayerControll : MonoBehaviour
{
    public Animator anim;
    public CharacterController characterController;
    public Rigidbody rb;
    public float Speed;
    public float Direction;

    Vector3 moveDir = Vector3.zero;
    float speedwalking = 8;
    float gravity = 8;

    void Start()
    {
        anim = GetComponent<Animator>();
        characterController = GetComponent<CharacterController>();
        rb = GetComponent<Rigidbody>();
    }

    void Update()
    {
        if (characterController.isGrounded)
        {
            anim.SetBool("Grounded", true);
            if (Input.GetButton("Vertical") || Input.GetButton("Horizontal"))
            {
                Speed = Input.GetAxis("Vertical");
                Direction = Input.GetAxis("Horizontal");
                anim.SetFloat("Speed", Speed);
                anim.SetFloat("Direction", Direction);
                moveDir = new Vector3(Direction, 0, Speed);
                moveDir *= speedwalking;
                moveDir = transform.TransformDirection(moveDir);
                characterController.Move(moveDir * Time.deltaTime);
                moveDir.y -= gravity * Time.deltaTime;
            }
            else
            {
                anim.SetFloat("Speed", 0);
                anim.SetFloat("Direction", 0);
            }
        }
        else
        {
            anim.SetBool("Grounded", false);
        }
    }
}

```

# Answer
Please search before posting a new question in the future. The answer to your question is right in the CharacterController.Move API reference.

You can do this by adding a movement in the opposite direction of your gravity when the Space key is pressed. I also moved the gravity calculation and the applying of the movement vector.

```
public class PlayerControll : MonoBehaviour
{
    public Animator anim;
    public CharacterController characterController;
    public Rigidbody rb;
    public float Speed;
    public float JumpSpeed = 8.0f;  // new
    public float Direction;

    Vector3 moveDir = Vector3.zero;
    float speedwalking = 8;
    float gravity = 8;

    void Start()
    {
        anim = GetComponent<Animator>();
        characterController = GetComponent<CharacterController>();
        rb = GetComponent<Rigidbody>();
    }

    void Update()
    {
        if (characterController.isGrounded)
        {
            anim.SetBool("Grounded", true);
            if (Input.GetButton("Vertical") || Input.GetButton("Horizontal"))
            {
                Speed = Input.GetAxis("Vertical");
                Direction = Input.GetAxis("Horizontal");
                anim.SetFloat("Speed", Speed);
                anim.SetFloat("Direction", Direction);
                moveDir = new Vector3(Direction, 0, Speed);
                moveDir *= speedwalking;
                moveDir = transform.TransformDirection(moveDir);
                if(Input.GetButton("Jump"))   // new
                {
                    moveDir.y = JumpSpeed;
                }
            }
            else
            {
                anim.SetFloat("Speed", 0);
                anim.SetFloat("Direction", 0);
            }
        }
        else
        {
            anim.SetBool("Grounded", false);
            moveDir = Vector3.zero; // reset all movement
        }
        moveDir.y -= gravity * Time.deltaTime;  // moved
        characterController.Move(moveDir * Time.deltaTime);
    }

}

```

Note that this requires `"Jump"` to be defined in the InputManager.
> 1 votes

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


title: Unity 2d, Animations start distorting

text:
# Question
Title: Unity 2d, Animations start distorting
I'm making my first game and I just finished adding animations for walking and jumping. Everything looked good at first but with time they started distorting, even rotating (Rotation is Frozen). This is how the character looks in the beginning:

But after some time of walking and jumping:

Did anyone have a similar error? Can anyone Help?

# Answer
I have seen this bug before, the cause of it was because I didn't created a rotation constraint, just freeze rotation and you should be good to go.
> 0 votes

---
Tags: unity, 2d, animation
---


title: Minecraft: `foot_size` doesn't work

text:
# Question
Title: Minecraft: `foot_size` doesn't work
I'm making an add-on that lets the player step over 1-block high blocks and the foot\_size property is exactly what I'm looking for.

The documentation says the following:

> "Sets the number of blocks the entity can step without jumping."

In the behavior pack, I added the following to the `player.json`. You can see `foot_size` in the components section.

```
{
  "format_version": "1.13.0",
  "minecraft:entity": {
    "description": {
      "identifier": "minecraft:player",
      "is_spawnable": false,
      "is_summonable": false,
      "is_experimental": true
    },

    "component_groups": {
      "minecraft:add_bad_omen": {
        "minecraft:spell_effects": {
          "add_effects": [
            {
              "effect": "bad_omen",
              "duration": 6000,
              "display_on_screen_animation": true
            }
          ]
        },
        "minecraft:timer": {
          "time": [ 0.0, 0.0 ],
          "looping": false,
          "time_down_event": {
            "event": "minecraft:clear_add_bad_omen",
            "target": "self"
          }
        }
      },
      "minecraft:clear_bad_omen_spell_effect": {
        "minecraft:spell_effects": {
        }
      },
      "minecraft:raid_trigger": {
        "minecraft:raid_trigger": {
          "triggered_event": {
            "event": "minecraft:remove_raid_trigger",
            "target": "self"
          }
        },
        "minecraft:spell_effects": {
          "remove_effects": "bad_omen"
        }
      }
    },

    "components": {
      "minecraft:experience_reward": {
        "on_death": "Math.Min(query.player_level * 7, 100)"
      },
      "minecraft:type_family": {
        "family": [ "player" ]
      },
      "minecraft:is_hidden_when_invisible": {
      },
      "minecraft:loot": {
        "table": "loot_tables/empty.json"
      },
      "minecraft:collision_box": {
        "width": 0.6,
        "height": 1.8
      },
      "minecraft:can_climb": {
      },
      "minecraft:movement": {
        "value": 0.1
      },
      "minecraft:step_height": {
        "value": 1.0
      },
      "minecraft:scale": {
        "value": 2.0
      },
      "minecraft:hurt_on_condition": {
        "damage_conditions": [
          {
            "filters": { "test": "in_lava", "subject": "self", "operator": "==", "value": true },
            "cause": "lava",
            "damage_per_tick": 4
          }
        ]
      },
      "minecraft:attack": {
        "damage": 1
      },
      "minecraft:player.saturation": {
        "value": 20
      },
      "minecraft:player.exhaustion": {
        "value": 0,
        "max": 4
      },
      "minecraft:player.level": {
        "value": 0,
        "max": 24791
      },
      "minecraft:player.experience": {
        "value": 0,
        "max": 1
      },
      "minecraft:breathable": {
        "total_supply": 15,
        "suffocate_time": -1,
        "inhale_time": 3.75,
        "generates_bubbles": false
      },
      "minecraft:nameable": {
        "always_show": true,
        "allow_name_tag_renaming": false
      },
      "minecraft:physics": {
      },
      "minecraft:pushable": {
        "is_pushable": false,
        "is_pushable_by_piston": true
      },
      "minecraft:insomnia": {
        "days_until_insomnia": 3
      },
      "minecraft:rideable": {
        "seat_count": 2,
        "family_types": [
          "parrot_tame"
        ],
        "pull_in_entities": true,
        "seats": [
          {
            "position": [ 0.4, -0.2, -0.1 ],
            "min_rider_count": 0,
            "max_rider_count": 0,
            "lock_rider_rotation": 0
          },
          {
            "position": [ -0.4, -0.2, -0.1 ],
            "min_rider_count": 1,
            "max_rider_count": 2,
            "lock_rider_rotation": 0
          }
        ]
      },
      "minecraft:scaffolding_climber": {},
      "minecraft:environment_sensor": {
        "triggers": {
          "filters": {
            "all_of": [
              {
                "test": "has_mob_effect",
                "subject": "self",
                "value": "bad_omen"
              },
              {
                "test": "is_in_village",
                "subject": "self",
                "value": true
              }
            ]
          },
          "event": "minecraft:trigger_raid"
        }
      }
    },

    "events": {
      "minecraft:gain_bad_omen": {
        "add": {
          "component_groups": [
            "minecraft:add_bad_omen"
          ]
        }
      },
      "minecraft:clear_add_bad_omen": {
        "remove": {
          "component_groups": [
            "minecraft:add_bad_omen"
          ]
        },
        "add": {
          "component_groups": [
            "minecraft:clear_bad_omen_spell_effect"
          ]
        }
      },
      "minecraft:trigger_raid": {
        "add": {
          "component_groups": [ "minecraft:raid_trigger" ]
        }
      },
      "minecraft:remove_raid_trigger": {
        "remove": {
          "component_groups": [ "minecraft:raid_trigger" ]
        }
      }
    }
  }
}

```

When I use the behavior pack it doesn't do anything. I also changed the scale and verified that scale works and `foot_size` does not, so installation is not the issue. What am I doing wrong?

# Answer
There appears to be a bug affecting this behaviour, as of now, not yet fixed:

https://bugs.mojang.com/browse/MCPE-67469

> In a behavior pack, adding a minecraft:foot\_size component to the player entity does not affect the stepping height like it should. I have experimental enabled and cheats enabled too. Attached behavior pack with foot\_size set to 1 added to component section. It should step over 1 full block.

This is reported 5th of April, so it must've been known for a while.
> 1 votes

---
Tags: minecraft-modding, json
---