# Question
Title: Sending different textures to instanced elements draw call
I'm making a little OpenGL renderer. Currently I use VAOs/VBOs and batch all the entities with the same VAO. I then draw using `glDrawElementsInstanced`. I am wondering how can I send a different textures in the uniform for the Sampler2D since each entities might have a different texture ?

Here the batch Java side building the uniform buffer:

```
public class ContainerBatch extends Batch<VisualContainer> {
    private VertexArray vao;
    private Camera perspective;
    private UniformBuffer buffer;

    public ContainerBatch(ShaderProgram program, Camera perspective) {
        super(program);
        this.vao = new RectangleVertexArray();
        this.perspective = perspective;
        this.buffer = new UniformBuffer()
                .setBinding(0)
                .addMatrix4fEntry("quadsTransforms", true)
                .addVector2fEntry("quadsSizes", true)
                .addIntegerEntry("quadsTextures", true)
                .addBooleanEntry("quadsHasTexture", true)
                .addVector3fEntry("quadsFillColors", true)
                .addFloatEntry("quadsOpacities", true)
                .allocate();
    }

    public void prepare() {
        if(this.size() > UniformBuffer.ARRAY_SIZE)
            throw new IllegalStateException("Batch cannot contain more than " + UniformBuffer.ARRAY_SIZE + " models.");

        this.program.use();
        this.program.sendMatrix4f("perspective", this.perspective.getOrthographicView());
    }

    public void fillBuffer() {
        IntStream.range(0, this.size()).parallel().forEach(i -> {
            VisualContainer visualContainer = this.get(i);

            if(this.perspective.contains(visualContainer) && visualContainer.isVisible()) {
                buffer.insertMatrix4fAt("quadsTransforms", visualContainer.getWorldTransformation(), i);
                buffer.insertVector2fAt("quadsSizes", visualContainer.getScale(), i);

                if(visualContainer.getTexture() != null) {
                    buffer.insertIntegerAt("quadsTextures", visualContainer.getTexture().getId(), i);
                    buffer.insertBooleanAt("quadsHasTexture", true, i);
                } else {
                    buffer.insertIntegerAt("quadsTextures", 0, i);
                    buffer.insertBooleanAt("quadsHasTexture", false, i);
                }

                buffer.insertVector3fAt("quadsFillColors", visualContainer.getFillColor(), i);
                buffer.insertFloatAt("quadsOpacities", visualContainer.getOpacity(), i);
            }
        });
    }

    public void draw(float depth) {
        this.fillBuffer();

        this.program.use();
        this.program.sendUniformBuffer(this.buffer);
        this.program.sendFloat("depth", depth);

        if(this.perspective.isDirty()) {
            this.program.sendMatrix4f("perspective", this.perspective.getOrthographicView());
            this.program.sendVector4f("viewport", this.perspective.getViewport());
        }

        this.vao.bind();
        this.vao.getIndexBuffer().bind();
        glDrawElementsInstanced(GL_TRIANGLES, this.vao.getIndexBuffer().getCount(), GL_UNSIGNED_INT, 0, this.size());
    }
}

```

Here's my vertex shader:

```
#version 460 core

const int MAX_QUADS_PER_SCENE = _[MAX_QUADS];

uniform mat4 perspective;
uniform vec4 viewport;
uniform float depth;

layout (location = 0) in vec3 vertex;
layout (location = 1) in vec2 texCoord;

layout(std140, binding=0) uniform quads {
    mat4 quadsTransforms[MAX_QUADS_PER_SCENE];
    vec2 quadsSizes[MAX_QUADS_PER_SCENE];
    int quadsTextures[MAX_QUADS_PER_SCENE];
    int quadsHasTexture[MAX_QUADS_PER_SCENE];
    vec3 quadsFillColors[MAX_QUADS_PER_SCENE];
    float quadsOpacities[MAX_QUADS_PER_SCENE];
};

out vec2 quadTexCoord;
out vec2 quadSize;
out vec3 quadColor;
out float quadOpacity;

out int textureSampler;
out int hasTexture;

void main() {
    quadTexCoord = texCoord;
    quadSize = quadsSizes[gl_InstanceID];
    textureSampler = quadsTextures[gl_InstanceID];
    quadColor = quadsFillColors[gl_InstanceID];
    quadOpacity = quadsOpacities[gl_InstanceID];

    float ndcDepth = (depth / 500) - 1;
    mat4 quadMatrice = quadsTransforms[gl_InstanceID];
    gl_Position = perspective * quadMatrice * vec4(vertex.xy, ndcDepth, 1.0);
}

```

And here's my fragment shader:

```
#version 460 core

out vec4 outColor;

in vec2 quadTexCoord;
in vec2 quadSize;
in vec3 quadColor;
in float quadOpacity;

in flat int textureSampler;
in flat int hasTexture;

void main() {
    if(hasTexture == 1) {
        vec4 texturePixelColor = texture(sampler2D(textureSampler), quadTexCoord);
        texturePixelColor.w = min(texturePixelColor.w, quadOpacity);
        outColor = texturePixelColor;
    } else {
        outColor = vec4(quadColor, quadOpacity);
    }
}

```

As you can see for the shader, I tried sending the texture id directly and using it as a sampler to no avail. To my understanding Sampler2Ds needs to be dynamic uniforms which means I can only send one with my draw call. Of course I could use an atlas here and change the texture coordinates. I'm wondering if this is possible using multiple images.

Thank you.

# Answer
> 0 votes
I have opted for simply utilising the many texture slots provided by OpenGL. When I load a texture I set its ID into an array where the index is the sampler index. In my fragment shader, the sampler2D is now an array.

Texture code:

```
public Texture(String filePath) {
        this.path = "src/main/resources/texture/" + filePath;
        this.id = glGenTextures();
        registry[currentIndex++] = this.id;

        this.bind();
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);  // Horizontal Wrap
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Vertical Wrap

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // Stretch algorithm
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // Shrink algorithm

        int[] width = new int[1];
        int[] height = new int[1];
        int[] channels = new int[1];
        ByteBuffer image = stbi_load(this.path, width, height, channels, 0);

        if(image != null) {
            this.width = width[0];
            this.height = height[0];
            this.channels = channels[0] == 3 ? GL_RGB : GL_RGBA;
            System.out.println(this.width + ", " + this.height);

            glTexImage2D(GL_TEXTURE_2D, 0, this.channels, this.width, this.height,
                    0, this.channels, GL_UNSIGNED_BYTE, image);
            stbi_image_free(image);
        }
    }

```

Then I bind the entries where the id \> -1 (i initialise the registry array to -1 everywhere) like so:

```
for(int i = 0; i < Texture.registry.length; i++) {
            if(Texture.registry[i] > -1) {
                glActiveTexture(GL_TEXTURE0 + i);
                glBindTexture(GL_TEXTURE_2D, Texture.registry[i]);
                this.program.sendTexture("textureSamplers", i); // Transform the string to add [i] at the end
            }
        }

```

And finally in my fragment shader I pass a texture index for that entity:

```
#version 460 core

out vec4 outColor;

in vec2 quadTexCoord;
in vec2 quadSize;
in vec3 quadColor;
in float quadOpacity;

uniform sampler2D textureSamplers[32];
in flat int textureIndex;

void main() {
    if(textureIndex >= 0) {
        vec4 texturePixelColor = texture(textureSamplers[textureIndex], quadTexCoord);
        texturePixelColor.w = min(texturePixelColor.w, quadOpacity);
        outColor = texturePixelColor;
    } else {
        outColor = vec4(quadColor, quadOpacity);
    }
}

```

Unsure if this is the best/right way but it fixes my problem. Of course I will never use all 32 slots and since the amount of slots changes based on hardware, I might make the size of the array dynamic by expanding it before compiling.

---
Tags: shaders, textures, rendering, glsl
---


# Question
Title: What kind/type was the 3D terrain editor of Warcraft 3's World Editor? How it worked?
Warcraft III (WC3) had a lovely map editor that allowed for a whole lot of stuff, yes *(this was the best result I could squeeze out of Google)*, but what to me stood out the most and what I played with the most, really, was its powerful yet easy to work with Terrain Editor.

It felt like playing with LEGO's... but better in some ways.

I remember even the first Starcraft had something similar, but of course, not as powerful as WC3, given how WC3 was Blizzard's first full-blown 3D rendered game.

To emphasize:

* It operated on a grid, yes, like a tilemap
* But it had varying heights (3D)
* It seemed to procedurally generate seams/transitions/cliffs/textures whatnot
* It also allowed for ramps
* Building with it was super simple and intuitive
* No janky heightmaps of varying heights (at least not directly, looking at you Unity)
* No CSG either? (Unreal / Source)
* No brush sensitivity
* You could only select given "biomes" to work with, but everything would fit to theme
* And boy was it performant... doesn't feel like every "cell" was a separate entity.
* It kind of felt voxely, but was it? Marching Cubes with low resolution?
* AI worked flawlessly atop of it (NavMeshes?)

If we were to classify it... what kind/type does it fall into? Any other editors operate like that? And then, how would one approach to build something like that?

# Answer
> how would one approach to build something like that?

First of all, you need a grid. And there is extra data per vertex - not per cell - of the grid.

Notably:

* How High the terrain is (this is a float). Thus, it is likely there is height map texture, or alternatively it is baked on the vertex position.
* To which Layer it belongs (this is an integer). While you could use the height to make smooth-ish hills, you would change the layer to make cliffs. And the cliff faces have additional geometry, depending on the type you pick. And, by the way: a ramp is a kind of cliff.
* Which kind of Tile it is. Apparently you draw like a tile map, with auto-tiling. This suggest we can use a render step to make a 2D tilemap, which would be the texture for the terrain (but not for the cliff additional geometry).

For water you probably need shallow and deep water masks, or a depth map (I mean, like a height map but for how deep the water is). Notably for shallow water we can make the terrain raise above the water level by changing its elevation.

The elevation of a vertex would be its height form the height map, plus the layer multiplied by the elevation of a cliff.

Since I'm saying to use addition custom geometry to make the cliff faces, that would also hide their change in elevation. This way the geometry for a ramp is: none. *Another idea would be able to mark vertex to be discarded.*

Picking the geometry build the cliff faces could work similar to auto-tiling, or marching squares. *We certainly don't need something as complex as marching cubes*.

I want to note that the game is able to animate the high of vertex during game play, and it would also move the cliffs. *This is something a vertex shader could do.*

Also note that the editor must be maintaining a navigation mesh. For example if you pick a cliff it will disconnect the navigation, unless it is a ramp. Also, I believe placing bridges would have had to update the navigation mesh.

