title: Analytical derivatives for noise

text:
# Question
Title: Analytical derivatives for noise
Lately i'm doing lot of research regarding procedural terrain generation. I do a lot of learning from www.iquilezles.org. I'm now familiar with such things as perlin/simplex noise, fbm, domain warping, etc. But right now I'm looking into this \> https://www.iquilezles.org/www/articles/morenoise/morenoise.htm and am very clueless what are those derivatives, what do they represent and how to use them. Maybe someone can put this knowledge in more simple words or/and illustration? Thank you in advance.

# Answer
The derivative of a function gives you the slope at each point of said function (it actually gives you the rate of change, but the two are identical for the first derivative)

For instance if you have the function \\$f(x)=x\\$, the derivative would be \\$f'(x)=1\\$, since the slope of the function is 1 at every point. Similarly for \\$g(x)=x^2\\$ it would be \\$g'(x)=2x\\$.

Knowing the slope of a function at any specific point is great, because it can be used to calculate the normals of the function, which can then be used to do lighting and other stuff, the article gives you a couple of ideas.

The second derivative is a bit harder to use in this context. It generally allows us to get the local minimums and maximums of any function by looking for coordinates where the second derivative is 0 and the signs of the values on the sides are different.
> 1 votes

---
Tags: procedural-generation
---


# Question
Title: How does my GPU know what game is running?
I am trying to understand how game ready drivers work. How does my gpu know what application i am running and which application to use a specific driver optimization. For example the new nvidia driver makes some improvements to devil may cry 5 . how does my gpu know that I am running DMC 5. Is there a code in that application the driver recognizes? or does it not care what application i am using and treats every application the same.

# Answer
> 1 votes
I'm not sure what AMD is using, but Nvidia identified games based on their executable name. In addition, for mobile chips, the driver software will look for special export symbols in binaries to determine which GPU to use in case there's no matching profile being found.

---
Tags: performance
---


# Question
Title: Reading text from file changes the text?
I'm currently trying to load a simple text file and filter it by a certain string. In the text file I'm using a new line for each value and sometimes use a "--" to make things easier to read for me when viewing the .txt-file.

Now, when I load the file and split it by new lines I end up with a list of substrings, each representing a value I need. Plus, all the "seperators" I put into the file.

My goal is to clean the list from all the seperators and basically just remove them from the list. However, RemoveAll does not work and I found out that the strings containing "--" are not really "--", but something else, because using string.Equals("--") fails on them.

Somewhere when reading the data or splitting it, something happened to those parts, but I can't figure out what's happening.

Here's the code:

```
void Awake() {

    _fileLines = new List<string>();

    TextAsset txt = Resources.Load<TextAsset>("SubjectPages/test");
    _fileLines = new List<string>();
    _fileLines = txt.text.Split(new string[] { "\n" }, System.StringSplitOptions.None).ToList<string>();

    _fileLines.RemoveAll(x => ((string)x) == "");
    _fileLines.RemoveAll(x => ((string)x) == "--");

    for (int i = 0; i < _fileLines.Count; i++) {
        Debug.Log(_fileLines[i] + " | " + (_fileLines[i].Equals("--")) + " | " + (_fileLines[i] == "--"));
    }
}

```

Removing empty lines with RemoveAll seems to work fine.

# Answer
> 0 votes
I checked each character value for the lines containing "--" and they did indeed have a third character with a char value of 13. Looking it up this translates to "\r". So, instead of removing "--" from the list I am now removing "--\r" from the list and this works now :)

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


# Question
Title: Creating 3D water on Unity for iOS/Android
I want to render an ocean where players can change waves’ amplitude in real-time. Initially, I would render rolling waves (see picture). As the amplitude increases, I need to transition the rolling waves into breaking waves (see picture). For now, I am not going to show the shoreline onscreen so I don’t need to render breaking waves interacting with the shoreline; I only need breaking waves on the open ocean.

I’ve tried three different approaches so far and I’ve only had success with rolling waves using approach 1. Breaking waves have been impossible so far with all three approaches.

**Approach 1**: **Mesh deformation**

* I can create smooth rolling waves using the Sine and Gerstner equations.
* Since I can’t use these equations for breaking waves, I tried to implement them by using this free plugin whose output is similar to this paid mesh deformation plugin. But there are 2 problems with this plugin approach:

Problem 1: There is no smooth transition between rolling waves generated by approach 1a and the breaking waves generated by the Deform plugin

Problem 2: The output of the plugin does not look similar to real breaking ocean waves in three different ways:

i. No smooth blending with the ocean surface

ii. A large depression is created below the crest

iii. The entire wave is the same height (rather than with more realistic variations)

* I considered using vertex shaders but this approach seems similar to mesh deformation.

**Approach 2:** **Fluid dynamics + metaballs**

1. To render an ocean I will need thousands of particles which will be too expensive in terms of performance (especially for mobile devices).

**Approach 3:** **Using mesh files**

1. I can create breaking waves using some 3D software like in this post but then I can’t modify the ocean in real-time. It will be more like a pre-rendered simulation.

To summarize, I am looking for an approach where I can vary ocean waves’ amplitude for a smooth transition between rolling waves and breaking waves.

# Answer
I understand the local need (moving from rolling waves to breaking waves), but as I can't figure out the larger need (how the game will evolve around this) my answer might just be out of place as highly theoretical. But let's try it.

Have you considered using *approach3* but only on small patches of your mesh? You have that mesh of yours with small waves on it... then you know where your wave center is, and the highest point of it. You could, on that very specific place where you want to have a breaking wave, display a mesh you'd have created in a 3D software. The trick here would be to move the vertices / or create new ones for the breaking wave base to fill the gap between wave it's supposed to replace and the other ones. Once your 3D mesh is in place you can play an animation to let it finish its movement and even play with its scale. Add to that some nice particles and it should do the trick.

TL;DR: remove the small rolling wave you want to break from the mesh, fill the empty gap using a 3D mesh modeled in a 3D software, fill the gap et voila.
> 1 votes

# Answer
You can use a shader to achieve the effect. Unity's new "Lightweight Rendering Pipeline(good for Mobile) supports "Shader Graph"; so you can use "shader graph" to create good looking wave, you can use change values of the material to control the wave and other stuff.

This tutorial can be a good start!!

https://www.youtube.com/watch?v=FbTAbOnhRcI
> -1 votes

---
Tags: unity, physics, 3d, particles
---


title: Adding a feedback survey to a game

text:
# Question
Title: Adding a feedback survey to a game
So I am currently making a game that aims to help people with anxiety management. I , however, would like to ask them how they feel before playing the game and then again after playing the game. Would it be possible to do this directly on Unity? I would like for them to be able to log their entries much like an online journal. I have attached pictures from the daylio app. I would like to do something similar. At this point, I really do not know how to begin doing this on Unity. Any advice, or tutorial suggestions would be appreciated.

This far I have managed to do the following (in the picture below): This is how the survey looks (its pretty rudimentary at this point):  And this is where the information is getting displayed (in the inspector):  So now, what I would like to know, is how would I go about sending this data to somewhere else i.e. as it is in the daylio app?

# Answer
> 1 votes
If these events are only for your benefit as a developer in order to measure the success of your game, then you could log the player answers as custom analytic events. Unity Analytics is a service provided by Unity Technologies. Your game can send event notifications with small amounts of data to Unity's servers. You can then log into the Unity website and get some statistics about them.

But if you would like to store historical data on the user device in order to allow the player to view their emotional history, this approach won't work. Games can post events to Unity Analytics, but they can't retrieve a history of events they posted before. The most platform-independent way of storing persistent data on the user device is using the `PlayerPrefs` class. But it isn't really designed to save large amounts of serial data. A better approach might be to use the standard C# classes for file input and file output (`StreamWriter` and `StreamReader`) to write and read files on the user device, but this is something which requires testing on each platform you want to support. And it won't work on platforms without a writeable filesystem, like WebGL.

If you need both - local access by the player and server-sided access for analytics - then you won't get around hosting your own server with an own database which offers an API for posting and retrieving data. Unity can post and retrieve data to/from servers using the the HTTP protocol with the class `UnityWebRequest`. There is a very, very wide array of possible technologies which can be used to implement such a webservice endpoint on the server side. Explaining all your options would be far out of scope for a single answer.