And of course there are entities placed on the map such as trees, building, etc... Plus we could vary entities according to the terrain where you are placing them.

---

And your other questions:

> If we were to classify it... what kind/type does it fall into?

It is a map editor. And a map is not just a terrain. There is a combination of techniques applied to make it. *It is easier to think out side any proverbial box if you don't put things in boxes to begin with.*

> Any other editors operate like that?

I'm unaware of any non blizzard one. It seems they evolved their solution along the development of multiple games.
> 1 votes

---
Tags: architecture, procedural-generation, terrain, terrain-rendering, world-editor
---


# Question
Title: OverlapCircle detects collider farther away than the provided radius
Small Context.

Moon - `Projectile`.

Eye - `Magnet` that rotates on z axis and causes projectile to rotate too.

On the first screen you can see a projectile and it is positioned as -1 on y axis. Parent position is 0,0,0.

The flow is next. Pressing mouse button launches projectile in direction that it is facing and if it hits target it is launched back. On the second screen you can see a code for `Magnet` that checks for a colliders in radius, if it found it than it means that it found the `Projectile`

Magnet.Script

```
private void Update() {
    StickProjectileToMagnetOnReturn();
}

private void StickProjectileToMagnetOnReturn() {
    if (ProjectileState.RETURNING == projectile.GetProjectileState()) {
        Collider2D collider = Physics2D.OverlapCircle(new Vector2(transform.position.x, transform.position.y), 1);
        if (collider != null) {
            projectile.StopProjectile();
            projectile.SetProjectileState(ProjectileState.ROTATING);

            rotationRoutine = StartCoroutine(Rotate());

            GameManager.Instance.SetGameState(GameState.GENERATE_TARGETS);
        }
    }
}

```

Problem: In unity editor I positioned my projectile on 0,-1,0 coordinates relative to parent. In code when I perform OverlapCircle in 1F radius it finds my `Projectile` when it is positioned on (0, -1.2,0) which is larger than (0, -1, 0) and results in `Projectile` being position further from `Magnet` than on start of the game. I thought that new position og the `Projectile` should be (0, -1, 0) too or something like (0.5, 0.5, 0)

Projectile.Script

```
public void LaunchProjectile() {
    Vector3 position = transform.position;

    float v = Vector3.Angle(rotator.transform.position, position);

    float sin = Mathf.Sin(v);
    float cos = Mathf.Cos(v);

    coroutine = StartCoroutine(LaunchInDirection(new Vector3(sin, cos, transform.position.z)));
}

private IEnumerator LaunchInDirection(Vector3 direction) {
    particleSystem.Play();

    while(true) {
        yield return waitForFixedUpdate;
        Vector3 translation = direction * speed * Time.deltaTime;
        transform.Translate(translation);
    }
}

public void StopProjectile() {
    rigidbody.velocity = Vector2.zero;
    rigidbody.angularVelocity = 0;

    transform.localEulerAngles = Vector3.zero;

    StopCoroutine(coroutine);

    particleSystem.Stop();
}

```

Target.Script

```
private void OnCollisionEnter2D(Collision2D collision) {
    if (isActive) {
        particleSystem.Play();
        LaunchProjectileBack(collision);
        SetNotActive();

        targetGroup.OnTargetHit();
    } else {
        targetGroup.OnWrongTargetHit();
    }
}

private static void LaunchProjectileBack(Collision2D collision) {
    // here i just redirect my projectile back
    collision.transform.localEulerAngles = new Vector3(0, 0, 180);

    Projectile projectile = collision.transform.GetComponent<Projectile>();
    projectile.SetProjectileState(ProjectileState.RETURNING);
}

```

# Answer
> 2 votes
The method `Physics2D.OverlapCircle(new Vector2(transform.position.x, transform.position.y), 1);` will return true if there is a collider that *overlaps* a circle of radius 1. That means the distance you will end up with is the radius of the circle plus the radius of the detected collider. I suspect that the reason why you end up at `-1.2` instead of `-1.0` is because the collider of the magnet has a radius of 0.2 units.

And there is another problem here: You are detecting *any* collider, not just the one of the magnet. Which could become a source of lots of bugs when your game gets more complex.

But there is a much more reliable and efficient way to check the distance between the positions of two game objects if you have references to both of them in the script. So if you add a variable `GameObject magnet` to the projectile and make it reference the magnet, then you can do this:

```
Vector2 myPosition = transform.position;
Vector2 otherPosition = magnet.transform.position;
if(Vector2.Distance(myPosition, otherPosition) <= 1.0f) {
    // destination reached
}

```

However, keep in mind that you don't know how far the object moved between the previous and the last frame. So in most cases it will end up slightly closer to 1.0f. So it's a good idea to set its position explicitly to where you want it to be:

```
Vector2 myPosition = transform.position;
Vector2 otherPosition = magnet.transform.position;
if(Vector2.Distance(myPosition, otherPosition) <= 1.0f) {
    transform.localPosition = new Vector3(0, -1, 0);
    // destination reached
}

```

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


# Question
Title: Triggering Enhanced Input Actions via inputs with modifier keys (Shift/Alt/Ctrl) in UE5
This question refers to the use of enhanced input in Unreal Engine 5. Whenever I say "modifier", I refer to modifier keys such as Shift, Alt, and Ctrl (rather than the Input Modifers such as Dead Zone and Aim Assist).

I am trying to bind actions to mouse and keyboard inputs that require the user to hold a modifier key, e.g. the following ones, which one would typically find in RTS type games:

* `Left click without modifiers` to select a unit
* `Left click + Shift` to add to selection
* Keyboard key `1` to select the units in control group #1
* `1 + Ctrl` to define control group #1
* `1 + Shift` to add to control group #1

This can be easily achieved through the deprecated Action Mapping in the Project Settings:

However, I am **looking for a way to achieve the same through the preferred Enhanced Input Actions and Input Mapping Context**. How does that work?

I could probably achieve the desired outcome with a Chorded Action (by defining a helper action for "Shift is Down" and then adding it as Chord Action to the left click. However, not only would I need to do this with the modifier I want, I would even need to add Chord Actions for those *I don't want*: otherwise if shift is down, both "Left click+shift" and "Only left click" will fire. That sounds insane. What am I missing (and why don't I find this in the docs -- this seems like a common use case)?

# Answer
> 4 votes
After doing some more research and implementing a solution that does work for me, I feel confident to be able to answer my own question. Unfortunately, the answer is: It's as cumbersome as already outlined in the question.

* Create Input Actions for Shift, Alt, and Control, and a dedicated Input Mapping that maps the respective left and right keys to these Input Actions. No special Trigger is needed for that.

These platform specific actions actually defeat the purpose of the entire approach, but it gets the job done.
* Always have this Input Mapping added to the Enhanced Input Local Player Subsystem with a sufficiently high priority.
* Create a second input mapping that holds your actual actions. For each action that requires a modifier key, use a `Chorded Action`, and use the Input Actions created above as the `Chord Action`.
* Note that the question contains an unnecessary assumption: It is *not* necessary to enforce *absence* of a modifier key for the action that doesn't require one. For some reason, the more specific action (the one that does specify a Chorded Action) takes precedence over the general one, but I found no documentation about how this works precisely. This makes it a bit less cumbersome than suggested in the question.

An almost identical solution has been posted in the UE Forums and repeated in February 2023, so there's likely no better solution possible at the moment. If a better option will be made available in a future version of Unreal Engine, please post another answer and I'll mark that one as correct.

---
Tags: input, mouse, rts, keyboard, unreal-5
---


# Question
Title: How to get spring effect between two bodies
I'm using Box2D 2.4.1 and trying to get a spring effect between two bodies. No matter how I change frequency or damping ratio with the Distance Joint, I see no effect..

Here's my setup

```
  b2BodyDef body1;
  body1.type = b2_dynamicBody;
  body1.position = b2Vec2(-1, -4);
  body1ptr = bWorld->CreateBody(&body1);

  b2BodyDef body2;
  body2.type = b2_dynamicBody;
  body2.position = b2Vec2(1, -4);
  body2ptr = bWorld->CreateBody(&body2);

  b2CircleShape circleShape;
  circleShape.m_radius = 0.40f;

  b2FixtureDef ballFixture;
  ballFixture.restitution = 0.8f;
  ballFixture.density = 5.f;
  ballFixture.shape = &circleShape;

  b2FixtureDef ballFixture2;
  ballFixture2.restitution = 0.8f;
  ballFixture2.density = 5.f;
  ballFixture2.shape = &circleShape;

  body1ptr->CreateFixture(&ballFixture);
  body2ptr->CreateFixture(&ballFixture2);

  float frequencyHz = 4.0f; // "Speed of oscillation" 1-5 typical
  float dampingRatio = 0.1f; // typical 0-1

  b2DistanceJointDef distDef;

  distDef2.Initialize( body1ptr, body2ptr, body1ptr->GetPosition(), body2ptr->GetPosition() );

  b2LinearStiffness(distDef2.stiffness, distDef2.damping, frequencyHz, dampingRatio, distDef2.bodyA, distDef2.bodyB);

  b2DistanceJoint* joint2 = (b2DistanceJoint*)bWorld->CreateJoint(&distDef2);

```

Box2D updates at fixed steps. Here is a gif showing what I have now:

I don't know if I'm thinking of this whole thing wrong, but I was expecting it to compress as the little dude was applying pressure against the wall.

What am I doing wrong? Or thinking wrong?

# Answer
> 1 votes
Looking at the Release notes for Box2d 2.4.1, it states:

> BREAKING: distance joint 0 stiffness now means the spring is turned off \>rather than making the joint rigid.

> BREAKING: distance joint minimum and maximum must be set correctly to get old behavior.

So setting minLength and maxLength of the joint did make it act more like the way i wanted. In my case, i set these parameters between distDef2.Initialize and b2LinearStiffness.

```
distDef.minLength = 0.1f;
distDef.maxLength = 4.f;

```

I did also change frequencyHz to 0.5f.

---
Tags: physics, box2d, spring
---


# Question
Title: What is the keyboard shortcut to access the Remote and Local tabs?
What shortcut can I use to activate the Remote and Local Tab so that it can be displayed for me?

I can' t activate these tabs.

# Answer
There aren't shortcuts to switch between Remote and Local tabs.

About activating them: the Remote tab is only available while the game is running in the debugger. What you have in the Scene dock while the game is not running is the Local tab.
> 1 votes

---
Tags: workflow, godot-3
---


# Question
Title: How to store localized text data in Unity?
I need to create a lot of read-only text data. As far as I know storing a lot of data directly in the script is not good, so I need to create a separate json file with ready-made data to load in the game.

But what if this data should be in multiple languages, that's where the question arises. Should I store in the json file the localization table's keys with translations to access the desired field?

# Answer
> 2 votes
Unity has built-in support for storing localization data. Import the localization package from Unity's package manager, and check out the Quick Start Guide.

It supports localization for `TextMeshPro`, `RawImage`, and `AudioSource`.

Populate your localization database, then right-click on the localizable component, and select Localize. Then you can choose the localization asset.

If you need more custom localization, you can use Smart Strings. You can also use Smart Strings to serialize/deserialize classes/structs, although I suspect you took a wrong turn somewhere if you need to do that.

---
Tags: unity, data, file, json, localization
---


# Question
Title: Orbit and control distance from object in 3D
I'm stumped on a key part of my game project, built in Godot 3.5.2.

I'm trying to have my player character be able to rotate around an object using A and D, as well as get closer and farther from it along a line using W and S. I've exhausted my personal knowledge on Godot trying to figure this out and I'll post my code below.

```
var move_base = .05

var move_dist = (Input.get_action_strength("move_down") - Input.get_action_strength("move_up")) * move_base
var move_orb = (Input.get_action_strength("move_right") - Input.get_action_strength("move_left")) * move_base

# Rotation variables
# Subtract origin point from target's position
var pivot_radius = Vector3.ZERO - target.global_translation

var pivot_transform = Transform(transform.basis, target.global_translation)

# Rotate around target
transform = pivot_transform.rotated(Vector3(0, 1, 0), move_orb).translated(pivot_radius)

```

I believe that if I can modify pivot radius to allow me to move along the radius it would work perfectly fine, but I'm bad when it comes to geometry and math.

I've also attached a picture to clarify what I'm trying to achieve if it helps at all. Thank you in advance!

# Answer
> 0 votes
First of all, work in global coordinates.

You are using `target.global_translation` which is global coordinates, but you are setting `transform` which isn't, instead it is relative to the parent node.

---

*I will not go for a clever solution, but for one that is easy to follow.*

We want to rotate the position of the player character `global_transform.origin` around the position of the distant object `target.global_translation.origin`.

So the vector we want to rotate is:

```
var vector_to_rotate := global_transform.origin - target.global_translation.origin

```

To rotate it we are to need a rotation axis, you are using `Vector3(0, 1, 0)`, so I will use `Vector3.UP`. And I believe `move_orb` is the rotation angle. *You might want to express it in terms of an angular velocity and use `delta` so it is frame rate independent, but I digress.*

We rotate it like this:

```
var rotated_vector := vector_to_rotate.rotate(Vector3.UP, move_orb)

```

So we can compute the new position:

```
global_transform.origin = target.global_transform.origin + rotated_vector

```

---

Ah, but you want to control the distance too! So, instead we will get direction and distance. For example, like this:

```
var vector := global_transform.origin - target.global_translation.origin
var direction := vector.normalized()
var distance := vector.length()

```

*You could also use `direction_to` and `distance_to`. Or you could normalize by dividing the vector over its length (but careful with division by zero).*

Then we rotate the `direction`:

```
direction = direction.rotate(Vector3.UP, move_orb)

```

Change the `distance`:

```
distance += move_dist

```

*Again, you could define a velocity and use `delta`, but you do you.*

And we get the new position:

```
global_transform.origin = target.global_transform.origin + direction * distance

```

---

You can have the player character facing the target with a `look_at`:

```
look_at(target.global_transform.origin, Vector3.UP)

```

And that would account for the rotation.

---
Tags: 3d, rotation, orbit, godot-3
---


title: Upgrading Godot project

text:
# Question
Title: Upgrading Godot project
Can I open a game that I made in Godot 3.1 in a later version (3.2 and higher) and get output from it with that higher version?

# Answer
> 1 votes
Yes.

You can upgrade your project from 3.0 up to whatever 3.x, and it should work - in most cases.

The advice is make sure you have a backup before doing so. *If you are working with version control, this is not an issue.* The reason why a backup is advised is because downgrading your project is not guaranteed... Mainly because a project for a newer version might be using features not available in older versions.

The incompatibilities you might find while upgrading are mostly behavior changes, but there were some removed features (although there were kept at a minimum and were mostly rarely used features). *This is why I said "in most cases" earlier*.