However, do keep in mind that you are dealing with data which is very personal. It could even be classified as (mental) health data. Data like that is often subject to legal restrictions. So inform yourself which data protection regulations apply to you if you store such data.

---
Tags: unity
---


# Question
Title: How to make a follower script without diagonal movement
I’m working on a 2d game in unity. Right now I’m trying to make a follow ai. Where a character will follow the position of the player. I currently have it set it and working using the MoveTowards function. But my problem is that my game does not use diagonal movement. Wondering if there’s a way to constrain the move towards function to not use diagonals or if there is a better function to use in this instance? Thanks

# Answer
Moving on a single axis is just incrementing the value of the relevant axis in the position vector by the relevant distance. So just do (pseudo code here, because I'm not near my Unity machine)

```
if (shouldMoveOnX(followerPos, myPos) {
  followerPos.x += step;
} else {
  followerPos.y += step;
}

```

The only question is how to determine 'shouldMoveOnX' - and in order to fill that function, you need to answer game logic questions such as whether there are blocking objects or other traversal circumstances that should be taken into account. If there aren't, this should be sufficient - it just moves on the axis that has the shorter distance:

```
bool shouldMoveOnX(Vec3 followerPos, Vec3 myPos) {
  return followerPos.x - myPos.x < followerPos.y - myPos.y;
}

```
> 1 votes

---
Tags: unity, c#, physics, ai
---


title: Unity 3D move kinematic rigidbody

text:
# Question
Title: Unity 3D move kinematic rigidbody
I'm trying to move a kinematic rigidbody (a spaceship) with this code: `float xSpeed = 0.0f;
float ySpeed = 0.0f;
float zSpeed = 30.0f;
Vector3 moveDirection = transform.right * xSpeed + transform.up * ySpeed + transform.forward * zSpeed;
ShipRigidBody.MovePosition(ShipRigidBody.transform.position + moveDirection * Time.deltaTime);`

but moving the ship using ShipRigidBody.MovePosition makes it go through other objects with kinematic rigidbody. The collision detection of both objects is continuous dynamic and works for both other rigidbody objects and the object with the character controller.

I've tried not using a kinematic rigidbody for the ship but when it gets hitted by projectiles (with rigidbody) it moves and starts spinning around.

So my questions here would be:

* Should I use a rigidbody for the NPC ship or use a character controller?
* There is any way to prevent a rigidbody from move after collision of other rigidbody, besides making it kinematic?
* How can I move a kinematic rigidbody so it doesen't go through other kinematic rigidbodies?

Thanks for your help!

# Answer
> 2 votes
> If isKinematic is enabled, Forces, collisions or joints will not affect the rigidbody anymore.

As explained in rigidbody documentation page, when the property `isKinematic` is set to true, collisions won't be checked anymore.

There is something important to understand: the role of the `Rigidbody` and the one of the `Collider`. `Rigidbody` gets all the Physics propeties while `Collider` is in charge of giving your object a shape in the physical world. A GameObject that would be composed of a `Rigidbody` only will have gravity applied to it (it will fall) but as it doesn't have a physical shape (a Collider) it won't collide with any other object... so if you have a plane under it, it won't stop it in its fall. There are some cases when you want to move a `Rigidbody` or rotate it by code, without having the gravity applied or any other forces... this is when you set your `Rigidbody` as kinematic.

* When to use a rigidbody?

It depends on what you're trying to achieve. From what I get of your game with in your question, there are NPCs, and collision check and also projectile check. You can use a Rigidbody on every of these things... the restriction is more about "what do you want to do with these?".

* How can I move a kinematic rigidbody so it doesen't go through other kinematic rigidbodies?

Kinematic rigidbodies will never compute collisions. So this is not the path you want to follow. I would suggest you to have a look at most of the Unity tutorials. There, it's explained that you should use `AddForce` on `Rigidbody` if you want to move it in a direction.

```
your_rigidbody.AddForce(moveDirection * thrust);

```
* Spinning `Rigidbody` on projectile impact

It's a classic, your projectile has a `Rigidbody` and so does your NPC. So when they collide they both start turning around and spinning like drunk fighters. You don't need to have an active collider on your projectile most of the time. You usually just want to know when a projectile has hit a NPC and then make the projectile disappear and start the rest of the game logic (apply damages, create a visual fx...). Just define your projectile Collider as a trigger and it will not collider with other rigidbodies anymore but -the method `OnTriggerEnter` will be called (instead of `OnCollisionEnter`) to let you know when another `Collider` has entered your trigger. It will prevent your object to spin but still warn you about collisions.

* Side note

As you seem to have NPCs and want to have them moving in your scene and interact with things... I would suggest you to have a look to `NavMeshAgent` feature of Unity. Very well explained here.

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


# Question
Title: Unexpected scaling of UI elements after build [Unity Web]
I have an unusual scaling of UI Elements after my build in unity for WebGL

Game in Unity Engine:

Game in Itch.io:

Has anyone seen this kind of behaviour? any suggestions on what I should look into? Happy to provide more info on the matter.

Thanks!

# Answer
> 1 votes
This is due to your Canvas scaling properties. By default the Canvas that you use doesn't scale with the resolution. So if you work in Unity with a small resolution (your game window size defines the resolution you're using, in your case it's a 4:3 ratio resolution but it seems very small), let's say 640x480 and try to play the game after building it on a 1280x1024 screen resolution, your canvas will still be 640x480 and at the middle of the screen.

To avoid that behaviour you can add a component `CanvasScaler` on your Canvas and define the behaviour you're expecting (I feel like you want a "Match width or height" mode). You can find more about the Canvas Scaler here.

---
Tags: unity, gui, webgl
---


# Question
Title: Maths and basics for a 2d top down game (object moving and rotating around center)
I want to eventually create a pseudo 3d game engine like the original Wolfenstein or doom. I am starting from 0 so my first step is to create a 2d top down view where my character would be in the center of the screen always looking up and objects would move around him.

I know how to create a game like Zelda where objects move but dont rotate and the center character just look in different directions. But after that i need some help. I tried to do some research online but could not find exactly what i was looking for.

I dont know yet what language i would use to code my engine. My 1st choice would be c++ but i want my evenual game to be easily ported on different platforms. For that reason ill probably go with Java.

# Answer
> 0 votes
2D math translates in game programming to 2D transformations. What to implement? Rotations, scaling, 2D shapes overlap/contain tests. Only with that you can already code a lot of fun games. With the correct terminology you can easily search for the required techniques. I included a single link as an example.

While the above paragraph tries to answer the question in the title, the body of the question is more in the grey area of the Q&A format. I can only provide personal experience here:

With Java you have most of the work done, in Android you have the Canvas class and in desktop you have the Graphics2D class. None guarantee to exploit the device GPU at its maximum but I have encounter that today both have very good performance (including no gaming hardware as long as the GPU helps a bit). Both will take care of, probably, all the transformations you will need.

If you want to go up a level, you can go close to low level OpenGL programming with LWJGL. While I said low level, you have all transforms for free (scaling, rotation, mirror, etc) because the GPU will be doing everything. You will be dealing with matrices and vectors a lot. You can optimize the calls for your specific game and got the best performance (this takes time, debugging, and experimentation).

2D hardware doesn't exist. Sprites can be implemented in APIs like OpenGL by using an orthogonal projection with textured quads. There are also more advanced techniques that you can read about, like optimize the shapes of sprites rather than just using a big quad.

Now, if you want to learn more than actually doing, C++ will teach you a lot more about not only game programming but about programming in general.

The multi-platform engine objective is actually very hard. For that is better to just use an existing engine. Except that you want to learn more than finishing the project.

If you want to do more than learn, stay away from low level. Engines like Unity are your friends here. There are solutions for C++ and Java too.

For example, SDL for C/C++ already covers everything including audio and input handling, it is multi-platform enough and doesn't stay in your way by imposing you a specific way of doing things. With SDL is better not to be afraid of extensions, like SDL\_mixer for audio, or things go too close to low level.

---
Tags: 2d, game-design
---


# Question
Title: Using enums for detecting object collisions
As far as I know, I can detect what objects the player is colliding with is by the following code:

```
private void OnCollisionEnter2D(Collision2D collision)
{
    if(collision.collider.name.Equals(""))
}

```

But I have heard that I can use enums instead to reduce computations. Could anyone explain to me using examples?

# Answer
I expect that the part you want to optimize is `collision.collider.name.Equals("")` because you used the Unity Profiler and found out that this particular line of code takes up an unacceptable amount of execution time (I would find that unlikely, though). You also might just want to find out if the other object is friend, enemy or neutral and consider the name of the collider an inappropriate method of doing so (Which I would consider a much better reason).

Let's also assume that you have more than two factions in your game. Because if you only have players and enemies, you don't need an enum to store faction membership. A bool would be much simpler.

In order to do that, you could add a component `FactionMembership` to each object in your game (or at least those where the friend/foe status is relevant). That class is a wrapper around an enum with all the factions an object can belong to:

```
public FactionMembership: MonoBehaviour {

     public enum Faction {
          CATS,
          DOGS,
          HAMSTERS
     }

     public Faction faction;
}

```

When you add this component to a GameObject, you will have a dropdown menu in its inspector where you can pick the faction it belongs to between "CATS", "DOGS" and "HAMSTERS".

You don't *need* to create a separate MonoBehaviour for this, by the way. You could just add this enum and public variable to an existing one if you have one where it makes sense. But I don't know what else you got in your project, so let's go with a dedicated behaviour for this.

Now back to your collision function. I assume you want to find out if the object belongs to a different faction. In that case you would do this:

```
private void OnCollisionEnter2D(Collision2D collision)
{
    // get the faction membership components of both objects.
    // note: if you call this function a lot, you might want to
    // store myFactionMembership in a private class-level variable
    // which you read in Start to improve performance
    FactionMembership myFactionMembership = GetComponent<FactionMembership>();
    FactionMembership otherFactionMembership = collision.gameObject.GetComponent<FactionMembership>();

    // do both objects in this collision actually have a faction membership?
    // If not, then we are not interested in this collision.
    if(myFactionMembership == null || otherFactionMembership == null) {
         return;
    }
    // check if we have encountered an enemy
    if (myFactionMembership.faction != otherFactionMembership.faction) {
          Console.log("Enemy encountered!");
    }

}

```

This code of course assumes that all 3 factions we have in this game are mortal enemies who will always fight each other. But this might not always be the case. For example, what if the dogs and the hamsters have forged a temporary alliance against the cats? In that case it might make sense to add a helper method `bool IsEnemyOf(FactionMembership other)` to FactionMembership.

```
    FactionMembership myFactionMembership = GetComponent<FactionMembership>();
    FactionMembership otherFactionMembership = collision.gameObject.GetComponent<FactionMembership>();
    if(myFactionMembership == null || otherFactionMembership == null) {
         return;
    }

    if (myFactionMembership.IsEnemyOf(otherFactionMembership)) {
          Console.log("Enemy encountered!");
    }

```

How that method determines which factions are enemies and which are not is outside of the scope of this answer, because the logic for this could get quite complex depending on what exactly your requirements are.
> 1 votes

# Answer
A common method to find out what kind of game object you are actually colliding with is to use `collision.gameObject.GetComponent` to find out if it has a certain component attached to it and then act accordingly.

For example, if all enemies and obstacles in your game have a script `Hazard` and all the collectible goodies have a script `Collectible`, you can write code like that:

```
private void OnCollisionEnter2D(Collision2D collision)
{
      Hazard hazard = collision.gameObject.GetComponent<Hazard>();
      if(hazard) {
            Console.Log("We collided with something bad :(");
            life -= hazard.damage;
      }

      Collectible collectible = collision.gameObject.GetComponent<Collectible>();
      if(collectible) {
            Console.Log("We picked up something good :)");
            score += collectible.scoreValue;
      }
}

```

By the way, you might notice that this code allows for an object to be both a hazard and a collectible at the same time.
> 0 votes

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


# Question
Title: How to export an IK structure created in Blender 2.8 to Godot 3.1?
I created this IK bone structure in Blender 2.8 and exported as `.escn`

As you can see, in Blender it's working ok. Now, how to use it in Godot?

I've tried export with:

1. `.dae` (native)
2. `.dae` (Better Collada)
3. `.escn`
4. `.glb`

None of them worked...

Is there any tutorial for using imported IK in Godot?

# Answer
> -1 votes
Godot has a demo project specifically for inverse-kinematics. It's not exactly a tutorial but it's a great place to start.

Download the package and use Godot's Project Manager to scan/import the folder for 3d IK.

---
Tags: blender, godot, export, inverse-kinematics
---


# Question
Title: FPS-like mouse-look camera WinAPI problem
I have a problem with implementing mouse-look camera movement, like in FPS games. For me common solution is:

1. Process `WM_MOUSEMOVE` event in `WndProc`
2. Calculate delta movement from the window's center using event's `lParam`
3. Rotate camera
4. Return cursor back to window's center using `SetCursorPos`

The problem is when `SetCursorPos` is called, another `WM_MOUSEMOVE` event is being fired. So camera rotates back.

What is the common way to create such type of camera on Windows platform (using WinAPI)?

I know that in `WM_MOSEMOVE` I can check is `mouse.x == windowCenter.x` and if it is - do nothing, but it's a hack from my point of view. Is there any "non-hacky" way to achieve the goal?

# Answer
You can use GetCursorPos, and use the result from that to calculate how far the mouse has moved from the center, then SetCursorPos to put it back. With this scheme you don't even need to handle WM\_MOUSEMOVE messages; just call GetCursorPos each frame.

This, IIRC, is the approach used by Quake and derivatives.
> 1 votes

# Answer
You can use some sort of flag to skip WM\_MOUSEMOVE handling whenever you are adjusting cursor position. That may seem a bit hacky too, but that's how usually this gets done.
> 0 votes

---
Tags: camera, input, first-person-shooter, winapi
---


# Question
Title: texturing a race track - applying variations
I have created a simple race track in Blender using bezier curve, array and curve modifiers. A track is created from simple planes and the basic seamless asphalt texture looks quite good.  As you can see a basic texture is repeated for a single segment to better match a track scale. I would like to add to the race track some variations, for example a normal map with cracks and transparent texture with tyre marks. I wonder how to achieve a realistic effect. I have two ideas:

* prepare many different textures and load them randomly for a track segment
* prepare a few bigger textures, generate somehow a second texture coordinates channel and apply bigger textures for a group of the segments

but maybe there is better way.

Finally I would like to export that race track (for example as wavefront obj file) and load in opengl graphics engine using assimp library.

How such texture variations are achieved in games ?

# Answer
> 0 votes
If you're looking for a quick and easy method press 5 to enter orthographic mode, press 7 to enter top down view, and finally press the 'U' key over the 3d View and select Project from View. This will overlay the entire 3d plane into the 0-1 space. You can press 5 again to leave Ortho mode.

---
Tags: textures, blender, uv-mapping, 3d-modeling
---


# Question
Title: Why boxCollider bound extents change when changing the size of an gameObject but doesnt in the script?
So, I have two players when I first made them they were with the default size `Y = 1`. After I finished the scripts I wanted to change their size but when I did that, the calculations use the size of `Y = 1` and I don't understand why is that.

The code I am running is this:

```
public class Player1Controller : PlayersController {
    private Vector3 downMost;
    private Vector3 upMost;
    private float minY, maxY;
    private float halfHeight;

    // Start is called before the first frame update
    private void Start () {
        halfHeight = GetComponent<SpriteRenderer> ().sprite.bounds.extents.y;

        float distance = transform.position.z - Camera.main.transform.position.z;
        downMost = Camera.main.ViewportToWorldPoint (new Vector3 (0, 0, distance));
        upMost = Camera.main.ViewportToWorldPoint (new Vector3 (1, 1, distance));

        minY = downMost.y + halfHeight;
        maxY = upMost.y - halfHeight;
    }

    // Update is called once per frame
    private void Update () {
        float verticalMovement = Input.GetAxis ("Player1Vertical");
        MovePlayer (verticalMovement, transform);
        PlayerLimit (transform, minY, maxY);
    }
}

```

The PlayerLimits method is

```
public void PlayerLimit (Transform transform, float minY, float maxY) {
        float restrictY = Mathf.Clamp (transform.position.y, minY, maxY);
        transform.position = new Vector3 (transform.position.x, restrictY, transform.position.z);
    }

```

***I assume the problem is either in the `sprite bounds.extents.y` or the `restrictY` but I don't get it.***

This helps me with the Player limits, shown in the next image:

As you can see on the left side is the modified player with size less than 1 and on the right side is the player with the default size, the script is the same but the calculations are wrong. The left bar had to go till the end of the border but it doesnt.

# Answer
> 0 votes
Collider boundaries extents do not scale with the Transform. The GameObject / MeshRenderer's role is to give a **visual** shape to your object while the Collider's role is to give it a **physical** shape in the Physics world. If one aspect (either visual or physical) changes it doesn't have an impact on the other one. I agree that the fact the Collider automatically tries to fit a Mesh bounds when you add it to a GameObject the first time can be missleading.

TL;DR: if you need to get the right size of the Collider bounds extents, simply scale them accordingly to `transform.localScale`. Something like:

```
Vector3 extents = _my_collider.bounds.extents;
extents.x *= _my_transform.localScale.x;
extents.y *= _my_transform.localScale.y;
extents.z *= _my_transform.localScale.z;

```

*side note: it's simple when a scale is applied to your game object only... but can get messier if your game object parents are scaled too. Then you'll have to loop in the hierarchy from root to your game object and combine every scaling value*

---
Tags: unity, c#, 2d
---


# Question
Title: How do I implement a banner ad from MoPub in my Android Unity app?
I am new with Unity and everything and I have made a simple game. I wanted to put a MoPub banner ad on the game and I read this on their site. But I was wondering where should I put that code from the site. Or even more useful if someone could show me how to do it.

# Answer
> 0 votes
Well, the introduction part of your link seems straightforward. You can request the banner and display it whenever and wherever you want.

If you want to have a banner at the end of your level for example. Once you reach the end of the level you can just add the request / display code shown in the tutorial in the code that display the end of your game level, and the banner will be displayed. Once you are done (for example when player clicks on "play again"), you can simply hide, then destroy the banner.

---
Tags: unity, android, advertisements
---


title: Catan Optimal Placement

text:
# Question
Title: Catan Optimal Placement
Is it possible to calculate the best possible placements for settlements in Catan without using an ML algorithm?

While it is trivial to simply add up the numbers surrounding the settlement (highest point location), I'm looking to build a deeper analysis of the settlement locations. For example, if the highest point location is around a sheep-sheep-sheep, it might be better to go to a lower point location for better resource access. It could also weight for complementary resources, blocking other players from resources, and being closer to ports.

It seems feasible to program arithmetically, yet some friends said this is an ML problem. If it is ML, how would one go about training, as the gameboard changes every game?

Edit: Catan is fairly complex, but involves a setup of placing hexagonal "tiles" randomly to make the board (example board below) . One can then, in turn with the other players, place 2 settlements on the board at corners. Settlements cannot be placed on corners directly next to each other, giving you the ability to deny spots to others. Settlements give you the ability to get the 3 resources around them. One needs certain resources to do certain things, but generally even-ish balance of resources through the game. You also want resources with number chips closer to 7, as you only get the resource if the 2 die rolled every turn land on that number. After the 2 initial settlements, you can build roads out and build new settlements. If you have a settlement on a port, you can also trade according to that port's trade type.

see this video for a tutorial on Catan

# Answer
There are a small fixed set of possible locations on the board so measuring each one against your metrics and picking the best one would be no problem. The issue is, whether you can come up with good, (or merely good enough,) metrics.

In other words, if you want the best place(s) to place a settlement then you need to define what best means. Then the rest is merely calculation.

Without a definition of what best means you would have no way of checking whether a ML algorithm is doing the right thing or not. ML models are currently very hard to understand the workings of. If you train a model and it gives you an answer that seems off, then what do you do?

If you go with a rules-based approach, then if you find the answer is different than you expect you can at least look at the rules and the particular input and figure out which rule caused that answer to be chosen. Then you can tweak the rules as necessary, iteratively approaching best, at least in your judgment.
> 1 votes

# Answer
**TL;DR**

If you use expected values you would not need to use chances explicitly although you would calculate a risk neutral entity.

---

Your could as you mentioned go for a ML approach here, but you might as well assign each adjacent field its expected value if rolling a set of dice, i.e. its chance \[since you get 1 per roll\] and maximize over the sum of chances.

If you now want to account for different resources you would factor in your current chance of getting said resource on any roll

*I am already adjacent to a forest with a 2, resulting in a 1/36 value, therefore another forest will be less good as if it was my first on, but it would still be very beneficiary for me.*

I would guess reducing any new fields value by the summed up value of all accounts of access you have to the given resource already.

*Any new forest would have its value reduced by 1/36 in the above example.*

But you can go further by factoring in the increased amount of wood and clay needed in the early game and the increased amount of ore needed in late game by additionaly factoring in the amount of points or settlements you already have.

Now you still would want to give the harbours some value in your calculations unless your algorithm/AI cannot yet interchange resources.

Maybe open another question for that part.
> 0 votes

---
Tags: java, mathematics, architecture, ai
---


# Question
Title: Why moving platform script is not working?
I have some code attached to a moving platform:

```
public Transform pos1, pos2;
public float speed;
public Transform startPos;

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

// Update is called once per frame
void Update()
{
    if (transform.position == pos1.position)
    {
        nextPos = pos2.position;
    }
    else if (transform.position == pos2.position)
    {
        nextPos = pos1.position;
    }
    transform.position = Vector3.MoveTowards(transform.position, nextPos, speed * Time.deltaTime);
}

private void OnDrawGizmos()
{
    Gizmos.DrawLine(pos1.position, pos2.position);
}

```

But my platform does not go to the pos2 when it reaches the pos1. What is wrong here?

# Answer
> 1 votes
I'm not sure how "MoveTowards" method works, but if you're working on floats then most likely you'll never have exact match of positions.

When doing path followers, I always check the distance between current position and target (pseudocode):

```
if (VectorLength(transform.position-pos1.position) < speed*Time.deltaTime)
{
    nextPos = pos2.position;
}

```

# Answer
> 0 votes
I agree with @crueltear's answer, I just wanted to provide some code that you might add in your script:

Since it is likely that the `transform.position` `pos1.position` will not perfectly match, try and add a bit of "discrepancy" so that instead of waiting for the positions to match perfectly you just have to wait for them to be within a certain distance.

Try and introduce a `float`, e.g. `public float
gapDistance` and replace in your if statements

```
(transform.position == pos1.position)

```

With

```
(Vector3.Distance(transform.position , pos1.position) <= gapDistance)

```

Do the same for `pos2.position`. If you are using 2D Vectors instead of 3D, just change `Vector3` with `Vector2`

# Answer
> 0 votes
I would recommend adding a few debug logs in update to see what it’s doing.

```
// Update is called once per frame
void Update()
{
    if (transform.position == pos1.position)
    {
        nextPos = pos2.position;
        Debug.Log("Starting move to pos2 at " +  nextPos);
    }
    else if (transform.position == pos2.position)
    {
        nextPos = pos1.position;
        Debug.Log("Starting move to pos1 at " +  nextPos);
    }
    transform.position = Vector3.MoveTowards(transform.position, nextPos, speed * Time.deltaTime);
    Debug.Log("move towards " + nextPos + "; new position is " + transform.position);
}

```

Check the console to see what is getting logged.

---
Tags: unity, platformer, moving-platforms
---


# Question
Title: Implementing a more reliable upwards slash?
I am working on a 2D action platformer and I am currently implementing an upwards slash.

For a normal horizontal slash, the player must press the attack button. For an upwards slash, the player must hold up and press the attack button.

I notice that when trying to do an upwards slash, players often press the attack button a few milliseconds before the up button, causing the player to do a normal slash rather than the intended upwards slash. It feels bad.

**I am wondering what are some techniques I could use to get a more reliable-feeling upwards slash?**

I considered waiting for some interval (for example, 20 milliseconds) after attack is pressed to see if up is pressed. If it is pressed in that interval, do upwards slash, otherwise do regular slash at the end of the interval. But this made the game feel unresponsive.

For a similar reason, I want the attacks to happen on button press rather than button release.

# Answer
> 2 votes
Usually the way we handle this is to introduce a new move that's a "slash precursor" whose short ~2-frame animation reads plausibly as the lead-in for either a horizontal or vertical slash.

When the button is pressed without the up button held, we immediately start the slash precursor move.

If the up button is pressed while we're in the slash precursor, we transition into the upward slash, starting partway into its animation since the precursor already gave us the lead-in. This way the attack still lands with the same timing, even if we hit the up button a tiny bit late.

If we hit the end of the precursor animation and up still hasn't been pressed, we continue into the payoff of the horizontal slash, again skipping any lead-in since the precursor animation handled that role.

This does impose some constraints on your moves' gameplay and visible/audible feedback. Your horizontal slash move needs a delay before it hits that's at least as long as your window of opportunity for a late up-press. And your first few frames of motion, animation, and sound have to work decently for either attack, with the differentiation pushed toward the end of the move.

If those constraints aren't acceptable for your needs, then you may need to change your control scheme so that both moves can be unambiguously distinguished in the initial press event.

---
Tags: 2d, input, state
---


# Question
Title: Translate transform and RigidBody2d Addforce relative to world space
I'm developing a game with my friends from University. Currently, I'm in the process of creating a basic movement system for the main player with a box form as its mesh. I used transform.Translate to move the player object left and right and a rigidbody.addForce to allow the player to jump

However, I found out that if the player was rotated due to it falling for a bit, it seems that the script moves the player object relative to the gameObject's axis. I would like to move the player relative to the world and not relative to the player. It would be nice if someone could tell me how to change from local to world. Here's my code:

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

[RequireComponent(typeof(Rigidbody2D))]
public class PlayerMovement2 : MonoBehaviour
{
    [SerializeField] private float speed;
    [SerializeField] private float upForce;
    [SerializeField] Rigidbody2D rb;

    //usahakan semua value di set di dalam script
    //initialize semua value di start, karena start udh memastikan value di set sekian (kalo di global, bisa aja value nya ganti sendiri)

    private bool left = false;
    private bool right = false;
    private bool jumpUp = false;
    private bool sprints = false;

    bool isGrounded;

    // Start is called before the first frame update
    void Start()
    {
        speed = 10;
        upForce = 40000f;
        rb = GetComponent<Rigidbody2D>();
        rb.gravityScale = 6;
        isGrounded = true;
    }

    // Update is called once per frame
    void Update()
    {
        left = Input.GetKey(KeyCode.A);
        right = Input.GetKey(KeyCode.D);
        jumpUp = Input.GetKey(KeyCode.W);
        //sprints = Input.GetKey(KeyCode.LeftShift);
    }

    private void FixedUpdate()
    {
        if(left) transform.Translate(Vector2.left * speed * Time.deltaTime);
        if(right) transform.Translate(Vector2.right * speed * Time.deltaTime);
        if (jumpUp && isGrounded) jump();

    }

    private void jump()
    {
        Debug.Log("jump()");
        rb.velocity = Vector2.zero;
        rb.AddForce(Vector2.up * upForce * Time.deltaTime);
        isGrounded = false;
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (!isGrounded) isGrounded = true;
    }
}

```

# Answer
As DMGregory pointed out, you can make transform.Translate ignore the rotation of the object by passing `Space.World` as the second parameter:

```
transform.Translate(Vector2.left * speed * Time.deltaTime, Space.World);

```

However, you generally should not manipulate the transform of an object directly when that object also has a non-static and non-kinematic Rigidbody. When you have an object which is influenced by physics, then you should only manipulate it through its Rigidbody component. If you manipulate its transform directly without going through the rigidbody then you can encounter a lot of weird physics glitches like phantom forces or imprecise collision detection.

The most direct conversion from your current architecture to using rigidbody-only movement would be to use `rigidbody.MovePosition(Vector3 newPosition)` instead of Translate. But it might be even better if you can find a way to use rigidbody.AddForce for both jumping and walking.
> 1 votes

# Answer
When you have a question about how the Unity API works, please take thirty seconds to consult the documentation:

> `public void Translate(Vector3 translation);`
> `public void Translate(Vector3 translation, Space relativeTo = Space.Self);`
>
> **Description**
>
> Moves the transform in the direction and distance of translation.
>
> If `relativeTo` is left out or set to `Space.Self` the movement is applied relative to the transform's local axes. (the x, y and z axes shown when selecting the object inside the Scene View.) **If `relativeTo` is `Space.World` the movement is applied relative to the world coordinate system.**

`AddForce` is already applied in world space:

> **Rigidbody.AddForce**
>
> `public void AddForce(Vector3 force, ForceMode mode = ForceMode.Force);`
>
> **Parameters**
>
> `force` Force vector *in world coordinates.*
> 0 votes

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


# Question
Title: Need help with a C26495 warning and E0513 error in a C++ SFML class
I'm currently learning to program a game with the SFML library.I dugged up a bunch of SFML tutorials on Youtube and found a really good one by 'Suraj Sharma':

https://www.youtube.com/channel/UC2i39AOpDSlO1Mrn1jQ8Xkg

I'm now making an animation class following his tutorial. Here's the video I'm watching:

https://www.youtube.com/watch?v=pq9OuBHJiVM&list=PL6xSOsbVA1ebkU66okpi-KViAO8\_9DJKg&index=27

> A C26495 warning:Variable 'AnimCmp::Timer' is uninitialized.Always initialize a member variable(type.6). Blockquote

and a

> E0513 error:a value of type "AnimCmp::Anim\*" cannot be assigned to an entity of type "AnimCmp::Anim\*"

appears right when I was watching the first 8 minutes of the video. Here's my code, compiled in Visual Studio 2019 community (Take notes that all declared classes, functions and variables are an abbreviated version of the video):

AnimCmp.h:

```
#pragma once
#ifndef ANIM_CMP_H
#define ANIM_CMP_H
//i've put every required headers in a precompiled one
#include "pch.h"

class AnimCmp
{
private:
    class Anim {
    public:
        //Vars
        sf::Sprite& Spr;
        sf::Texture& TexSheet;
        sf::IntRect StartRct;
        sf::IntRect CurrRect;
        sf::IntRect EndRct;

        float Timer;
        float AnimTimer;
        int w;
        int h;
        //C26495 at Anim's constuctor
        Anim(sf::Sprite& Spr, sf::Texture& TexSheet, float AnimTimer, int stx, int sty, int frx, int fry, int w, int h)
            :Spr(Spr), TexSheet(TexSheet),AnimTimer(AnimTimer),w(w),h(h){
            this->w = w;
            this->h = h;
            this->StartRct = sf::IntRect(stx * w, sty * h, w, h);
            this->CurrRect = this->StartRct;
            this->EndRct = sf::IntRect(frx * w, fry * h, w, h);

            this->Spr.setTexture(this->TexSheet, true);
            this->Spr.setTextureRect(this->StartRct);
        }
        //virtual~Anim();
        //Functions
        //void Pause();
        void Reset() {
            this->Timer = 0.f;
            this->CurrRect = this->StartRct;
        }

        void Play(const float& dt) {
            //Update Timer
            this->Timer = 10.f*dt;
            if (this->Timer >= this->AnimTimer) {
                //Reset Timer
                this->Timer = 0.f;
                //Animate
                if (this->CurrRect != this->EndRct) {
                    this->CurrRect.left += this->w;
                }
                else {//Reset
                    this->CurrRect.left = this->StartRct.left;
                }
                this->Spr.setTextureRect(this->CurrRect);
            }
        }
    };

    sf::Sprite& Spr;
    sf::Texture& TexSheet;
    std::map<std::string, Anim*> Anims;
public:
    AnimCmp(sf::Sprite& Spr,sf::Texture& TexSheet);
    virtual~AnimCmp();
    //Functions
    void AddAnim(const std::string key, sf::Sprite& Spr, sf::Texture& TexSheet,
        float AnimTimer, int stx, int sty, int frx, int fry, int w, int h);

    void Start(const std::string Anim);
    void Pause(const std::string Anim);
    void Reset(const std::string Anim);
    void Play(const std::string key, const float& dt);
};
#endif // !ANIM_CMP_H

```

AnimCmp.cpp:

```
#include "AnimCmp.h"

AnimCmp::AnimCmp(sf::Sprite& Spr, sf::Texture& TexSheet)
    :Spr(Spr),TexSheet(TexSheet)
{
}

AnimCmp::~AnimCmp()
{
    for (auto& i : this->Anims) {
        delete i.second;
    }
}

void AnimCmp::AddAnim(const std::string key, sf::Sprite& Spr, sf::Texture& TexSheet,float AnimTimer, int stx, int sty,
 int frx, int fry, int w, int h)
{
    this->Anims[key] = new Anim(this->Spr, this->TexSheet, AnimTimer, stx, sty, frx, fry, w, h);//E0513
}
//Functions
void AnimCmp::Start(const std::string Anim)
{
}

void AnimCmp::Pause(const std::string Anim)
{
}

void AnimCmp::Reset(const std::string Anim)
{
}

void AnimCmp::Play(const std::string key, const float& dt)
{
    this->Anims[key]->Play(dt);
}

```

The thing is the game still runs even when an error is showing. I'm just not sure how it'll affect the game.

# Answer
> 1 votes
> A C26495 warning:Variable 'AnimCmp::Timer' is uninitialized.Always initialize a member variable(type.6).

As it says, the compiler tells you that you have a class variable that is not initialized.

It will most likely look at the variable declaration

```
class AnimCmp
{
private:
    class Anim {
    public:
        //Vars
        float Timer;

```

...in the constructor initialization list...

```
            :Spr(Spr), TexSheet(TexSheet),AnimTimer(AnimTimer),w(w),h(h){

```

...or in the constructor body...

```
        {
            this->w = w;
            this->h = h;
            this->StartRct = sf::IntRect(stx * w, sty * h, w, h);
            this->CurrRect = this->StartRct;
            this->EndRct = sf::IntRect(frx * w, fry * h, w, h);

            this->Spr.setTexture(this->TexSheet, true);
            this->Spr.setTextureRect(this->StartRct);
        }

```

to find a place where you actually assign a value to the variable.

In no case here there is such a thing.

So you have the choice, either:

at the variable declaration

```
class AnimCmp
{
private:
    class Anim {
    public:
        //Vars
        float Timer {};

```

...in the constructor initialization list...

```
            :Spr(Spr), TexSheet(TexSheet),AnimTimer(AnimTimer),w(w),h(h),Timer(0.0f){

```

...or in the constructor body...

```
        {
            this->Timer = 0.0f;
            this->w = w;
            this->h = h;
            this->StartRct = sf::IntRect(stx * w, sty * h, w, h);
            this->CurrRect = this->StartRct;
            this->EndRct = sf::IntRect(frx * w, fry * h, w, h);

            this->Spr.setTexture(this->TexSheet, true);
            this->Spr.setTextureRect(this->StartRct);
        }

```

An uninitialized variable will always behave the same in debug mode because the compiler is happy to set a default value for you, but all hell can break loose in release. It's possible that your code is unaffected by such a thing, but the compiler does not know that. Better to initialize it for the sake of remove potential issues.

---

As for your other issue, I'm not exactly certain why it is occurring. Maybe you do not show everything that has to be shown for us to give you a definitive answer.

Shooting in the dark, and following a google search, you might have declared some parts of the map (or the function) as being `const`, or maybe the compiler thinks your c++ code is actually c code.

---
Tags: c++, animation, sfml, visual-studio
---


# Question
Title: Inventory objects not persisting between scenes?
My Game Manager object has an Inventory script attached to it, which has "Don'tDestroyOnLoad(gameObject)" in its Awake function. During gameplay, items are pushed into a public List in this script. This is done successfully. The trouble comes when changing scenes, where either script instance is being overwritten or the object that was pushed into the list has been destroyed. How can I prevent this in a way that will scale well?

I am linking to a video you can watch of this problem happening in real time:

https://youtu.be/CLzDJg15VTk

This is the Inventory script, which is attached to my GameManager:

```
// Inventory.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Inventory : MonoBehaviour
{
    private static Inventory instance = null; // static (class level) variable
    public static Inventory Instance { get { return instance; } } // static getter (only accessing allowed)

    public List<GameObject> itemList;

    private void Awake()
    {
        // if instance is not yet set, set it and make it persistent between scenes
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            // if instance is already set and this is not the same object, destroy it
            if (this != instance) { Destroy(gameObject); }
        }
    }

    // debug only
    public void Debug_PrintItemInventory()
    {
        foreach(GameObject obj in itemList)
        {
            Debug.Log(obj.GetComponent<Item>().itemName);
        }
    }

    public void AddItem(GameObject item)
    {
        itemList.Add(item);
        Debug_PrintItemInventory(); // debug only
    }
}

```

This is the script that pushes an item into my character's inventory ("gm.GetComponent

```
// ItemBox.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ItemBox : MonoBehaviour
{
    bool disabled = false;
    private Animator anim;
    [SerializeField]
    private GameObject[] items = new GameObject[3];
    [SerializeField] private GameObject gm;

    void Start()
    {
        anim = GetComponent<Animator>();
        if (!disabled)
        {
            anim.Play("ItemBoxIdleState");
        }
    }

    void OnTriggerEnter(Collider other)
    {
        if (!disabled && other.gameObject.tag == "Player")
        {
            anim.Play("ItemBoxGetItemState");
            int randInt = Random.Range(0, 3);
            GameObject itemObj = Instantiate(items[randInt].GetComponent<Item>().getPrefab, transform.position + new Vector3(0, 0.375f, 0), Camera.main.transform.rotation);
            gm.GetComponent<Inventory>().AddItem(Instantiate(items[randInt]));
            Destroy(itemObj, 1.6f);
            disabled = true;
        }
    }
}

```

# Answer
`gm.GetComponent<Inventory>().AddItem(Instantiate(items[randInt]));`

On this line you instantiate a new GameObject on your scene, which happens **before** loading the new scene. You put a reference of that new object in the list of the Inventory (which is set as persistent during loadings).

When you ask for a scene loading, all the content of your current scene is destroyed except game objects that are marked as persistent (via `DontDestroyOnLoad()`). So your Inventory object is kept, its content too, but the item you created is destroyed... and so the reference to it in the inventory list too. That explains why the Inventory still has one item in its list, but it's null.

The easy trick here, would be to set the Inventory (that is not destroyed on load) as the parent of the created item. It'll make it persistent, so the reference will be kept accross loadings.
> 4 votes

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


title: Center Gravity in Unity

text:
# Question
Title: Center Gravity in Unity
a 2d planet in the center, where the players will be able to walk on it and also will be affected by center gravity. planet will be static and there won't be any other planets. so;

Is there a way that I can change the gravity position? yes you can adjust gravity via project settings but I want it to be in the middle x,y,z(0,0,0)

I have tried creating my own gravity but it wasn't very useful because objects wouldnt fall, stand on foot and also in contact with another object they would vibrate instead of standing still. (if they stand on the planet they would vibrate)

```
        private void FixedUpdate()
{
    foreach(GameObject item in grav)
    {
        Attact(item);
    }
}

private void Attact(GameObject gmf)
{
    Rigidbody2D rgg = gmf.GetComponent<Rigidbody2D>();

    Vector3 direction = rg2d.position - rgg.position;
    float distance = direction.sqrMagnitude;

    float forceMag = (10 * rgg.mass) / distance;
    Vector3 force = direction.normalized * forceMag * 10;

    rgg.AddForce(force);
}

```

I can create a script that will change the gravity by the opposite of the object's position. this does work but I cannot see any way to do it for more than one object.

# Answer
> 2 votes
Are you aware of the PointEffector2D component? I believe that is exactly what this is for.

See this tutorial (step 7). (Link directly to video)

# Answer
> 1 votes
You can't use the Unity gravity system for point gravity sources. As mentioned by the answer by Ed Marty, you can use the PointEffector2D component to create a point gravity source, but only if all your rigidbodies have the same mass.

But you can also very easily build your own gravity system. Here is an example script for a "Gravity Source" component. Place it at your center of gravity, set the "gravity" value in the inspector to your desired acceleration and give it a trigger-collider which represents the zone in which it is supposed to affect objects.

```
using UnityEngine;

public class GravitySource : MonoBehaviour {

    public float gravity;

    void OnTriggerStay2D(Collider2D other) {
        if (other.attachedRigidbody) {
            Vector2 difference = this.gameObject.transform.position - other.gameObject.transform.position;
            Vector2 gravityDirection = difference.normalized;
            Vector2 gravityVector = gravityDirection * gravity;

            other.attachedRigidbody.AddForce(gravityVector, ForceMode.Acceleration);
        }
    }
}

```

This script is a simplified version of my script from my answer to the question "How can I accurately simulate orbits in Unity?". The more complicated version works with 3d rigidbodies and simulates gravity getting weaker with distance.

What this script does not do is tell the objects it affects where "down" is. Depending on your game you might want to rotate objects towards the center of gravity under some conditions. If you want to add this, then you can use the `gravityDirection` vector for this purpose.

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


# Question
Title: How would you go about placing objects between chunks in a 2D game?
I have a 2D infinitely generated world which is split up into 9 chunks at a time. Three chunks are loaded and three are unloaded whenever a player moves into a new chunk (if the player moves up a chunk the top three chunks are loaded and the bottom three are unloaded so there's always 8 chunks surrounding the player, pretty standard). My chunks are stored as 16x16 2D arrays so I loop through the array of chunks and then through each dimension of the array to access tiles.

In my game the player can place buildings and other various things which are technically groups of tiles that take up a few spaces on the grid. The issue I'm having is knowing how to refer to adjacent chunks as to whether or not the object should be allowed to be placed.

If the player is trying to place an object within the boundaries of a single chunk this is fine and works great because I can check the tiles within that chunk easily. However when checking across chunk boundaries (worst case 4 different chunk arrays) things because incredibly complicated and bug prone.

How I'm managing it right now:

The player is trying to place a 4x4 tiled building on the boundary of ChunkArray\[1,1\] (always the chunk under the player, as ChunkArray\[2,2\] makes up 9 chunks) and ChunkArray\[2,1\] (the chunk directly to the right of the player.

If the 4x4 building overlaps directly down the center of the boundary, lets say ChunkArray\[1,1\]\[15,5\] and ChunkArray\[1,1\]\[15,6\] (two adjacent tiles, one above the other on the right side of main chunk) and therefore ChunkArray\[2,1\]\[0,5\] and ChunkArray\[2,1\]\[0,6\] (same thing but on left side of adjacent chunk) then I'm checking to see if those tiles in the chunk to the right are clear and the tiles in the chunk under the player are clear.

You can see how this would become hellish when dealing with objects which are even larger than 4x4 or even worse if they overlap 4 different chunks at the same time.

I also thought about treating all 9 chunks relative the player as a super-chunk and combining all the chunks into one large array which would make placing objects much easier, although I haven't really processed how realistic this would be as loading/unloading and rearranging the super chunk every time a player moved between chunks could be insane.

Is there some obvious solution I'm missing?

# Answer
Abstract chunks!

You probably have a class handling these chunks, have it be the source of truth for your world, mine is called WorldHandler, I tell it to read from position x,y and it transparently gets the chunk I need and uses it.

```
class ChunkHandler { // this is our "WorldHandler"
    private int[,] _chunks = new Chunk[ 16, 16 ];
    // Use a dynamically allocated array instead for memory flexibility / performance

    // Uses a global tile position to set data into the correct chunk
    public void set( int x, int y, int data ) {
        // Can be simplified if you don't have negative positions
        int cx = Math.Floor( (float) x / 16.0f );
        int cy = Math.Floor( (float) y / 16.0f );

        const chunk = this.getChunk( cx, cy );

        // Gives the chunk the relative position
        this.chunk.set( x - cx * 16, y - cy * 16, data );
    }

    // Gets the chunk
    public void getChunk( int cx, int cy ) {
        // Check if the chunk exists and is functional before returning it
        if ( ! _chunks[ cx ][ cy ].exists ) {
            // Initialize the chunk into memory because we might need it
            _chunks[ cx ][ cy ].init();
        }
        return _chunks[ cx ][ cy ];
    }
}

```

Then you don't need to think about Chunks anymore, they are abstracted and isolated from your game world:

```
class Chunk {

    int[,] _blocks = new int[ 16, 16 ];
    // Again, dynamically allocated structures are better

    // Sets a relative position tile data in this chunk
    public void set( int x, int y, int data ) {
        // You probably have something more complicated here
        _blocks[ x ][ y ] = data;
    }
}

```

If chunk lookup is hard (it generally isn't), you could add a cache of 'last-accessed-chunk' at your World Handler class.

Here's an example with a 4-tile-aligned chunk:

```
  +4  +5  +6  +7   +8  +9  +10  +11
|----------------|-----------------|
|              X | X               |
|              X | X               |
|      C+0       |        C+1      |
|                |                 |
|----------------|-----------------|

```

I can transparently access position like so:

```
world.get(7, 0) == "X" // top left, accesses first chunk
world.get(8, 0) == "X" // top right, accesses second chunk
world.get(7, 1) == "X"
world.get(8, 1) == "X"

```

The idea behind this abstraction is that a placement of a multi-tile object doesn't need to be aware of how the world is layed out, that problem should be solved by a specific class.

And if you happen to store these multi-blocks objects as an object with x and y instead of in-world tiles, you could store a list of chunks that it is present to load conditionally only when all these chunks are loaded into the screen (or load it partially if any of these chunks are loaded). You could even create a class just to handle this saving of multi-block structures in your world, something like WorldMultiTileMemory.

By the way the names I provide are suggestions, I might not be the best at naming things.

If you're interested you can read more about decoupling patterns here.
> 0 votes

# Answer
I'm not sure what does a chunk actually contain in your implementation. I assume that these chunks are memory intensive, if you want to lazily load them. It seems to me that if you decoupled your logic from game engine content, you could easily load to memory and check a lot of grid spaces at the same time. This will require you to keep some kind of sparse container that will remember what each grid space logically contain, but that shouldn't be too complex. looping though 4 16x16 containers is at most 1024 operations, which is very little, assuming the repeated operation is quick.

For example, just for the sake of the current issue, you could cache which chunks contain things with a container of bools, and check the container in order to check whether the relevant chunks are filled, without loading the actual chunks to memory.
> 0 votes

---
Tags: c#, xna, monogame, tiles
---


# Question
Title: How to Store AI Knowledge about the Game-World for AI Decision Making
I have a game-world with a fair amount of AI that have some **Senses**, like vision, hearing, touch, smell, etc.

But I'm not sure how to put that information in a single place for the individual AI to then iterate over it and make a decision.

For example, each sense (emitter and receiver) currently returns a structure called a *Stimulus* with information like position, direction, stimulus type (sight, sound, smell, etc), npc type (human, animal, monster, etc), and so on.

And currently, the monster AI just have a hard-coded hierarchy of preference - touch (e.g., damage events) \> sight \> sound \> smell, so if you fire a gun it'll try to follow that noise but if he then sees you, he'll switch to tracking you visually and forget about the noise.

However, this isn't very robust. It doesn't deal with repeated damage events or one player kiting or stale stimuli vs new stimuli very well. Ideally I'd want to use some sort of utility evaluation so that I can get more complex and dynamic behaviour out and I can fix edge cases where it feels like the AI isn't interacting right (e.g., ignoring stimuli that it shouldn't be).

I'm not sure how to approach that implementation. Should I just have an array of every stimulus the AI encounters and loop over that every tick? But then how do I prune that list since it'd get very large very quickly and might contain really old stimuli (currently the AI only has one "target stimuli" and new stimuli go through that hierarchy of preference before being either discarded or replacing the target stimuli).

(As a side note, this GDC Talk about Creating the Living, Breathing World of Hitman has provided some great information about how they deal with Knowledge, but I wasn't able to discern how they store it and iterate through multiple Knowledge fields of a single AI and so on).

(I'd also love any advice on the Knowledge/Stimulus data structure itself; to be modular enough to hold different types of information, instead of having a bunch of unused fields; say how a sound might need only type and direction, but a visual stimulus might only need type and position and so on)

# Answer
As you might know, it is common for ai to act and change behaviour in a Finite State Machine. This a state referes to some kind emotional state of the ai: idle, searching, fighting, running etc.
Now normally, these states are context-free. Its not important, that state of the ai changed from B to K, only that the state right now is in K.

You could use a modified version of an FSM. Lets say, the ai is idle or guarding. It is activly looking for stimuli. if it recieves a stimulus, the state of the ai may change. E.g. the Guard Orc smells something. Now, does the orc recognize the smell? Is he smelling food? Then change the state to hungry. Does he smell another orc, stay in guarding mode or whatever.

To solve your Problem of multiple stimuli, you could:

* Only accept the hightest kind of stimuli.
If the orc fights the character, it should not matter that he hears fighting in the distance.
* Evalute Several stimuli based on the state
If the orc is fighting one player, but sees 3 other players approaching, he might try to escape. Or maybe he hears a signal to retreat while fighting. But if he is not fighting, he could ignore those signals or maybe just change his state to enraged or something. For this you should definitly have some sort of hirachy list of stimuli tha the orc might recieve at every moment.

It seems like you would prefer the second solution. So now what to modify in the FSM?
An example: The orc just hears something from behind the rocks while he smells enemies from another direction. He tries to approach the place he heared the noise from, until the sound stops. Although the sound stops, he would not follow the smell to the other direction immediatly. Of course he would first look for the source of the sound, altough the sound is gone.

To do that, you could have your states with exit. These exits have conditions. if a condition is fulfilled, go through the exit to the connected next state. Now, if a state change needs a stimuli for a state change, save that stimuli to the connection edge. If you are in the next state, you can still access the stimuli, that brought you there, without the stimuli still being active.

The idea is this. The Orc was in the guard state, when he recieved the smell and sound stimuli. The sound gave him some sort of position or maybe only a direction and distance, the smell only direction and distance. When he recieves both stimuli at the same time, he evaluates the sound has higher priority and switches to "looking for sound". Even when the sound stops (so it is removed from the current stimuli list), he can still go there and check. If he does not find anything, he can then follow the smell. If on the way to the sound position he finds something of higher priority, he of course changes the state from "looking for sound" to "saw enemy" or "saw wonded ally" or something. This way, he can even go from "found wounded ally" or "Saw enemy" back to "looking for sound".

So if the orc is fighting and you have several hit detection stimuli or just when his health goes low, he can switch to the "retreat" state, but can still tell his allies, that there is an enemy following him.

As you can see, this kind of FSM does archive what you want, while it can get arbitrarily complex but also saves the needed and followed states.
> 1 votes

---
Tags: game-design, architecture, ai
---


# Question
Title: Run script after game start, before scene load
I'm making some kind of dependencies solving script. To work this script, it must be run before all other MonoBehaviour scripts.

So I made the script something like this:

```
public class DependencyController {
    private static Dictionary<string, bool> m_DependencyTable = new Dictionary<string, bool>();

    static DependencyController() {
        SceneManager.sceneUnloaded += ResetDependencyData;
    }

    ... some other stuffs ...
}

```

I'm using dictionary to compare which dependency script(s) loaded. To can use every script's Awake/Start, I declared as static and instantiated right after.

The system actually work pretty good, all scripts can access DependencyController in Awake/Start without any problem, but have some questions remains:

1. Is static m\_DependencyTable is always created before scene loaded?
2. Is static DependencyController constructor always called after SceneManager is loaded? As you can see, I attached EventListener in SceneManager.sceneUnloaded so that I can clear the dependency table before scene loads.

Any advice will very appreciate it.

# Answer
In Unity we don't Have such a thing. Instead you have to change script running priority. for example you have many scripts that have Awake methods. just go to: Edit \> Project Settings\> then select the Script Execution Order.

Just find you resolver script and drag it on top of others scripts. this way you make sure that it runs before all of scripts.

Just put

```
static DependencyController() {
    SceneManager.sceneUnloaded += ResetDependencyData;
}

```

on awake of that script that runs before all of scripts.
> 1 votes

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


# Question
Title: 3D models on 2D background perspective mismatch
we are working on a tactics game, with a hand drawn 2D backgrounds and 3D models moving on them. The game generates a 2D grid placed on a XY plane, with faux isometric tiles (Diamond Grid).

I have tried following the guides found here to create the "isometric" effect on the 3D models: prepared two ortho cameras, one perpendicular to the 2D elements and seeing only them and another rotated (30,45,0) which sees only 3D models. Like this:

The issue we're having is the mismatch of the positions between the elements seen by the cameras.

Character should be standing on the tile with the green border. This cannot be solved by simply moving the 3D camera to match these positions because the seem to differ for objects placed in different parts of the screen.

Could anyone please help?

Thanks!

# Answer
You could try applying some form of vertex shader (or similar model modification) to fake some of the perspective:

As I understand it, all models in the game are actually at a kind of shear slant. When viewed from above, it gives all the objects in the scene the same kind of look and perspective that they had in the snes days:

There should be a way to transform the 3d model (at run time I guess) to make it look more like an isometric/othogonal projection.
> 3 votes

# Answer
I think your problem might be related to the "Size" attribute of your camera. A higher value will cover a bigger area, and also make the displayed objects move slower. When using several cameras, this might cause the illusion of one objects being further/closer and moving slower/faster.

This could also mess up the position where the object is being rendered, like in your example.

You should try to tweak the size of the amera that renders the charaters.
> 1 votes

# Answer
You can not do this in your current state. You'll have to split your background into tiles and render them in a correct order, also your character should be in this render queue. You need to either preserve the right amount of space on Z axis to fit sprites and characters, or make a render texture use it in your queue. This way everything will be flat and even 0.0001 difference on Z axis will give you proper rendering order. And render your character into that render texture.
> 0 votes

---
Tags: unity, 3d, isometric
---


# Question
Title: Unity Editor stops updating ScriptableObjects if I click away from them in editor
I'm trying to be better about structuring my code, and I think I'm doing it right. The issue I've got right now is I need to get joystick inputs, scale those values appropriately, and then use that scaled data on any number of MonoBehaviour scripts.

I'm trying to split the input conditioning from the end user, and I'd like to do that by using a ScriptableObject to hold the conditioned data.

I was thinking that a MonoBehaviour script would run, get the joystick data, scale it, and then push that data to variables in the ScaledJoystickData ScriptableObject. Later, a second MonoBehaviour script would access the variables in the ScaledJoystickData and use those to move the things in the game.

I'm understanding the benefits of structuring the code this way, especially in that I can access the ScriptableObject from the editor and manipulate those values; I don't actually need to have a joystick connected, and I'm free to test either end of the input handling independently.

The problem is that, if I am looking at the ScriptableObject instance in the editor, it stops updating as soon as I click away from it (to the consuming GameObject). If I click back to the ScriptableObejct instance, none of the values update. Nothing on the GameObject's script updates unless I start the game with that GO selected in-editor, and again THAT fails to update if I click off and click back.

The GameObject script is currently using the values from the ScriptableObject instance and piping them to public variables, and the public variables aren't updating.

Is there some bug with ScriptableObjects, or am I doing this wrong?

:EDIT:

Here's an example. Make a script called "ExampleSO" and replace the contents with:

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

[CreateAssetMenu]
public class ExampleSO : ScriptableObject
{
    public float stashedVar = 0f;
}

```

Make a script called "ExampleWriter" and replace the contents with:

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

public class ExampleWriter : MonoBehaviour
{
    public float scaling = 2f;
    public float scaledInput = 0f;
    public ExampleSO exampleSO = null;

    // Update is called once per frame
    void Update()
    {
        if(exampleSO!=null)
        {
            scaledInput = scaling * (Input.GetKey(KeyCode.LeftArrow) ? 1f : 0f);
            exampleSO.stashedVar = scaledInput;
        }
    }
}

```

Make a script called "ExampleReader" and replace the contents with:

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

public class ExampleReader : MonoBehaviour
{
    public float display = 0f;
    public ExampleSO exampleSO = null;

    void Update()
    {
        if(exampleSO!=null)
        {
            display = exampleSO.stashedVar;
        }
    }
}

```

Create an instance of the ExampleSO, add the ExampleWriter to a game object, and put the ExampleSO instance into the ExampleWriter slot.

Highlight the game object holding ExampleWriter and run it. Push the left arrow key and see the value toggle 0/2.

Click the ExampleSO instance. Nothing is happening there now. Click back on the game object, and now it doesn't update either.

If you have the ExampleReader on the same game object then it won't work at all. ExampleReader will read fine, if you have it on a separate GameObject, but again if you click off and click back then it stops responding.

# Answer
> 2 votes
The input isn't updating when I clicked around in the editor because inputs are only passed to Unity if you click the game view port in editor. By selecting the ScriptableObject instance, or the other GameObject, etc., I was actually clicking off of the Game view port, which stopped the inputs from being passed to Unity.

Once that happened, the ExampleReader (in the example I posted) is no longer getting any inputs, so there's just nothing to write. Nothing written, nothing to read, nothing to update, so of course the ScriptableObject instance and the ExampleReader look like they're not responding.

Super irritating to troubleshoot, but there you go.

---
Tags: unity
---