The bigger incompatibilities within the 3.x versions are for the version 3.2.2 that changed the Android plugin system (so if you rely on old Android plugins that weren't upgraded for the new system you will be in trouble). And also for 3.2.3 that changed the C# project format (you should be able to regenerate the project file if necessary).

Godot is adhering to semantic versioning to a healthy degree. So, as you would expect, a change in the major version version number signifies that the development team took the liberty to break compatibility. In fact, upgrading from 3.x to 4.x is not safe. There is an upgrade system (Godot 4.x will ask you if you want to upgrade a Godot 3.x project the first time you try to open it), it is not perfect, and you will have to spend time making sure your project works and works correctly in Godot 4.x. Furthermore, if you need to go back to Godot 3.x you are on your own (so, again, make sure to have a backup).

---

**Addendum** To upgrade a project to a new version of Godot, you:

* Download the new version of Godot
* Open the new version of Godot
* Open the project in the new version of Godot (if it is a major version, you might have to scan the project folder for Godot to detect it)
* If Godot needs to modify the project to be able to open it, it will ask you if you want to proceed before doing any changes.

That's it.

---
Tags: godot-3
---


title: How to use ads in Godot 3.1?

text:
# Question
Title: How to use ads in Godot 3.1?
I want to put ads in my game built using Godot 3.1, but I can't find the plugin and source for Google AdMob.

How can I incorporate ads?

# Answer
The Android plugin system has been through some changes. Some community maintained plugins have not being keeping up, and others did not bother to back port to earlier versions. So you need to pay attention to which version of Godot the plugin supports, and follow their instructions to set it up.

In fact, for Godot 3.1 you would likely find Android plugins in the form of modules. Which require to compile custom export templates for Android. You need to follow the documentation for your version of Godot (for Godot 3.1 it is this one: compiling).

*I want to point you to a similar question I answered over StackOverflow: GODOT- how to deal with godot source file, custom modules , and how to import projects?.*

For what I can find, this module supports Godot 3.1: kloder-games / godot-admob. Barring that, try the one it is forked from: Mavhod / GodotAdmob.

You might run into other kind of compatibility problem, because these are modules, and you need the correct SDK to build them. Plus, you probably want to keep up with newer Android SDKs (Why target newer SDKs?).

I believe the change in the Android plugin system is for the better, and that the risk of upgrading your project is marginal. So, I recommend to try to upgrade your project (and again I remind you to make sure you have a backup, just in case).
> 1 votes

---
Tags: advertisements, admob, godot-3
---


# Question
Title: How to swap skinned meshes for a customizable character in Godot?
Using Godot 3.5.1, I need to make a system that switches armors/helmets/hair styles/weapons and so on.

I've seen a single tutorial for how this is done in 3D games in Godot, and apparently it is not the best system, it's just something some guy who didn't knew how to do it came up with. It is very hard to set up and very inefficient, as it makes the game way heavier than it should be.

I already have animations and a skeleton. What is the process now to make sure that all pieces can be swapped and work with the same skeleton in Godot? I've already tried swapping objects that follow no animations and they work just fine, but what about things that bend like fingers or legs?

# Answer
The easier path is probably to export a single model with all the pieces, so you only need to toggle their visibility (or dynamically remove parts) in runtime.

*The problem of that is that we might be talking of a single file, and would grow hard to maintain (version control), and will have an impact in your load times.*

---

Alternatively, you would export multiple models...

For a model to follow a mesh in Godot:

1. You need a `Mesh` that has bone weights (weight paint). You cannot set these from Godot, so you need a model exported with them, and take the `Mesh` from it.
2. Set a `MeshInstance` with the `Mesh`. *It is usually set as a child of the `Skeleton` so applying a transformation to the `Skeleton` also applies it to the `MeshInstance`.*
3. You needs to have a `Skin` set in the `skin` property of `MeshInstance`. The `Skin` has the references of the bone indexes, names, and rest position. *You want these to match between interchangeable parts.*
4. You needs to have the `Skeleton` set in the `skeleton` property of the `MeshInstance`. *By default the `skeleton` property will be set to the parent of the `MeshInstance`.*
5. The animations will move the `Skeleton` itself, not the `MeshInstance`, and `MeshInstance` will follow the movement of the `Skeleton`.

So, you would not change your `Skeleton` or `AnimationPlayer`, thus must stay the same. You would only swap the `MeshInstance`s that are children of the `Skeleton`, and as long as they satisfy the requirements, they should work.

To get your interchangeable pieces into Godot you would export models with the same skeleton but with different parts. You would need to load the models and assemble the parts via script.

---

*I also want to mention that if you want to have weapons or other pieces that do not deform but must follow the animation you can use `BoneAttachment`s.*
> 1 votes

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


# Question
Title: Running multiple game servers on single host
I want to use a vps/dedicated server for game hosting. I expect hosting a lot of servers on that. For the connection, should I assign a unique port for every server or change IPs for every server. And how would these 2 options impact on the game, if I had multiple vps/dedicated servers.

# Answer
> 2 votes
Performance-wise, it doesn't matter. But IPv4 IP addresses are a rare commodity, so you won't get more than one per server unless you pay extra. Not so with IPv6 IP addresses, though.

But if you are the game developer, then why run multiple processes of your gameserver instead of just writing your gameserver in a way that it can handle multiple game session at once by implementing game sessions on the application layer of your network protocol?

# Answer
> 0 votes
If you go the route of multiple servers per machine then you can have you're server bind on 0.0.0.0 & then have each new instance of a server increment a port from your set base by +100. Server 1: 0.0.0.0:7777 Server 2: 0.0.0.0:7877 Server 3: 0.0.0.0:7977 ...

For example

---
Tags: server, multithreading
---


# Question
Title: Add a rounded border to a texture with a fragment shader
I am trying to draw a rounded border / outline around a texture. Basically I have two textures doing a transition and the border should look like being part of the textures itself.

I tried different approaches, but the best I could get is a border that is cut off on the top and only the top right corner being rounded.

The result looks like this:

I have the feeling I am pretty close, but it seems that I am missing something.

Here is my fragment shader code:

```
precision highp float;

uniform vec2 uImageActiveSize;
uniform vec2 uImageNextSize;
uniform vec2 uPlaneSize;
uniform vec2 uDirection;
uniform float uTransitionProgress;
uniform float uMaskProgress;

uniform float uBorderThickness;
uniform float uBorderRadius;
uniform vec4 uBorderColor;

uniform sampler2D tMapActive;
uniform sampler2D tMapNext;

varying vec2 vUv;
varying vec3 vPosition;

vec4 getFromColor(vec2 uv){return texture2D(tMapActive, uv);}
vec4 getToColor(vec2 uv){return texture2D(tMapNext, uv);}

const float smoothness = 0.5;
const vec2 center = vec2(0.5, 0.5);

vec4 transition (vec2 uv) {
  vec2 v = normalize(uDirection);
  v /= abs(v.x) + abs(v.y);
  float d = v.x * center.x + v.y * center.y;
  float m = 1.0 - smoothstep(-smoothness, 0.0, v.x * uv.x + v.y * uv.y - (d - 0.5 - uTransitionProgress * (1.0 + smoothness)));
  return mix(getFromColor((uv - 0.5) * (1.0 - m) + 0.5), getToColor((uv - 0.5) * m + 0.5), m);
}

float calcDistance(vec2 uv) {
    vec2 extend = vec2((uPlaneSize.x), (uPlaneSize.y));
    vec2 coords = abs(uv) * (extend + uBorderRadius);
    vec2 delta = max(coords - extend, 0.);
    return length(delta);
}

void main() {

  vec2 ratio = vec2(
    min((uPlaneSize.x / uPlaneSize.y) / (uImageActiveSize.x / uImageActiveSize.y), 1.0),
    min((uPlaneSize.y / uPlaneSize.x) / (uImageActiveSize.y / uImageActiveSize.x), 1.0)
  );

  vec2 uv = vec2(
    vUv.x * ratio.x + (1.0 - ratio.x) * 0.5,
    vUv.y * ratio.y + (1.0 - ratio.y) * 0.5
  );

  vec2 ratio2 = vec2(
    min((uPlaneSize.x / uPlaneSize.y) / (uImageNextSize.x / uImageNextSize.y), 1.0),
    min((uPlaneSize.y / uPlaneSize.x) / (uImageNextSize.y / uImageNextSize.x), 1.0)
  );

  vec2 uv2 = vec2(
    vUv.x * ratio2.x + (1.0 - ratio2.x) * 0.5,
    vUv.y * ratio2.y + (1.0 - ratio2.y) * 0.5
  );

  vec2 uvMix = mix(uv, uv2, -uTransitionProgress);

  float dist = calcDistance(vUv);
  if (dist > uBorderRadius) discard;

  float alpha = ( vPosition.y + uMaskProgress ) > 0.5 ? 0.0 : 1.0;

  float aspect = uPlaneSize.y / uPlaneSize.x;
  float maxX = 1.0 - uBorderThickness;
  float minX = uBorderThickness;
  float maxY = maxX / aspect;
  float minY = minX / aspect;

  if (vUv.x < maxX && vUv.x > minX &&
      vUv.y < maxY && vUv.y > minY) {
    gl_FragColor = transition(uvMix);
  } else {
    gl_FragColor = vec4(1.,0.,0.,1.);
  }

  gl_FragColor.a *= alpha;
}

```

# Answer
You have:

```
float calcDistance(vec2 uv) {
    vec2 extend = vec2((uPlaneSize.x), (uPlaneSize.y));
    vec2 coords = abs(uv) * (extend + uBorderRadius);
    vec2 delta = max(coords - extend, 0.);
    return length(delta);
}

```

This would do what you want if texture UV coordinates had a range of -1 to 1 — then all four corners would have coordinates of ±1 and get rounded. But they actually have a range of 0 to 1, so the only corner that is rounded is the one that *does* have coordinates of (1, 1), the top right.

You can fix this by rescaling the coordinates so they *are* symmetric that way:

```
float calcDistance(vec2 uv) {
    // Rescale UV to be -1 to 1
    vec2 positionInQuadrant = abs(uv * 2.0 - 1.0);

    vec2 extend = uPlaneSize;
    vec2 coords = positionInQuadrant * (extend + uBorderRadius);
    vec2 delta = max(coords - extend, 0.);
    return length(delta);
}

```

Note that because this stretches the coordinates to double the range, you will have to compensate for that by changing uPlaneSize too.

```
float calcDistance(vec2 uv) {
    // Rescale UV to be -1 to 1
    vec2 positionInQuadrant = abs(uv * 2.0 - 1.0);  // key change
    // Rescale uPlaneSize to compensate
    vec2 extend = uPlaneSize / 2.0;

    vec2 coords = positionInQuadrant * (extend + uBorderRadius);
    vec2 delta = max(coords - extend, 0.);
    return length(delta);
}

```

I tested this out by running the following shader in Shadertoy:

```
const float uBorderRadius = 20.0;

float calcDistance(vec2 uv) {
    vec2 positionInQuadrant = abs(uv * 2.0 - 1.0);
    vec2 extend = vec2(iResolution) / 2.0;
    vec2 coords = positionInQuadrant * (extend + uBorderRadius);
    vec2 delta = max(coords - extend, 0.);
    return length(delta);
}

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 uv = fragCoord/iResolution.xy;

    float dist = calcDistance(uv);
    if (dist > uBorderRadius) {
        fragColor = vec4(0.0, 0.0, 0.0, 1.0);
    } else if (dist > 0.0) {
        fragColor = vec4(1.0, 0.0, 0.0, 1.0);
    } else {
        fragColor = vec4(0.0, 0.5, 1.0 ,1.0);
    }
}

```
> 0 votes

---
Tags: shaders, webgl
---


# Question
Title: Singleton call twice when I switch to another scene and return back
I'm working on a Unity project where I have a Singleton class, `XPmanager`, which is responsible for managing XP data across multiple scenes. I'm using the `DontDestroyOnLoad` method to make sure the `XPmanager` instance is preserved when switching between scenes.

However, I've noticed that when I switch to another scene and then return back to the main scene, the `Awake()` method of my `XPmanager` is called twice, and the Instance IDs are different, indicating that a new instance is being created. This results in the loss of the XP data.

```
public class XPmanager : MonoBehaviour
{
    public static XPmanager singleton;

    // Other fields ...

    private void Awake()
    {
        if (singleton == null)
        {
            singleton = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }

        // ...
    }

    // Other methods ...
}

```

I've checked that there's only one instance of the `XPmanager` in my project. Despite using `DontDestroyOnLoad`, the `Awake()` method is called again with a different Instance ID when I switch back to the main scene.

Why is this happening, and how can I ensure that only a single instance of the `XPmanager` is preserved across scene changes?

# Answer
`DontDestroyOnLoad` only works for root GameObjects or components on root GameObjects.

I set all my singleton managers as children of an emptygameobject and doing so caused my problem.
> 2 votes

---
Tags: unity
---


# Question
Title: Where can I find a game development team that is willing to accept a 2D artist with no experience in game development?
I'm a book illustrator, but I want to try my hand at game development. I have experience working with clients as a book illustrator, but have never worked on a game development team before. Where and how can I find a game development team?

# Answer
A good way to gain some experience in working is a game development team without the pressure of having to deliver commercially viable work is to participate in **game jams**.

Game jams are game development "competitions" where solo developers or small teams receive a prompt and are then asked to create a game that loosely matches the prompt in a relatively short time window (usually between a weekend and a couple weeks). I put "competition" in quotes, because although game jams are usually framed as a competition, and there is usually either a jury or a voting system to decide which game is "the winner" of the game jam, they really don't feel very competitive. For most people it's really more about collaboration, networking, experimentation and being creative than it is about winning. And it's not uncommon at all to have a lot of participants who are still beginners at game development, so you usually don't need to be afraid of not being good enough for a game jam either.

My experience with game jams is that there is usually an overabundance of programmers but a lack of artists. So you will probably not have trouble to find a team. How do you find a team for a game jam? Many game jams have discord servers specifically for that purpose.

For a calendar of upcomming online game jams, check out this calendar on itch.io.

---

Another option is to join a group that wants to create a more ambitious long-term project as a hobby. That's actually how I made my first experience with working as a member of a game development team. I contributed to the development of an open source game. One place where people go to recruit people for projects like that is the subreddit r/INAT.
> 4 votes

---
Tags: game-industry, career, jobs
---


title: How do pick up nearby items only?

text:
# Question
Title: How do pick up nearby items only?
I am trying to build an inventory system to pick up items depending on arrays. But the problem is when I pick up an item, all other items are picked up together. I want to collect each item alone.

THE CODE IS BELOW:

```
public class EquipItem : MonoBehaviour
{
    public GameObject[] Items;
    public Transform []CollectedItems;
    public RawImage[] ItemImages;
    public string [] names;
    public GameObject PicUp_TXT, Drop_TXT;
    bool disabledItem = false;
    public bool ItemCllected;
    float Timer , MaxTimer = 9;
    int counter = 0;

    enum tool { Pilers, ScrewDriver, Wrench, Cutter };

    void Start()
    {
        foreach(GameObject Item in Items)
        {
            Item.GetComponent<Rigidbody>().isKinematic = true;
        }

        foreach(RawImage ItemImage in ItemImages)
        {
           ItemImage.enabled = false;
        }

        PicUp_TXT.SetActive(false);
        Drop_TXT.SetActive(false);
        ItemCllected = false;
        Timer = 0;
    }

    public void EquipedItem()
    {
        for (int i = 0 ; i < CollectedItems.Length; i++)
         {

                    Items[i].GetComponent<Rigidbody>().isKinematic = true;
                    Items[i].transform.position = CollectedItems[i].transform.position;
                    Items[i].transform.rotation = CollectedItems[i].transform.rotation;
                    Items[i].GetComponent<MeshCollider>().enabled = false;
                    Items[i].transform.SetParent(CollectedItems[i]);
                    ItemImages[i].enabled = true;
                }

        ItemCllected = true;
    }

    private void OnTriggerStay(Collider other)
    {
        //Picup Item
        if (other.gameObject.tag == "Tools")
        {
            //if (Item)
                PicUp_TXT.SetActive(true);
            if (Input.GetKey(KeyCode.E))
            {
                EquipedItem();

                //CollectedItem.gameObject.SetActive(false);

            }
            if (ItemCllected)
            {
                PicUp_TXT.SetActive(false);
                Drop_TXT.SetActive(true);
            }
        }

        //Drop Item
        Timer = Timer + Time.deltaTime;

        if (Timer >= MaxTimer)
        {
            Drop_TXT.SetActive(false);
        }

    }

    private void OnTriggerExit(Collider other)
    {
        PicUp_TXT.SetActive(false);
    }
}

```

Any suggestions, please?

# Answer
What you currently do, is that you check if the player is in *any* collider with the tag "Tools", and if so, you use a `for` loop to go through the whole array of possible tools and set each one to the picked up state.

What you need to do is:

1. find out which tool is represented by the collider the player is in
2. use that information to pick the right tool to pick up

So first, how can we find out which tool is represented by the collider? One solution would be to add a component that contains this information and add it to those objects. Let's call it `ToolPickup`. All this component does is hold the information which tool is controlled by this collider. And because you are using arrays to address the tools, we can use the array index for that:

```
public class ToolPickup : MonoBehaviour {
    public int toolIndex;
}

```

Attach this component to each "tool" in the world and set the "Tool Index" in the inspector to the array index of the tool it represents.

Now, in your `OnTriggerStay` method, you can extract that information and pass it to the `EquipedItem` method:

```
if (other.gameObject.tag == "Tools")
{
    /*...*/
     if (Input.GetKey(KeyCode.E))
     {
         var toolPickup = other.GetComponent<ToolPickup>();
         if(toolPickup != null)
         {
             EquipedItem(toolPickup.toolIndex);
         }
     }

```

The `EquipedItem` method needs to be modified to take an array index as a parameter and then only change the state of the tool with that array index:

```
public void EquipedItem(int toolIndex)
{
     Items[toolIndex].GetComponent<Rigidbody>().isKinematic = true;
     Items[toolIndex].transform.position = CollectedItems[toolIndex].transform.position;
     Items[toolIndex].transform.rotation = CollectedItems[toolIndex].transform.rotation;
     Items[toolIndex].GetComponent<MeshCollider>().enabled = false;
     Items[toolIndex].transform.SetParent(CollectedItems[toolIndex]);
     ItemImages[toolIndex].enabled = true;

     ItemCllected = true;
 }

```
> 1 votes

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


# Question
Title: What is the canonical name of the interaction symbol over NPCs heads?
More often than not, 2D and 3D games markup interactive NPCs (and objects) with the exclamation mark symbol. Typically yellow. But of course, sometimes it's an "i" or a small cloud, or other interaction-appropriate symbols of well standing out colors. Could be even vibrant or animated. The goal is clear - to indicate what ~~can~~ should be interacted and what not.

I'm adding such feature to my RTS game and I'm wondering what is this symbol/element usually called?

P.S. Somewhat similar to What is the name for the little numbers that appear over characters' heads when they lose health?

# Answer
## Disclaimer

There is no canonical name as far as I'm aware. So, instead I will provide terms that I hope will be useful for you.

And while I cannot provide a definitive source these terms, I do not claim to have come up with them, instead that I have picked them from assets, tools, and other developers.

So, feel free to take my answer as hearsay. In fact, I invite you to search the terms and decide if you will use them for yourself.

In that order of ideas, I shall point out that "Dialogue Marker" has other meanings aside from the one I give below, including the icon used to indicate that you must press a button to advance a dialogue.

Also, if you search the terms "Quest Marker" will give you mostly icons and models, similarly "Status Marker" will yield status tokens for tabletop games, but for the other look for tools that use them, since they don't yield many visual results.

---

## Overhead Marker vs Quest Marker

The most general term for some visual element floating above the head of a character is **Overhead Icon**, although I prefer **Overhead Marker** because the other related terms are also called **Markers**.

However, even more popular is the term is **Quest Marker**, but they are not limited to be over the head of characters (they might mark places or items too, and might appear in maps or other navigation aids). Also you might want to place other things over the head of characters that are unrelated to quests.

So there is overlap between **Overhead Marker** and **Quest Marker**.

---

## Other kinds of Markers

Aside from **Quest Marker**, these are the related terms that I can find:

* **Overhead Marker**: An icon floating above the head of a character. In general.
* **Status Marker**: visual elements either floating above the head of a character or below its feet, which tells you something about the current status of said character. These also include nameplates (floating text), health bars, status effect icons, and active selection indicators. *And yes, I'm counting The Sim's Plumbob as an example.*
* **Dialogue Marker**: An icon floating above the head of a character, that tells you that the character has something to say. *A common example is an speech balloon icon. Sometimes an information icon (an "i") or interrogation if they give you instructions about an active quest. And some games also have a dedicated icon for shops. Plus the popular exclamation mark for quest givers (which is a **Quest Marker** too).*
* **Interaction Marker**: An icon floating above the head of a character or above an item to indicate that an special interaction is available.
* **Waypoint Marker**: An icon that might appear in maps or other navigation aids, and also on the terrain, to indicate a location for the player to reach. \*Usually an arrow or map pin icon.

So a particular **Dialogue Marker**, **Interaction Marker**, or **Waypoint Marker**, could also be **Quest Marker** if it is indicating something that is part of a quest.
> 14 votes

# Answer
The general category is **context-sensitive user interface**. In Scott Roger's book "Level Up" he calls them **context-sensitive prompts**:

> an icon or symbol that appears when the player is next to an object or character with which it interacts.

The `!` symbol is sometimes referred to as a **pling** in slang (Commonwealth Hackish) and with respect to use in video game UI:

> In massively multiplayer online (MMO) games such as World of Warcraft, an exclamation mark hovering over a character's head is often used to indicate that they are offering a quest for the player to complete.

Scott Rogers also use the term pling stating that they used plings and pling variants as:

> emoticons that told the player when they couldn't do an action as well as when they could
> 9 votes

---
Tags: gui, terminology, ui-design, npc, quests
---


# Question
Title: Factorio style conveyer belts, how to implement multiple speeds?
I've been reading this article by Factorio about optimisation (please read it to understand the context of this question): https://www.factorio.com/blog/post/fff-176

I have implemented this optimisation and it works very well. But if i have different speeds for the belts connected together, now i don't know how to deal with passing the item on to the next belt that has a different speed without having to iterate each item to check the distances between them.

The article doesn't really go into detail how they pass items across to the next belt especially if the speeds differ.

Does any one know how they did it, or have some ideas how to do it?

Note: items are not singular points they have a radius to them so theres a couple of complex problems:

The first item on the first belt might partially overlap the next belt The last item on the second belt might partially overlap the previous belt

Given this it gets kinda confusing how to actually implement this optimisation when belts have different speeds (and they do support different speeds).

# Answer
Apply the optimization to sequences of belts *of the same speed* only. When items reach a belt of a different speed, they leave that belt section and enter a different belt section, just like if they pass through a splitter or junction — you'd need to handle the interactions of items moving between different belts (that may or may not be blocked) in those cases, even if you have no speed differences.

I believe this is what Factorio itself does, based on the `show-transport-lines` debug setting — arrow markers appear at each speed transition.

Of course, this means that players can defeat the optimization, but that's true of just about anything.

You *could* treat fast belts as if they were a visual effect that stretches out a segment of slow belt — changing the ratio of "distance on screen" to "distance on belt" but still calculating the belt the same way — but that would not work for fast-to-slow transitions since items may collide with each other at that point. I wouldn't bother.
> 5 votes

---
Tags: architecture, optimization
---


# Question
Title: OnCollisonEnter2D not triggering despite collision taking place
I have been following a Unity basics tutorial and have run into a problem with trying to bring up the Game Over screen when a collision occurs. The bird (it's a Flappy Bird game) collides with the pipe and the collision occurs but my function doesn't trigger.

Here's my current code:

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

public class birdscript : MonoBehaviour
{
    public Rigidbody2D myRigidBody;
    public float flapStrength = 1;
    public LogicScript logic;

    // Start is called before the first frame update
    void Start()
    {
        logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<LogicScript>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space) == true)
        {
            myRigidBody.velocity = Vector2.up * flapStrength;
        }
    }
    void OnCollisonEnter2D(Collision2D collision)
    {
        Debug.Log("Bird collision detected!");
        logic.gameOver();
    }
}

```

# Answer
> 2 votes
The collision does not happen because you have a spelling mistake in your code. The correct method name is `OnCollisionEnter2D` and not `OnCollisonEnter2D`. Once you fixed that one, the obvious error should be gone.

If it still does not work afterwards, other common mistakes are (credit to DMGregory)

* collider set to isTrigger
* script not on the same object as the Rigidbody component
* rigidbody set to Kinematic

---
Tags: unity
---


# Question
Title: Why does Unity sprite editor reduce the resolution of my sprites?
I have a PNG file (taken from here) with tiles that look like this:

Each tile is 32x32 pixels. I tried to use Unity's Sprite Editor to slice them into individual tiles. Here are the settings I used:

After I clicked "apply", the sprite resolution became much lower - about 8x8:

What did I do wrong? How can I correctly slice the PNG file?

# Answer
When I download your image, it is not 32x256 but 246x1953. If you cut it on 32x32 chunks, it would make small looking images. The preview agrees with that

If you don't want to do the math, use the Grid by Cell count option. If all your other assets are in a 32x32 chunks, you can adjust with the Pixels per Unit to get the sprite to the overall same size.

The second image has a different problem. The size is 32x8192, the default size for images is 2048. Once you change it in the import settings of the sprite, when you go to the slize screen it looks normal again.
> 3 votes

---
Tags: unity, sprites
---


# Question
Title: GLSL - if or #if for conditional sampler read
I have a GLSL ES 3.0 shader and in certain scenario, I want to read from two textures instead of one and do a lerp between them.

However, I am not sure what is a better solution.

Use standard runtime if like:

```
vec4 res = vec4(0);
if (enable2Tex){
   res = mix(texture2d(s1, tx), texture2d(s2, tx), t)
}
else {
   res = texture2d(s1, tx);
}

```

or should I create two versions of the same shader like:

```
vec4 res = vec4(0);

#ifdef ENABLE_2_TEX
   res = mix(texture2d(s1, tx), texture2d(s2, tx), t)
#else
   res = texture2d(s1, tx);
#endif

```

and switch between two shaders in code?

# Answer
> 1 votes
You should create two versions of the same shader.

> Branching based on non-uniform variables means that the GPU must either perform different operations at the same time (and therefore break parallelism), or “flatten the branch” and maintain parallelism by performing the operations for both branches and then discarding one result. Branching based on uniform variables means that the GPU must flatten the branch. Both of these approaches result in reduced GPU performance. For any type of dynamic branching, the GPU must allocate register space for the worst case. If one branch is much more costly than the other, this means that the GPU wastes register space. This can lead to fewer invocations of the shader program in parallel, which reduces performance. In general, if your code branches on uniform values and both branches have roughly similar workloads, then the impact on GPU performance is likely to be small. However, you should always profile your application and consider the advantages and disadvantages case-by-case.
>
> Note: Dynamic branching can also lead to large shader programs, because the code for all conditions is compiled into the same shader program. However, the effect of these larger files on load times and Memory usage is usually less significant than the impact of shader variants.

Source: Unity Documentation

---
Tags: textures, glsl
---


# Question
Title: How would i make two loops for a game engine
I want to structure my program as shown in the first two images, but I don't know how to get make two game loops happening simultaneously. The arrows show the flow of data.

\** I figured that having the engine processing everything from the system in the background, it would make my game run much more smoothly as well as open memory for my game to function since everything coming from the system already be handled.

The game loop would be a normal game loop and the game would only interact with the handlers.

The handlers would take everything from the engine and make it a more easily accessible version. The only handler I know of that needs interact with the engine be graphics, so it be its own circle.

The second loop is the engine, which i want to be processing everything from the system in the background while my game be running. It would have a win32\_platform class--the "circle"--that processes everything from the system and everything leaving the engine is in a platform\_external class--the tall ellipse

I want to avoid multithreading since I read somewhere that multi-threading is slower than hardcoding a game engine.

# Answer
This is a hard question... Like really hard to answer.

### First suggestion

Purchase a hardcopy of "Game Engine Architecture" by Jason Gregory or a book similar to it. And read it, write down notes, summarize what you learn in a notebook etc... (this is a 1200 page book). You have a lot of learning to do.

### The mechanics

There are multiple ways to do what you want to do from single thread processing to multi-thread (parallel) processing.

I would start by making it a single threaded process. Have a function that performs all required physics engine calculations for a single time step.

Then have a function that performs all required game logic calculations for a single time step.

(Or reverse the order if you want to)

While you are writing both functions, make certain to design them so that you can place either one on top or bottom... Also, also you want to design them so that if they were to to run at the same time it wouldn't break things... Then add in message queues to communicate from your game logic to your physics Engine...

Assuming that all of your step sizes are the same...

```
class PhysicsEngine:
private:
    # reference to a message queue, PhysicsEngine does not own this.
    MessageQueue<>& message_queue
    # reference to game object list. Physics Engine does not own this.
    list<GameObjects>& game_objects
    void step() {
        #! do one time step of calculations for your game engine stuff. read the
        # message_queue and apply it's effects to the relevant game_object.
    }

class GameLogic:
    # reference to a message queue, GameLogic does not own this.
    MessageQueue<>& message_queue
    # reference to game object list. GameLogic does not own this.
    list<GameObjects>& game_objects
    void step() {
       #! do one time step of game play logic...
       # Read user input, AI calculations etc..
    }

    void main() {
       for (;;) {
          game_logic.step()
          physics_engine.step()
       }
    }

```

If you do a good enough job separating the game logic and game engine's area of concerns you should be able to split the 2 into a multi threaded environment without any extra work. Make a game logic thread, and a game engine thread. More work can be done to further parallelize the computation, but that starts becoming complicated.. Could put the AI on its own thread... multi thread the physics calculations (Which is by itself a multi person/multi-year million dollar project).
> 1 votes

---
Tags: c++, game-loop
---


# Question
Title: TextMeshPro Page Mode Issue (Readable Books In game)
I'm trying to implement readable books into my game. Much like Morrowind and Skyrim. I have a system that sort of works, but it appears as though there is a bug that is duplicating some page data, and trimming other page data. I've tried to google search for a solution, but can't seem to find one. I'm thinking this is an issue with how the pages are turned, perhaps I am missing something along the path to accomplishing this. Here are two pictures showing off the problem:

And here is the text that it's supposed to be displaying:

> The Legend of the Quick Brown Fox
> There once was a quick brown fox, who nimbly jumped over a lazy dog.
> The lazy dog was not amused, and tried to catch the fox. However, being that the dog was far too fat and lazy to move, the fox managed to escape the clutches of the dog.
> But then, given time, the dog decided to make a change. It started eating healthy, started working out. Waiting for the day when the quick brown fox would return.
> And on a cold day, that's exactly what happened. The quick brown fox came from beyond the forest, and locked eyes on the dog who was seemingly fast asleep.
> Without hesitation, the quick brown fox took off across the field and lept over the dog, only to be immediately snatched out of the air and ripped to shreds by the dog.
> And everyone lived happily ever after. The end.

As you can see from the images, there is some duplicated text on pages 2 and 3, and then some text is missing completely.

Here is the code I'm using to achieve this:

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

using TMPro;

public class BookContents : MonoBehaviour
{
    [TextArea(10, 20)][SerializeField] private string content;
    [Space][SerializeField] private TMP_Text leftSide;
    [SerializeField] private TMP_Text rightSide;
    [Space][SerializeField] private TMP_Text leftPagination;
    [SerializeField] private TMP_Text rightPagination;

    private void OnValidate()
    {
        UpdatePagination();

        if (leftSide.text == content)
        {
            return;
        }

        SetupContent();
    }

    private void Awake()
    {
        SetupContent();
        UpdatePagination();
    }

    private void SetupContent()
    {
        leftSide.text = content;
        rightSide.text = content;
    }

    private void UpdatePagination()
    {
        leftPagination.text = leftSide.pageToDisplay.ToString();
        rightPagination.text = rightSide.pageToDisplay.ToString();
    }

    public void PreviousPage()
    {
        if (leftSide.pageToDisplay < 1)
        {
            leftSide.pageToDisplay = 1;
            return;
        }

        if (leftSide.pageToDisplay - 2 > 1)
        {
            leftSide.pageToDisplay -= 2;
        }
        else
        {
            leftSide.pageToDisplay = 1;
        }
        rightSide.pageToDisplay = leftSide.pageToDisplay + 1;

        UpdatePagination();
    }

    public void NextPage()
    {
        if (rightSide.pageToDisplay >= rightSide.textInfo.pageCount)
        {
            return;
        }

        if (leftSide.pageToDisplay >= leftSide.textInfo.pageCount - 1)
        {
            leftSide.pageToDisplay = leftSide.textInfo.pageCount - 1;
            rightSide.pageToDisplay = leftSide.pageToDisplay + 1;
        }
        else
        {
            leftSide.pageToDisplay += 2;

        }
        rightSide.pageToDisplay = leftSide.pageToDisplay + 1;

        UpdatePagination();
    }
}

```

Here is a picture of the game object setup:

Here is a picture of the TextMeshPro Text object:

I would post the object for the right page, but it's literally the exact same as the left, with the only difference being that it's marked as page number 2 instead of 1.

And finally, Here are the objects and data being assigned to the script.

Can anyone spot why some of the text is duplicated, and why some of it is missing? I have a feeling it's related to the way the page-turning works, but I can't seem to fix it.

# Answer
I figured it out. Naturally, this issue was derived from the fact that I had done something exceedingly stupid. Evidently the TextMeshPro Text objects were not the same size, which led to the discrepancy. After making both text fields the same size, everything works as intended.
> 0 votes

---
Tags: unity-ui, text-mesh-pro
---


# Question
Title: Unity Save System - is there a better way?
I've been trying to understand how best to approach carrying state over between scenes, and how to save/load game state. I've built an isolated project to focus on building out this approach.

You can view the project on GitHub.

Essentially, my approach is to use a singleton `StateCache`, which tracks all state objects, such as the `PlayerState` in my example. When the `PlayerMove` script (and therefore the player object) is destroyed (i.e. when a different scene is loaded), it writes its latest state to the `StateCache`. When clicking the Save button, all state in the cache is written to a JSON file. Finally, when loading the game data, the JSON is parsed into appropriate state types and the `StateCache` is prepopulated with this data.

Some caveats here, though, that make this more complex:

1. To be able to load the state using strong typing, I need to write the actual state object type names into the JSON object.
2. When loading, I load the next scene first and then prepopulate the cache. However, the player reads its state when the scene is loaded (before the cache is populated). If I load the cache before the scene is loaded, then in the example, the player will be destroyed and overwrite the loaded data in the cache (this could be mitigated by loading from a main menu scene where no player exists).
3. Due to #2, I need to run an additional step to find all active instances that have a state, and apply the state from the cache (if it exists).
4. Also, not necessarily a caveat, but adds complexity, I've brought in Zenject for dependency injection to get away from having static instance references.

To try to explain it visually, I've also created this diagram:

This is working in my isolated project. But it feels overly complicated for what seems like a common problem. I'm relatively new to Unity, building a game as a casual hobby, so I'm keen to understand recommended approaches here. Is there a better way? Or is this complexity necessary?

# Answer
Unity does not have a build-in system for saving and loading gamestates, so there is no standard solution for this. Which means that there are as many approaches to gamestate serialization as there are Unity programmers.

The problem I see with your solution, though, is that you write the state of an object to the "StateCache" every time `OnDestroy` is called. Your line of thought is probably that when the current scene gets deconstructed, then the `OnDestroy` method for all the objects will be called, so they all get an opportunity to write their state to the cache.

But there are a couple problems with this.

1. Objects might get destroyed during the scene for all kinds of gameplay or architectual reasons. You probably don't want to serialize them in that case. The opposite, actually.
2. You have no control over the order in which objects get destroyed during scene changes. Which could be a problem if you have objects that depend on other objects for their serialization.
3. You might want to be able to save the game *without* destroying everything in the scene.

So using the OnDestroy method is probably not the best idea.

A better idea might be to have a dedicated method for each GameObject that does the serialization. Then the process for scene transitions or creating a savegame would be:

1. Clear the StateCache
2. Populate the StaeCache from scratch by calling the save-method of each object in the scene
3. Write the savegame file / switch the scene

How do you call the save-method of each object in the scene? Well, did I already mention that there are as many approaches to gamestate serialization as there are Unity programmers?

* You could create an interface `ISaveable` and then give every saveable gameObject a MonoBehavior that implements that interface. You are then able to get all of those via `FindObjectsByType`.
* Or you could do the same thing with an universal `Saveable` MonoBehaviour that finds out what MonoBehaviours on the same gameObject need to be serialized and how. Probably by using some custom `[Attributes]`.
* Or you could use the good old Unity messaging system and use the `BroadcastMessage` method to call every method with a specific name.
* Or you could have a `OnSave` UnityEvent every saveable game-object is subscribed to
* ...and many more.

The same applies to loading. Relying on `Awake()` handling it for each gameObject might turn out to be a mistake if objects spawn or respawn during gameplay. So you should also have a dedicated method for setting up each gameObject based on the data in the StateCache. You will also probably have situations where you don't know how many objects of what type are supposed to be in the scene while you build it. So you are probably going to need spawners that instantiate any number of gameObject based on what's in the StateCache.
> 2 votes

---
Tags: unity, savegame, state, game-state
---


# Question
Title: How do you rotate an object that uses a quaternion to represent orientation in 3D from a 3 vector input with values from a gamepad?
I'm using unity3d to create a six-degree of freedom flying game. The game takes in input from a standard dual-stick gamepad (like the Logitech f310).

In unity each of the gamepad's joystick's axes are stored as a float value range from a negative minimum to a positive maximum. Minimum value when the joystick is pushed all the way down, maximum value when the joystick is pushed all the way up, and zero when the joystick is centered at rest. (see diagram)

This gives me three float values which can then store as a 3 vector for which I want to use to rotate my object.

```
inputVector = new Vector3(Input.GetAxis("Vertical"), Input.GetAxis("Horizontal"), Input.GetAxis("Pitch"));

```

In unity3d a gameobject's rotation/orientation is stored in a quaternion. this is a mathematical structure that can represent rotation in 3d like a 3x3 matrix, but with fewer variables and without being sensitive to small angles, doesn't suffer from gimbal lock like Euler angles, and also rotations represented with it can be combined easily without issue unlike angle-axis representation.

With all that out of the way, I'm trying use my "input" vector (or at least the three separate values for my three joystick axes) to rotate my quaternion so I can have 3D rotational movement without singularities like gimbal lock and such.

I already know that unity has two functions related to this, `Quaterion.Euler()` and `Quaternion.AngleAxis()` but both of these have issues when dealing with 3D rotations, `.Euler()` gives gimbal lock, and `.AngleAxis()` ignores the magnitude of the individual axes being input which I suppose is the reason for no smooth rotations.

I've looked far and wide and not found a solution that fits my bill. Either I'm missing something or maybe I need to do the reverse of a quaternion rotation a point in 3D, but I need assistance.

# Answer
You only need to axis - I'm not sure what the third one is anyway - as rotating an object around two axis will also result in some rotation around the third.

And you can Euler angles to process the input, without worry of gimbal lock, because:

* The orientation of your object would be in Quaternions and will remain in Quaternions regardless of how you process the input. *The same argument would hold if you were working with a basis (3x3 matrix)*.
* The input rotation shall only represent small angles. *The axis should go from -1 to 1. If it does not, then normalize it to make it so.*

The process is as follows:

1. Each frame you take the input of the axis in the range -1 to 1.
2. You interpret them as Euler angles.
3. Convert into a Quaternion or Axis-Angle.
4. Scale the rotation according to the delta time (and thus making the behavior frame rate independent). You might also scale it by a "sensitivity" factor to tweak how fast it rotates. *For a Quaternion, this is an unclamped interpolation from the identity rotation. For the Axis-Angle, this is multiplying the angle.*
5. Then convert the result to Quaternion or basis (3x3 matrix) - *depending on what you are using to represent the orientation of the object*.
6. And compose it with the orientation of the object. *This step is either Quaternion or Matrix multiplication*.

The result is that the object it rotates each frame some amount depending on the input (and the "sensitivity").

If the input is zero (being that the rest point of the joystick, or within its dead zone), there should be no rotation. And further away from the rest point, you should get more rotation (i.e. the object rotates faster).
> 1 votes

---
Tags: unity, mathematics, rotation, vector, quaternion
---


# Question
Title: How can I make sure that money goes to the right player?
I created a tycoon game in Roblox and made it so every 10 seconds (the Val.value means how much money you have), and you begin getting the money as soon as you claim the tycoon. My Problem now is that, for some reason, when you play it in multiplayer, **it gives money to other players but not to the player who's owner of the tycoon**.Please Help. Anyways here's the code:

```
CurrencyName = "Money" --Change "Cash" to whatever the name of your currency will be.
StarterValue = 0

game.Players.PlayerAdded:connect(function(plr)
    local fold = Instance.new("Folder", plr)
    fold.Name = "leaderstats"
    val = Instance.new("IntValue", fold)
    val.Name = CurrencyName
    val.Value = StarterValue
end)

v = script.Parent.Values.OwnerValue
m1 = game.ReplicatedStorage.Mosques.Mosque1
b = script.Parent.b

PayOut = 2
WaitBetweenPayout = 10

script.Parent.Touched:Connect(function(Hit)

    if Hit.Parent:FindFirstChild("Humanoid") and v.Value == nil then

        local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)

        v.Value = Player

        script.Parent.Transparency = 1
        script.Parent.CanCollide = false
        script.Parent.SurfaceGui.TextLabel.Text = tostring(v.Value).."'s Mosque"

        local Repeat = true  --Repeat giving currrency

        while true do
            wait()
            if Repeat ==  true then
                wait(WaitBetweenPayout)
                val.Value = val.Value+PayOut
            end
        end

        b.a.Touched:connect(function(Hit)
            if Hit.Parent:FindFirstChild("Humanoid") then
                local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
                if v.Value == Player and val.Value >= 10 then
                    m1.Mosq.Decorations.Outside.Stairs:Clone()
                    m1.Mosq.Decorations.Outside.Stairs.Parent = workspace.Mosques.mosque1
                    b.a:Destroy()
                    val.Value = val.Value - 10
                    PayOut = PayOut + 2
                    b.b.CanCollide = true
                    b.b.CanTouch = true
                    b.b.Transparency = 0
                    b.b.BillboardGui.Enabled = true
                end
            end
        end)

        b.b.Touched:connect(function(Hit)
            if Hit.Parent:FindFirstChild("Humanoid") then
                local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
                if v.Value == Player and val.Value >= 25 then
                    m1.Mosq.Decorations.Outside.Sign:Clone()
                    m1.Mosq.Decorations.Outside.Sign.Parent = workspace.Mosques.mosque1
                    b.b:Destroy()
                    val.Value = val.Value - 25
                    PayOut = PayOut + 4
                    b.c.CanCollide = true
                    b.c.CanTouch = true
                    b.c.Transparency = 0
                    b.c.BillboardGui.Enabled = true
                end
            end
        end)

        b.c.Touched:connect(function(Hit)
            if Hit.Parent:FindFirstChild("Humanoid") then
                local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
                if v.Value == Player and val.Value >= 45 then
                    m1.Mosq.WallsEtc.Roofnfloor.FloorF:Clone()
                    m1.Mosq.WallsEtc.Roofnfloor.FloorF.Parent = workspace.Mosques.mosque1
                    b.c:Destroy()
                    val.Value = val.Value - 45
                    PayOut = PayOut + 4
                    b.d.CanCollide = true
                    b.d.CanTouch = true
                    b.d.Transparency = 0
                    b.d.BillboardGui.Enabled = true
        b.d.Touched:connect(function(Hit)
            if Hit.Parent:FindFirstChild("Humanoid") then
                local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
                if v.Value == Player and val.Value >= 25 then
                    m1.Mosq.WallsEtc.WallParts.WallPart1:Clone()
                    m1.Mosq.WallsEtc.WallParts.WallPart1.Parent = workspace.Mosques.mosque1
                    b.d:Destroy()
                    val.Value = val.Value - 25
                    PayOut = PayOut + 2
                    b.e.CanCollide = true
                    b.e.CanTouch = true
                    b.e.Transparency = 0
                    b.e.BillboardGui.Enabled = true
                    end
                end
            end)
    b.e.Touched:connect(function(Hit)
            if Hit.Parent:FindFirstChild("Humanoid") then
                local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
                if v.Value == Player and val.Value >= 25 then
                    m1.Mosq.WallsEtc.WallParts.WallPart2:Clone()
                    m1.Mosq.WallsEtc.WallParts.WallPart2.Parent = workspace.Mosques.mosque1
                    b.e:Destroy()
                    val.Value = val.Value - 25
                    PayOut = PayOut + 2
                    b.f.CanCollide = true
                    b.f.CanTouch = true
                    b.f.Transparency = 0
                    b.f.BillboardGui.Enabled = true
                end
            end
        end)
    b.f.Touched:connect(function(Hit)
            if Hit.Parent:FindFirstChild("Humanoid") then
                local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
                if v.Value == Player and val.Value >= 125 then
                    m1.Mosq.WallsEtc.Walls.EtcRoom.Wall1:Clone()
                    m1.Mosq.WallsEtc.Walls.EtcRoom.Wall1.Parent = workspace.Mosques.mosque1
                    b.f:Destroy()
                    val.Value = val.Value - 125
                    PayOut = PayOut + 6

                end
            end
        end)

                end
            end
         end)
        end
    end)

```

# Answer
It appears that this code here:

```
game.Players.PlayerAdded:connect(function(plr)
    local fold = Instance.new("Folder", plr)
    fold.Name = "leaderstats"
    val = Instance.new("IntValue", fold)
    val.Name = CurrencyName
    val.Value = StarterValue
end)

```

sets up a new IntValue representing the money balance for each player it connects to. But it then assigns this to the variable `val`, which is then shared by all players. That means that `val` always refers to the balance of the last player who connected. Which is why later, when you do `val.Value = val.Value+PayOut`, the money doesn't go to the "tycoon" but to another player.

So how do you solve this problem?

First of all, I would rename the variable `val` to something that's more descriptive. Like `tycoonPlayerMoney`. That way this line in the PlayerAdded:connect handler would already look really fishy at first glance:

```
tycoonPlayerMoney = Instance.new("IntValue", fold)

```

I mean why would you change the value that represents the money of the tycoon player with something new every time a new player connects? Does that make sense here? No, it doesn't! See? Proper variable naming makes logical mistakes like that far easier to spot. The variable that temporarily holds the newly created money value for the new player should probably be a variable that is `local` to this function.

Then you need to make sure that `tycoonPlayerMoney` actually points to the money IntValue of the player who is currently "the tycoon". Unfortunately your code doesn't seem to include the part that makes the player "the tycoon" (or if it does, I can't find it due to lack of comments in the code). That code would need to store the personal money value of "the tycoon" in this variable, so you can use it to give money specifically to "the tycoon" later via `tycoonPlayerMoney.Value = tycoonPlayerMoney.Value + PayOut`.

---

Oh, and it also appears that you create a "leaderstats" folder that's parented to each player when they connect. That means that each player has a separate leaderstats folder which doesn't automatically get synced with those of the others. Are you sure you don't want the leadership stats in `ReplicatedStorage` instead so that you have only one global leaderboard that's automatically synced between all players? Or perhaps I am just misunderstanding what "leaderstats" actually means and it is indeed private data specific to each player.
> 1 votes

---
Tags: roblox
---


# Question
Title: Why is the position of my GameObject inaccurate when copying another object's position?
I've been stuck with this nightmare for a while, and it's certainly my perfectionism. What I have is a cannon that fires a shell from an object pool. The order of operations is as follows.

1. The disabled pooled object is SetActive
2. The pooled Object's forward vector is set to match the cannon's forward vector (previously also used rotations)
3. The pooled Object's position is set to the tip of the barrel (previously from another transform that was placed at the tip of the barrel, now done via a field, this caused 0 difference in the issue)
4. The pooled Object's velocity is set based on its now changed forward vector.

After all this is done, the shell is supposed to be perfectly accurate. Instead, the shell appears to come into existence offset from the barrel tip, when a Gizmo given the same transform has no such issue. The shell's trajectory is also incorrect, as the barrel's forward vector and the shell's forward vector deviate before the shell even has its first frame of flight. I have attached a screenshot of the issue, and the hierarchy of objects which shows where the cannon (which gives the shell its position) is.

It should also be noted that, for some reason, this problem is less severe (but still present) when the game is built, and is far worse in editor.

Another very important note is that the pivot point of the shell, and the mesh center, are in fact in the center of the shell. I double checked this by instantiating primitive spheres in the position and that creates an identical result.

Here is a (simplified) version of the code which creates and fires the shell.

Code is applied relative to the hierarchy as follows:

**Player (parent of PlayerVehicle, not pictured)** contains PlayerController

**Player Vehicle** contains a rigidbody

***120mm\_Mid\_Long*** contains CannonBehavior

***Shell (not pictured, no parent in hierarchy)*** contains ShellBasic and ShellPhysics

```
PlayerController : MonoBehaviour
{
    Player player;
    public KeyCode unlockMouse = KeyCode.LeftAlt;

    void Start()
    {
        this.player = GetComponent<Player>();
    }

    void Update()
    {
        isUnlocked = !Input.GetKey(unlockMouse);

        //Input used to drive vehicle is in this section

        if (isUnlocked)
        {
            Cursor.lockState = CursorLockMode.Locked;
            Cursor.visible = false;
            player.turretAim.GetInput(Input.GetAxis("Mouse X") * sensitivity * Time.deltaTime, Input.GetAxis("Mouse Y") * sensitivity * Time.deltaTime);
            player.turretAim.AimTurret();
        }
        //else statement exists, just changes cursor lock state and visibility

        if(Input.GetButton("Fire1")
        {
            player.cannon.TryFireShell();
            //player contains CannonBehavior
        }
    }
}

```

```
public class CannonBehavior : MonoBehaviour
{
    public Vector3 ShellFireOffset => GetShellOffset();

    public void TryFireShell()
    {
        //checks to see if cannon can fire, then gets a shell from the pool
        ShellBasic shellBehavior = shell.GetComponent<ShellBasic>();
        ShellPhysics shellPhys = shellBehavior.simplifiedPhysics;

        shell.SetActive(true);
        shellBehavior.Reset(ShellFireOffset, transform.forward.normalized);
    }

    public Vector3 GetShellOffset()
    {
        //going to use transforms here later
        return this.transform.position + this.transform.forward.normalized * this.fireOffset.z + this.transform.right.normalized * this.fireOffset.x + this.transform.up.normalized * this.fireOffset.y;
    }
}

```

```
public class ShellBasic : MonoBehaviour
{
    public ShellPhysics simplifiedPhysics;

    void Awake()
    {
        this.simplifiedPhysics = this.GetComponent<ShellPhysics>();
    }

    public void Reset(Vector3 position, Vector3 direction)
    {
        this.simplifiedPhysics.FireFromPosition(position, direction, velocity);
    }
}

```

```
public class ShellPhysics : MonoBehaviour
{
    public Vector3 velocity;

    void FixedUpdate()
    {
        this.velocity += Physics.gravity * Time.fixedDeltaTime;
        this.transform.forward = this.velocity.normalized;
        this.transform.position += this.velocity * Time.fixedDeltaTime;
    }

    public void FireFromPosition(Vector3 position, Vector3 direction, float velocity)
    {
        this.transform.forward = direction;
        this.transform.position = position;
        this.velocity = this.transform.forward.normalized * velocity;
    }
}

```

# Answer
**SOLVED** The issue was caused by shells firing on Update, when vehicle physics happened on FixedUpdate. When the shell fired, it was not synced to the vehicle's physics. I fixed the issue by making shells fire on FixedUpdate instead, as technically, shell firing is a physics operation anyways.
> 0 votes

---
Tags: unity, vector, gameobject
---


# Question
Title: How to run libgdx game on Windows or Linux without IDE?
I made test task in company and in requirements there was a point which stated that on the machine where check will take place only JDK of the last version is established.
I have an auto generated LibGdx Gradle project. An i think i need to write an instruction how to run project from the command line on Windows and Linux. Or may be run Jar file. But i don't know how to generate it in Eclipse.
Thank you for any help.

# Answer
> 1 votes
I'm not sure, I understand your question correctly
You will create a runnable .jar in eclipse?

When you use Gradle you can write in terminal: `gradlew desktop:dist`.
Then you find a runnable .jar under `\desktop\build\libs\`

Here are some more links how you can create a runnable .jar from libgdx project: https://stackoverflow.com/questions/16765596/executable-jar-with-eclipse-libgdx

https://help.eclipse.org/luna/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftasks-37.htm

https://support.smartbear.com/alertsite/docs/monitors/web/selenium/export-eclipse-java-project-as-runnable-jar.html

https://stackoverflow.com/questions/25113692/create-executable-jar-file-under-eclipse

Hope it helps

# Answer
> 0 votes
Build the game:

```
./gradlew build

```

Run the game:

```
java -jar -XstartOnFirstThread ./desktop/build/libs/desktop-1.0.jar

```

---
Tags: libgdx
---


# Question
Title: How do I make an object move to a certain location when the player looks at it?
I want to have an eyeball that when the player looks at, it disappears by moving to the side. Like in a horror game. I know how to make the object move to a set location but I don't know how I would make the object do the action when the player looks at it.

Help would be appreciated.

# Answer
"The object the player looks at" is functionally identical with "the object the main camera points at".

So you can just use a `Physics.Raycast` from the camera into the scene, check if the object that is hit by the ray is the one you want, and if so cause it to do a reaction.

This script assumes that it is on the active camera. If you want to put it on a different object, replace `transform` with `Camera.current.transform`. It also assumes that the eyeball has a Collider of appropriate size and shape. This script also assumes that the eyeball has an unique script on it named "YourEyeballScript". Yours is probably named differently, so you need to change the name of the script accordingly. Or if you don't have any unique script on it, you could create an empty one as a marker-component.

```
// do the raycast
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit))
{
    // if we hit an object, check if it is the "Eyeball" by checking
    // if it has the script that is on the eyeball
    YourEyeballScript eyeball;
    if(hit.collider.TryGetComponent<YourEyeballScript>(out eyeball)) {
        // We are looking at the eyeball. Make the eyeball do The Thing!
        eyeball.DoTheThing();
    }
}

```

If the raycast fails to detect the object, then I recommend to read the documentation of Physics.Raycast I linked above. The method has optional parameters that might or might not be required in your case, depending on how your scene is set up and how you are using layers in it.
> 1 votes

---
Tags: unity, c#, game-mechanics, transformation, visibility-determination
---


# Question
Title: Performance issue when particle system occupies most part of the screen
I'm using particle systems to create stars in my space sim project. The star is made off 2 particle systems: star surface (max particles: 500) and corona (max particles: 250), both use the Mobile/Particles/Additive shader, and a sphere mesh with Standard material. And it works fine and looks pretty nice:
But there's one problem: When I get close to the star so it occupies the most part of the screen, fps drops significantly (from 60 to 30-40). This happens in editor and mobile (Samsung A8 2018), didn't test PC standalone build yet but I'm pretty sure the result will be the same. Disabling the sphere mesh doesn't affect the performance. Disabling of one of the particle systems does improve performance. When the camera is relatively far away from the particles, performance is fine. Changing the scale doesn't seem to matter, whether it's a big star with real size radius 10 million units or a small star with radius 1 unit. The problem occurs when the particles occupy the most part of the screen space. Changing the shaders to other available ones does change the result FPS but whatever shader I use the performance drop is still there.

So, the question is: are there some tips, workarounds or something? Or do I have to write a custom shader? Or changing shaders won't help anyway? I'm using built-in render pipeline, by the way. Tried URP and while fps is a bit higher in general, there's still a big drop (to 40-45 fps).

# Answer
DMGregory already gave some quick guidance in his comment, but to expand on his comment in more detail:

**Overdraw** refers to situations where the GPU has to draw to the same pixel multiple times in one frame, a problem typically caused overlapping transparent textures (often sprites) on top of each other.

Overdraw can have a major impact if there are many layers of overdraw or they cover a significant portion of the screen. It's very easy to cause overdraw with a particle system that uses large, overlapping particles. This is why many games suffer from framerate issues when the screen is filled with smoke or other complex particle effects.

Unity has a feature to help you spot overdraw issues: In the scene window, there is a render-mode dropdown just below the word "Scene" which has "Shaded" selected by default. If you expand the dropdown, you can select the "Overdraw" mode.

In this mode, Unity renders objects using a transparent orange material that turns yellow where objects overlap. The way Unity has implemented this is a little gimmicky and sometimes misleading, but it's still a good tool for getting an idea of places where you have particle systems with too many overlapping sprites.

One trick I sometimes use to create complex-looking effects without a huge number of overdrawn particles is with rotating sprites:

In this example, there are just three layers of clouds, one rotating clockwise and two rotating counter-clockwise. Using additive blending, the rotating layers create the illusion of more complex eddies. It tends to look better when the layers rotate at different speeds; e.g. you might have one layer rotating clockwise at 49°/minute and another rotating counter-clockwise at 62°/minute. However, this trick might be difficult to adapt to a 3D star.
> 6 votes

# Answer
An alternative could be to have multiple transparent spheres on each other and similar to Kevin's answer, each one rotating with different speeds.

and for the atmosphere you can sill use particle systems. but maybe you should try fewer but larger particles.

maybe also activate culling, so that particles from the other side of your planet does not need to be rendered. making sure that culling is activated often can helps against overdraw.
> 0 votes

---
Tags: unity, performance, particles
---