title: Tiled2Unity not accepting a .txm file

text:
# Question
Title: Tiled2Unity not accepting a .txm file
I'm trying to import a map from Tiled to Unity. I have seen on several video tutorials (all of them on Windows) that they used Tiled2Unity in order to import such files. However, when I download Tiled2Unity, it does not accept .tmx files. It says that it wants .xml. Fair enough--I export it from Tiled as an .xml, and then it can't read the file.

Has anyone else had this problem? Anyone know how to deal with it?

# Answer
> 1 votes
In case anyone was as silly as I was, you have to "Open" the .txm file via the top menus and you can ignore the XML option.

---
Tags: unity, tiled, tiled2unity
---


# Question
Title: My Canvas has an image which I am using for my background but it is blocking my Camera from seeing my Game Scene
So I am not entirely sure how to explain this as I have not had any luck searching online and I'm sure this is a simple problem but I'm being stupid and can't see it.

I have a Canvas which is for my UI obviously and I have added an Image as a Background to the Canvas. The problem I am having is that due to the Image on the Canvas it is blocking my Camera from seeing the Scene with my game object you can see in the background.

On the Canvas, I have tried playing around with Sort Order, Render Mode, and see if I could edit the Z-Position but I can't seem to do that. I'm not too sure what I have missed but I must have missed something.

Any assistance would be great.

# Answer
Just use a second canvas and put the background image into it. Then toggle off everything that may trigger interaction like the `Graphic Reycaster` component and interactibility options of images themselves. Unless you want to enable something like a background click to be able to "click away" menus or windows.

Now, set that canvas to `Screen Space - Camera` instead of `Screen Space - Overlay`. Overlay causes the canvas to be rendered on top of everything else and is meant as foreground UI which should be viewable at all times to the player. Use `Plane Distance` to set up at which z-position that canvas should be rendered at. Everything behind it will be obscurred by it... but you can set it to any high value (not more than the `view distance` of your camera though).
> 0 votes

---
Tags: unity, camera, gui, html-canvas, scene
---


# Question
Title: Problem while creating balancing board using Unity physics
I am trying to create a balancing board using Unity Physics. Below are the steps that I followed to achieve my result and I got unexpected Unity Physics.

1. Balancing-bar and base are connected through a sphere and sphere is having a fixed joint with balancing-bar and I freeze y,z rotation and all the positions of the sphere and base's all position and rotation are fixed.
2. Balancing-bar is having a rigid body with Mass, Drag and Angular Drag 5,1,5 respectively and rotation on y and z are Freeze. Balancing bar is connected to the sphere using Hinge Joint. below I attached an Image for understanding.

I created a video for understanding.

Video Link

Problems:
1. When I throw an object a bit above from my balancing-board then it that side of bar automatically pulls down.

(Both objects is having the same mass=1 and both are 4 Meter far from the pivot point and on "Let's check" button I just turn off board's isKinematic)

2. When I do the same before Unlocking the isKinematic it works perfectly well.

I am just blank here what to do next or where I did the mistake, any help is appreciated.

# Answer
To create a weighing balance that will return to the original position, the horizontal beam must be positioned below the axis of rotation. Read more here.

In your case, the center of mass for the boxes plus the beam is above the rotational axis. The net force will not help move the beam toward the original position, as a weighing balance does.

I see at least two ways of fixing this. One way is to change your seesaw construction into a weighing balance, with the boxes hanging down below the beam. Another way would be to shift the center of mass for the boxes below the beam. In a unity script, do something like this:

```
rigidbody.centerOfMass = Vector3 (0, -2, 0);

```

You might need to shift the CM more or less depending on your setup. I've added a GIF showing a that the shifted center of mass approach works (using p2.js physics engine). The small circles at the bottom are the center of mass positions for the boxes.
> 3 votes

---
Tags: unity, physics
---


title: Java/LibGDX Self made Input Field

text:
# Question
Title: Java/LibGDX Self made Input Field
I want to create an Inputfield from Scratch in Java and LibGDX, my Question is: How can I display only certain Parts of a String in a specific width?

For example: My Input field GUI is 200 pixels wide. But I can write like 500 Letters maximum in my Input field. When I display this 500 letters all at once. It would be bigger than the GUI. So I want when I wrote down the first 100 letters and then write the next one that the first one disappears and the displayed text starts from the 2 Letter and then goes to the 101. And so on. Much like the Minecraft Chat Input field.

# Answer
> 4 votes
One way to achieve this is to measure on-screen width the string contained by the control and compare that to the width of the control. If it is too wide, skip the first character and try again.

The `GlyphLayout` class in **libGDX** can help you here.

A naive implementation may look like this:

```
package com.bornander.playground3d;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.GlyphLayout;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;

public class CustomInput extends Actor {

    private static final String TEMPLATE = "The quick red fox jumps over the lazy brown dog. ";

    private int index = 0;
    private float elapsed;
    private BitmapFont font;
    private StringBuilder text = new StringBuilder();

    public CustomInput(Skin skin) {
        font = skin.getFont("default-font");
        setWidth(100);
        setHeight(font.getLineHeight());
    }

    @Override
    public void act(float delta) {
        // Just pretend a character is typed every .2 second
        elapsed += delta;
        if (elapsed > 0.2f) {
            elapsed = 0;
            text.append(TEMPLATE.charAt((index++) % TEMPLATE.length()));
        }
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        font.setColor(Color.WHITE);

        // Try to fit the full text, if after measuring it it turns out to be too long,
        // skip the first character and try again
        String textToDisplay = text.toString();
        for(int i = 0; i < text.toString().length(); ++i) {
            textToDisplay = text.toString().substring(i);

            GlyphLayout glyphLayout = new GlyphLayout(font, textToDisplay);
            if (glyphLayout.width < getWidth()) {
                break;
            }
        }

        font.draw(batch, textToDisplay, getX(), getY() + font.getLineHeight());
    }
}

```

In the above example I have ignored the task of attaching a key listener and the control simply adds a character every .2 seconds, also no consideration has been given to performance.

---
Tags: java, libgdx
---


# Question
Title: ScriptableObject referencing a gameobject in scene
What I'm using for the scriptableobjects that requires a reference of a gameobject in scene is for scheduling events like for moving. Meaning a scriptableobjects should have a gameobject or waypoint for an npc to go to.

Is there a workaround to scriptableobject to have reference of a gameobject in scene? Or are there any better ways to do this?

# Answer
Sorry, but that's not going to work. ScriptableObjects are supposed to act as assets which can be reused between scenes. That means you can't and shouldn't make them dependent on objects which exist in only one scene.

But what you can do instead is:

* **Ugly workaround 1:** Have the ScriptableObject find its object(s) at runtime. You can do that by tag, by name or by their position in the hierarchy. Just keep in mind that most methods to find objects are slow, so you should do this once in `OnEnable()` and not whenever that object is requested.

The major drawback of this solution is that you won't be able to just drag&drop game objects to the fields of the scriptable object. You would have to enter some description and then you will have to start the game to see if that description finds the correct object.
* **Ugly workaround 2:** Make the ScriptableObject's responsible for instantiating the objects they need. Note that it is possible to reference prefabs from a ScriptableObject.

This will of course be difficult to do when the ScriptableObjects are supposed to share objects between each other.
* **Alternative solution which might actually work:** Turn your ScriptableObject class into a MonoBehaviour class. Instead of creating a bunch of assets, create a bunch of invisible game objects which live in your scene hierarchy and *pretend* to be assets. You can then assign other objects in the scene to the properties of these objects and then assign the objects to properties of other objects.

One advantage of this solution is that it allows you to add some scripting to your objects which gets executed in edit mode. For example, when the object represents a route consisting of multiple waypoints, then they could visualize that route in the scene editor by drawing a series of lines.

I'm looking forward to playing your game.
> 7 votes

---
Tags: unity, c#, gameobject, waypoints
---


# Question
Title: How can I make randomly meeting between the agents?
The logic is that randomly each agent if he is at distance from other agent less then 2 stop moving rotate smooth facing to the other agent wait 3 seconds then both to rotate smooth back facing the next waypoint and keep moving to the waypoint.

There is also a possible that agent that is close to other agent less then 2 distance will not stop and rotate facing to it. The idea is to make random meetings between random agents.

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

public class AgentControl : MonoBehaviour
{
    public List<Transform> points = new List<Transform>();
    public bool randomMeeting = false;
    public float threshold = 3f;
    public float strength = 5f;

    private float speed;
    private int destPoint = 0;
    private NavMeshAgent agent;
    private GameObject[] agents;

    void Start()
    {
        agents = GameObject.FindGameObjectsWithTag("Agent");

        agent = GetComponent<NavMeshAgent>();
        var agentsDestionations = GameObject.FindGameObjectsWithTag("Waypoint");

        for (int i = 0; i < agentsDestionations.Length; i++)
        {
            points.Add(agentsDestionations[i].transform);
        }
        // Disabling auto-braking allows for continuous movement
        // between points (ie, the agent doesn't slow down as it
        // approaches a destination point).
        agent.autoBraking = true;
        agent.speed = Random.Range(10, 50);
        speed = agent.speed;

        GotoNextPoint();
    }

    void GotoNextPoint()
    {
        // Returns if no points have been set up
        if (points.Count == 0)
            return;

        // Set the agent to go to the currently selected destination.
        agent.destination = points[destPoint].position;

        // Choose the next point in the array as the destination,
        // cycling to the start if necessary.
        destPoint = (destPoint + 1) % points.Count;
    }

    void Update()
    {
        RandomMeeting();
        // Choose the next destination point when the agent gets
        // close to the current one.
        if (!agent.pathPending && agent.remainingDistance < 2f)
        {
            GotoNextPoint();
        }
    }

    private void RandomMeeting()
    {
        if (randomMeeting)
        {
            GameObject randomAgent = agents[Random.Range(1, agents.Length)];
            if (Vector3.Distance(agent.transform.position, randomAgent.transform.position) <= threshold)
            {
                StartCoroutine(Meeting(randomAgent));
            }
        }
    }

    IEnumerator Meeting(GameObject randomAgent)
    {
        var targetRotation = Quaternion.LookRotation(randomAgent.transform.position - transform.position);
        var str = Mathf.Min(strength * Time.deltaTime, 1);
        transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, str);

        yield return new WaitForSeconds(3);
    }
}

```

I added the RandomMeeting method. But it's far away from the behaviour I want.

UPDATE: Still not working. This is what I did so far:

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

public class AgentControl : MonoBehaviour
{
    public List<Transform> points = new List<Transform>();
    public bool isInMeeting = false;
    public float threshold = 5f;
    public float strength = 5f;

    private float speed;
    private int destPoint = 0;
    private NavMeshAgent agent;
    private NavMeshAgent[] agents;

    void Start()
    {
        agents = FindObjectsOfType<NavMeshAgent>();

        agent = GetComponent<NavMeshAgent>();
        var agentsDestionations = GameObject.FindGameObjectsWithTag("Waypoint");

        for (int i = 0; i < agentsDestionations.Length; i++)
        {
            points.Add(agentsDestionations[i].transform);
        }
        // Disabling auto-braking allows for continuous movement
        // between points (ie, the agent doesn't slow down as it
        // approaches a destination point).
        agent.autoBraking = true;
        agent.speed = Random.Range(10, 50);
        speed = agent.speed;

        GotoNextPoint();
    }

    void GotoNextPoint()
    {
        // Returns if no points have been set up
        if (points.Count == 0)
            return;

        // Set the agent to go to the currently selected destination.
        agent.destination = points[destPoint].position;

        // Choose the next point in the array as the destination,
        // cycling to the start if necessary.
        destPoint = (destPoint + 1) % points.Count;
    }

    void Update()
    {
        Meeting();
        // Choose the next destination point when the agent gets
        // close to the current one.
        if (isInMeeting == false && !agent.pathPending && agent.remainingDistance < 2f)
        {
                GotoNextPoint();
        }
    }

    private void Meeting()
    {
        for (int i = 0; i < agents.Length; i++)
        {
            if (agent != agents[i])
            {
                float dist = Vector3.Distance(transform.position, agents[i].transform.position);
                if ( dist < threshold)
                {
                    agents[i].GetComponent<AgentControl>().isInMeeting = true;
                    isInMeeting = true;
                    agent.GetComponent<Renderer>().material.SetColor("_Color", Color.yellow);
                    agents[i].GetComponent<Renderer>().material.SetColor("_Color", Color.yellow);
                    StartCoroutine(Meeting(agents[i]));

                    break;
                }
            }
        }
    }

    IEnumerator Meeting(NavMeshAgent Agent)
    {
        var targetRotation = Quaternion.LookRotation(Agent.transform.position - agent.transform.position);
        var str = Mathf.Min(strength * Time.deltaTime, 1);
        agent.transform.rotation = Quaternion.Lerp(agent.transform.rotation, targetRotation, str);

        yield return new WaitForSeconds(10);
        Agent.GetComponent<AgentControl>().isInMeeting = false;
        isInMeeting = false;
    }
}

```

The script is attached to a Prefab and then I duplicate the prefab so I have many agents. So each agent have the script attached.

The logic as I see it should be that each two or more agents that the distance is less the threshold should stop rotating smooth facing each other waiting 10 seconds rotate back and continue each one on the way they was.

A meeting can be between two or more agents. And if an agent is on the way and there is already a meeting he can join the existing meeting or maybe not to join and keep moving on his way the logic is to create some kind of meetings or more to say groups of conversations.

So when the game is running you see some groups of agents in conversations some agents will not be at any conversation and some agents will leave/join existing conversations.

But I'm still can't make the first part a simple meeting between two agents. When two agents getting close less then threshold they are in yellow but not stopping then other agents getting close and get in yellow too. In the end there is a bog group of agents all the agents at the same place like a one big conversation (meeting).

# Answer
```
public bool randomMeeting = false;

```

You've turned off your meeting logic, so it's being skipped.
> 2 votes

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


# Question
Title: Remove background from sprite sheet after splitting
I am using libgdx to implement a Parallax background. Now I need to show some animated object over the background. I downloaded a sprite sheet(with images of objects on white background), and split it using TextureRegion.split() method. But when I draw the objects to screen, white background is shown along with the object as in this image:

I tried using batch.enableBlending() but it didn't work. Is there any way to resolve this issue? Or should I code only using individual sprites with transparent background? Here is a brief code snippet :

```
public class Animator extends Actor{
        int FRAME_COLS = 3, FRAME_ROWS = 3;

        Animation<TextureRegion> eagleAnimation;
        Texture eagleSheet;
        float stateTime;

        Animator(Texture sheet) {
            eagleSheet = sheet;
            TextureRegion[][] tmp = TextureRegion.split(eagleSheet, eagleSheet.getWidth()/FRAME_COLS,
                    eagleSheet.getHeight()/FRAME_ROWS);
            TextureRegion[] eagleFrames = new TextureRegion[FRAME_COLS*FRAME_ROWS];

            int index = 0;
            for(int i = 0; i < FRAME_ROWS; i++) {
                for(int j = 0; j < FRAME_COLS; j++) {
                    eagleFrames[index++] = tmp[i][j];
                }
            }

            eagleAnimation = new Animation<TextureRegion>(0.09f, eagleFrames);
            stateTime = 0f;
        }

        @Override
        public void draw(Batch batch, float parentAlpha) {
            stateTime += Gdx.graphics.getDeltaTime();

            TextureRegion currentFrame = eagleAnimation.getKeyFrame(stateTime, true);
            batch.enableBlending(); // doesn't work
            batch.draw(currentFrame, 250, 250, 264, 264);

        }

    }

```

This is where I call above class from :

```
    public class GameScreen implements Screen {

        MyGdxGame game;

        Texture eagleSheet;
        OrthographicCamera camera;
        Array<Texture> layers;
        Stage stage;

        public GameScreen(MyGdxGame game) {
            this.game = game;
            stage = new Stage(new ScreenViewport());
            camera = (OrthographicCamera) stage.getViewport().getCamera();

            layers = new Array<Texture>();

            for(int i = 1 ; i <= 6; i++) {
                layers.add(new Texture(Gdx.files.internal("parallax/img" + i + ".png")));
            }
            ParallaxBackground parallaxBackground = new ParallaxBackground(layers);
            parallaxBackground.setSpeed(1);
            parallaxBackground.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
            stage.addActor(parallaxBackground);

            eagleSheet = new Texture(Gdx.files.internal("eagle.png"));
            Animator animator = new Animator(eagleSheet);
            animator.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
            stage.addActor(animator);

        }

        @Override
        public void render (float delta) {
            Gdx.gl.glClearColor(1, 0, 0, 1);
            Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

            stage.act();
            stage.draw();

        }

        @Override
        public void dispose () {
            stage.dispose();
        }

        @Override
        public void show() {}

        @Override
        public void hide(){}

        @Override
        public void resume(){}

        @Override
        public void resize(int x, int y){}

        @Override
        public void pause(){}

    }

```

# Answer
Resolved this by editing image in TexturePacker, which makes background transparent.
> -1 votes

---
Tags: libgdx, alpha-blending
---


# Question
Title: How do I change a bool value once an animation has played?
I've designed a Dodge behavior for my player. On input the behavior is executed setting "isDodging" bool to true. My Animation also plays when "isDodging" is true.

I need a proper way to set "isDodging" to false once the Behavior is complete. Currently "isDodging" becomes false once touching the ground is detected, but I think the best way to handle this would be once the animation is complete or the animation has been canceled into a different behavior. What steps would you recommend?

```
using UnityEngine;

public class Dodge : AbstractBehavior
{
    public float speed;
    public bool isDodging;

    private void FixedUpdate()
    {
        var canDodge = inputState.GetButtonValue(InputButtons[0]);

        if (!isDodging && canDodge)
            OnDodge();

        else if (isDodging && collisionState.standing)
            isDodging = false;
    }

    protected virtual void OnDodge()
    {
        var velocityX = speed * (float) inputState.direction;

        isDodging = true;
        body2D.velocity = new Vector2(velocityX, body2D.velocity.y);

    }
}

```

# Answer
reference a Animator component and you can create a bool in the animation tab. to set it you can use anim.SetBool()

```
Animator anim

void Start{
anim = GetComponent<Animator>()
}

if (!isDodging && canDodge)
        OnDodge();

  //removed where you set to false

protected virtual void OnDodge()
{
    var velocityX = speed * (float) inputState.direction;

    isDodging = true;

    anim.SetBool("isDodging", isDodging);
    body2D.velocity = new Vector2(velocityX, body2D.velocity.y);

}

```
> 1 votes

---
Tags: unity
---


# Question
Title: Why some of the agents are keep staying in the waypoint and not continue to the next waypoint/s?
In the screenshot group of 4 agents (in red) are staying on the waypoint(blue) and they just rotating on the waypoint. The other agents keep moving the waypoints.

I'm creating waypoints and agents (NavMeshAgent):

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

public class InstantiateObjects : MonoBehaviour
{
    public GameObject prefab;
    public Terrain terrain;
    public float yOffset = 0.5f;
    public int objectsAmount;
    public bool parent = true;
    public bool randomScale = false;
    public string tag;
    public string name;

    public Vector3 RandScaleMin;
    public Vector3 RandScaleMax;

    private float terrainWidth;
    private float terrainLength;
    private float xTerrainPos;
    private float zTerrainPos;
    private GameObject clonedObject;
    private ObjectPool objectPool;

    public void Start()
    {
        //Get terrain size
        terrainWidth = terrain.terrainData.size.x;
        terrainLength = terrain.terrainData.size.z;

        //Get terrain position
        xTerrainPos = terrain.transform.position.x;
        zTerrainPos = terrain.transform.position.z;

        generateObjectOnTerrain();
    }

    public void Update()
    {

    }

    public void ReleaseObjects()
    {
        GameObject[] allobj = GameObject.FindGameObjectsWithTag(tag);
        for (var i = 0; i < allobj.Length; i++)
        {
            objectPool.ReturnInstance(allobj[i]);
            allobj[i].hideFlags = HideFlags.HideInHierarchy;
        }
        generateObjectOnTerrain();
    }

    public void generateObjectOnTerrain()
    {
        objectPool = new ObjectPool(prefab, objectsAmount);

        for (int i = 0; i < objectsAmount; i++)
        {
            //Generate random x,z,y position on the terrain
            float randX = UnityEngine.Random.Range(xTerrainPos, xTerrainPos + terrainWidth);
            float randZ = UnityEngine.Random.Range(zTerrainPos, zTerrainPos + terrainLength);

            float yVal = Terrain.activeTerrain.SampleHeight(new Vector3(randX, 0, randZ));

            var randScaleX = Random.Range(RandScaleMin.x, RandScaleMax.x);
            var randScaleY = Random.Range(RandScaleMin.y, RandScaleMax.y);
            var randScaleZ = Random.Range(RandScaleMin.z, RandScaleMax.z);
            var randVector3 = new Vector3(randScaleX, randScaleY, randScaleZ);

            //Apply Offset if needed
            yVal = yVal + yOffset;

            clonedObject = objectPool.GetInstance();

            if (randomScale == true)
                clonedObject.transform.localScale = randVector3;//new Vector3(randScaleX, randScaleY, randScaleZ);

            if (parent)
            {
                GameObject parent = GameObject.Find(name);
                clonedObject.transform.parent = parent.transform;
            }

            clonedObject.tag = tag;
            clonedObject.transform.position = new Vector3(randX, yVal, randZ);
        }

        if (prefab.name == "AgentPrefab")
            AgentsComponents.StartInit();
    }
}

```

Then adding two components to each agent:

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

public class AgentsComponents
{
    private static GameObject[] objectsfound;

    public static void StartInit()
    {
        objectsfound = GameObject.FindGameObjectsWithTag("Agent");

        for (int i = 0; i < objectsfound.Length; i++)
        {
            objectsfound[i].AddComponent<NavMeshAgent>();
            objectsfound[i].AddComponent<AgentControl>();
        }
    }
}

```

And the AgentControl script:

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

public class AgentControl : MonoBehaviour
{
    public List<Transform> points = new List<Transform>();
    private int destPoint = 0;
    private NavMeshAgent agent;

    void Start()
    {
        agent = GetComponent<NavMeshAgent>();

        var agentsDestionations = GameObject.FindGameObjectsWithTag("Waypoint");

        for (int i = 0; i < agentsDestionations.Length; i++)
        {
            points.Add(agentsDestionations[i].transform);
        }

        // Disabling auto-braking allows for continuous movement
        // between points (ie, the agent doesn't slow down as it
        // approaches a destination point).
        agent.autoBraking = true;

        agent.speed = Random.Range(10, 50);

        GotoNextPoint();
    }

    void GotoNextPoint()
    {
        // Returns if no points have been set up
        if (points.Count == 0)
            return;

        // Set the agent to go to the currently selected destination.
        agent.destination = points[destPoint].position;

        // Choose the next point in the array as the destination,
        // cycling to the start if necessary.
        destPoint = (destPoint + 1) % points.Count;
    }

    void Update()
    {
        // Choose the next destination point when the agent gets
        // close to the current one.
        if (!agent.pathPending && agent.remainingDistance < 0.5f)
            GotoNextPoint();
    }
}

```

I set autoBraking to true since I want the agents to slow down when getting close to each waypoint.

What I want to do is to make all the agents to move between all the waypoints. Either is there are 10 agents or 500 some of them stay at some waypoint and not continue to the next one. I waited like 2-3 minutes and they didn't continue.

I didn't change anything in the NavMeshAgent properties except the autoBraking set it to true.

# Answer
You want to increase the Stopping Distance so the agent will complete the navigation.

The crowded agents all fighting and auto braking to get .5f away from the destination so they will just spin around.

Increasing the stopping distance will allow a bit of leeway for when a destination get's crowded and it should move to the next point just as expected.
> 0 votes

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


# Question
Title: How can I fill a Polygon with a certain color on Pixmap?
Libgdx allows to fill area on a Pixmap just with circles, rectangles and triangles, but I need to fill complex figure that can be described with Polygon class, so how can I do that?

I was thinking about polygon triangulation, but it seems sophisticated to me.

May be exists some better way to fill complicated shapes with pixels?

# Answer
> 1 votes
Depending on what you need the `Pixmap` for you can probably use a `FrameBuffer` to draw anything on, including complex shapes using a `ShapeRenderer`.

Using a `FrameBuffer` you get a render target where you can draw whatever you like and then get a `Texture` of that that you can then draw onto the *screen*.

An example of using a `FrameBuffer` might look like this;

```
package com.bornander.playground3d;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.TextureData;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.FrameBuffer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;

public class Playground3DGame extends ApplicationAdapter {
    private OrthographicCamera camera;
    private ShapeRenderer shapeRenderer;
    private FrameBuffer frameBuffer;
    private SpriteBatch spriteBatch;

    @Override
    public void create() {
        float aspectRatio = (float)Gdx.graphics.getHeight() / (float)Gdx.graphics.getWidth();
        float width = 100;
        float height = width * aspectRatio;
        camera = new OrthographicCamera(width, height);
        shapeRenderer = new ShapeRenderer();
        // Create a FrameBuffer that is 50x50 pixels
        frameBuffer = new FrameBuffer(Format.RGBA8888, 50, 50, true);
        spriteBatch = new SpriteBatch();
    }

    @Override
    public void render() {
        camera.update();
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

        // Begin the FrameBuffer, this means render calls after this will
        // affect the FrameBuffer and not the screen
        frameBuffer.begin();

        // Use the ShapeRenderer to render what-ever shapes you need
        // (you can also draw anything you can draw onto the screen onto the FrameBuffer)
        shapeRenderer.setProjectionMatrix(camera.combined);
        shapeRenderer.begin(ShapeType.Filled);
        shapeRenderer.setColor(Color.RED);
        shapeRenderer.circle(0, 0, 16);
        shapeRenderer.end();

        frameBuffer.end();

        // Get the Texture from the FrameBuffer when done drawing
        Texture texture = frameBuffer.getColorBufferTexture();

        // If you still need to, you can get a Pixmap from the Texture
        Pixmap pixmap = null;
        TextureData textureData = texture.getTextureData();
        if (!textureData.isPrepared()) {
            textureData.prepare();
            pixmap = textureData.consumePixmap();
        }

        // If you don't need the Pixmap, you can draw the texture directly
        // onto the screen
        spriteBatch.begin();
        spriteBatch.draw(texture, 0, 0);
        spriteBatch.end();
    }
}

```

---
Tags: libgdx
---


# Question
Title: How to make the camera follow the player in Libgdx?
In Play class I have the viewport of game height=320 and game width=240unitswith camera cam. I have set the camera(cam) viewport width to 10 and viewport height to 7.I have another camera hud whose viewport width is game width and viewport height is game height. In render method, I have set Spritebatch to a projection matrix of hud.combined.Here is how the game looks like

I want the camera to follow the player. I have tried this

```
cam.position.set(player.getPosition().x,player.getPosition().y,0);

```

After doing this, the tilemap is bouncing and i can see the black portion of the screen

# Answer
Looking at it, you probably want to update only the `x` position of the camera. And since the player is not really centered, you may want to add a delta to it:

```
cam.position.x = player.getPosition().x + delta;           // adjust delta to your needs (start with 0, then increase it untill you find the right amount)
cam.update();                                              // don't forget to update

```

`delta` is the horizontal distance from the center of the screen to your player.

**Note:** This could use some **lerping** so that the camera movement is smooth:

```
cam.position.x += (player.getPosition().x + delta - cam.position.x) * lerp * deltaTime;
cam.update();

```

`lerp` should have a value between `0` and `1`. Play around with it untill you get something good.
> 2 votes

# Answer
After you set the position on the camera using `cam.position` call `cam.update()` to recalculate the matrices before you use `combined`.
> 0 votes

---
Tags: java, libgdx, android, camera, opengl-es
---


title: Open world game state saving Android

text:
# Question
Title: Open world game state saving Android
As a hobby project I'm building a **2D** game with a **custom game engine** in Android. Currently I can render a json map, and let the user interact with objects on the map. The game should be an open world map, with multiple maps. One of my current maps has a 150 x 150 tile pattern, with on every tile one or more objects. Thus, the map has **22.500**, multiple layers, and more attributes. The player can edit objects (like fish in water object, plant seeds in soil, etc.), so every object needs to be stored separately. Some objects, like growing plants, **need to be updated over time**, even when the player is not playing the game.

My question is about efficiently **saving and loading** the game state. I think I need to store all the attributes of the maps, together with the objects, player progress, npc progress, and so on. Since this is a lot of data for a **mobile device**, I can't think of a good way to store this on the phone (or in the cloud).

I've tried the following: \- Store the entire game state in a **serialized** file. The parsing of this file took way to long while loading, and when one object's state changed, the whole game had to be loaded. \- Store every object in a **sqlite database**, with for every attribute a **column**. This was even slower than the first option, so not an option either. \- Store every object serialized as a **blob** in the database. This option wasn't much faster than the previous one.

I've been looking at **ObjectBox**, but in order to create the entity values for this database, I need to change a lot of reference values to ToOne\<\> or ToMany\<\> objects, which will take a lot of time and since I am using the map attributes to render the maps, the wrapping and unwrapping of the objects would cause (unnecessary) delay. (This is an assumption)

How do I save the game state without causing a 20-minute loading delay?

# Answer
A common solution is to divide your game world into rectangular chunks which have about the size of one screen and only load those chunks which are currently needed.

Store each chunk in one serialized file or in one database entry.

When the player enters the game, only load the chunks which are in or around their viewport.

When the player moves to a different chunk, load the chunks around them and save and unload the chunks they moved away from. This is not just important for loading times but also for conserving memory and CPU cycles for updates.

When you want things to happen to chunks even when the player isn't present (like plant growth, for example), process these for the chunk when that chunk is loaded. When the player returns to their farm, check how long ago you unloaded that chunk, and then process the plant growth accordingly.

But you might also want to take a close look at how exactly your serialization format looks on the byte level. 150x150 tiles really isn't that large. I've worked on games which could easily handle much larger maps without having to use chunks. Think carefully about how much data your really need to save. You haven't wrote much about how your data structures look, so it's hard to give any concrete advise. But usually a tile is just an integer representing the type. When you need to store more information per tile, look at how to store that information in the least bytes possible.

I'm looking forward to playing your game.
> 2 votes

---
Tags: java, 2d, android, performance, savegame
---


# Question
Title: How can I loop through pixels in the material editor?
I am using Unreal Engine 4, and I want to try to procedurally generate a grass texture. For now, I am using a noise block. Now I want to loop through every 16 pixels or whatever (4x4 squares), take the average color of those pixels, and make that all one "pixel". I don't see any for loops, loops, etc. in the pallete though. Can you not do this with the material editor? Thanks.

# Answer
You can do this but it just makes your nodes messy! It's a bit of a messy approach but I'm not aware of any nodes that gives us quick access to surrounding pixels:

1. Create const floats ( name them wRatio and hRatio ) and set their values to:
wRatio : `1.0/texture width`
hRatio: `1.0/texture height`

If you want to hit pixel center offset the texture ( or add it to w/hRatio ) by half of wRatio and hRatio.

2. Create a `TexCoord` node
3. Create a `BreakOutFloatComponent` and attach the TexCoord output to it.
4. With our new data we now need to Create 9 new (3x3, you can do 16 but do you really want to?) 2d Vectors. The ouput is set by their offset based on the wRatio and hRation. for example {-wRatio,-hRatio} is the top left pixel of the 3x3 setup. Combine the `BreakOutFloatComponent` with your ratios using `add` math nodes. Make sure to negate any ratio first by multiplying by -1 using a math `multiply` node to get the correct coordinate. R output with wRatio and G with hRatio.
5. Use the `append` node to combine the new u and v coordinates into a new vector 2d. Repeat this for every offset.
6. Use each result to sample from the texture as uv input. For this create 9 `Texture Sample` nodes and connect each offset respectively.
7. Add all of the color outputs together with the math `add` node and then divide them by 9 with the math `divide` node. This is your average color.

Here is the setup for average of 2 lookups

You can see that this will be a nightmare if you go up in sample count.

Alternatively you can also use a custom expression : https://docs.unrealengine.com/en-us/Engine/Rendering/Materials/ExpressionReference/Custom

Requires you to write some hlsl but the syntax for such function is actually very easy. The blur example points you in the right direction.
> 1 votes

# Answer
I don't think this can be done through material nodes. However you can use the Custom node to write your own GLSL code, or write a custom GLSL shader.
> 0 votes

---
Tags: textures, unreal-4, materials, unreal, blueprints
---


# Question
Title: UnrealEngine4 "backwards compatilibility": Can I view a site that uses Unreal Engine4 on a very old laptop and still see in high definition?
# Backwards compatible?

### The project:

I want to render a high definition model on my personal website such that it'll be rendered in the highest definition possible on any device, from a 20-year-old Gateway PC running Windows 95 to an iPhoneX. It's particularly important that it's real pretty on mobile (whatever Android and iPhone models are big these days)

### The question:

I was thinking I'd buy an expensive desktop with GPUs to make sure I can make the app really fancy for users on a high-end desktop with nice monitors. But I'm not going to do that if the high-definition I get on my new expensive screen doesn't make it out to the app my employer is building. How does this work? Does OpenGL display the highest-definition render it can on the mobile device?

# Answer
> 2 votes
A "20 year old" PC is going to be well below the minimum requirements needed to run anything built on modern Unreal 4. So no, this will not scale gracefully (or indeed, *at all*). It certainly won't render in "high definition."

To support hardware and software that old you'll likely need to fall back on entirely different technology in that scenario. Given the cost-to-benefit ratio of supporting users on such antiquated platforms, I'd strongly advise going with what was suggested in the comments and falling back to pre-rendered static images or simply moving your own minimum spec up to something in the modern era.

I'd also suggest that UE4 is a pretty heavyweight tool to use just to display a model on a webpage; you may want to investigate alternative, more web-focused technology (perhaps three.js, which can apparently create a simple model view embed pretty easily).

---
Tags: opengl, javascript, unreal-4, mobile, swift
---


# Question
Title: How to create a grid of 3d objects without making them actual GameObjects
Very simple question: If I'm going to be generating and placing a lot of 3d objects (in this case cubes), that are not going to be interactive, like no collision, no raycasting intersections etc. Should they be GameObjects or is there a lighter solution that doesn't inherit the GameObject blob?

Cheers,

# Answer
GameObjects don't really prove to be that big of an overhead. Just make sure you are using a material with GPU Instancing enabled.

However, if you want to avoid GameObjects anyway, you can instead use the `Graphics` class. Specifically `Graphics.DrawMeshInstanced`. You just need a reference to a Mesh and Material, as well as an array of matrices that indicate where to draw each one. Something like this:

```
public class DrawCubes : MonoBehaviour {
  public Mesh cube;
  public int submeshIndex;  //If the mesh has more than one submesh, specify which one to draw. Normally this can be left as 0.
  public Material material; //Note: This material must have instancing enabled.

  private Matrix4x4[] locations;
  void Start() {
    locations = new Matrix4x4[10];
    for (int i = 0; i < locations.length; ++i) {
      //Position at (i,0,0), no rotation, with no scaling
      locations[i] = Matrix4x4.TRS(new Vector3(i,0,0), Quaternion.identity, Vector3.one);
    }
  }
  void Update() {
    Graphics.DrawMeshInstanced(cube, submeshIndex, material, matrices);
  }
}

```

A few notes, from Unity's documentation:

> Meshes are not further culled by the view frustum or baked occluders, nor sorted for transparency or z efficiency.

And

> You can only draw a maximum of 1023 instances at once.

Also

> InvalidOperationException will be thrown if the current platform doesn't support this API (i.e. if GPU instancing is not available). See SystemInfo.supportsInstancing.

If instancing is not supported, while you can still draw one at a time, using `Graphics.DrawMesh`, this is actually going to be less performant than using GameObjects, because this method does not use batching.

Finally, there are many overrides to `DrawMeshInstanced` to check out which add other features, like MaterialPropertyBlock overrides per instance.
> 1 votes

---
Tags: unity, gameobject, efficiency
---


# Question
Title: Unity: Resources folder empty in Build and public variables NullReferenceException
I got 2 big problems that after a lot of research I´m unable to solve.

**First problem**: I got 5 xml files and a sub-folder inside the Resources folder but when I build my project, the Resources folder is empty (well, only two unity files in there: unity default resources and unity\_builtin\_extra. So I can´t access my xml files when I do: Resources.Load, anywhere on my code.

I post images to clarify:

**Second problem**: As Resources file was not working I decided to use public variables for my xml files declaring: public TextAsset myXmlDoc, but I realize that, only when I build this isn´t working as it gets NullReferenceException as if my public TextAsset variable wasn't assigned by me (wich is not true)

I post images and code to clarify:

```
public class LoadXml_Narrator : MonoBehaviour {

    NarratorTextClass narratorClass;
    public TextAsset file;

    void Awake()
    {

        print("Xml file " + file);
    }
}

```

This is the output log of my Build:

NullReferenceException: Object reference not set to an instance of an object at LoadXml\_Narrator.Awake () \[0x0001d\] in D:\Projects\PC\Majorel\_\Majorel\_\Assets\Scripts\XML\Narrator\LoadXml\_Narrator.cs:20

(Filename: D:/Projects/PC/Majorel\_/Majorel\_/Assets/Scripts/XML/Narrator/LoadXml\_Narrator.cs Line: 20)

> Note: IN the editor everything works perfect. The issue is only when build and execute the project.

# Answer
> 1 votes
I found the origin of the problem. I had marked the checkbox: Scripts Only Build at Build Settings. Honestly, I don't know why becasue I didn't even know what it does. Anyway thank you so much for pointing me in the right direction. I Was about to go crazy.

After some research I found little info about this option, even the manual doesn´t show it https://docs.unity3d.com/Manual/BuildSettings.html The documentation just say: Build only the scripts of a project. So I guess it includes only some of the scripts for speed reasons when building.

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


title: How to optimize collisions

text:
# Question
Title: How to optimize collisions
I'm building a 2D MORPG using JavaScript, Node JS and socket.io

To prevent cheating, I have to run all collisions for all players on my server.

I'm currently doing fairly simple square collisions like this:

```
  for (var i = 1 ; i < collidables.length ; i++) {
    if (y < collidables[i].y + collidables[i].z &&
        x < collidables[i].x + collidables[i].z &&
        x + z > collidables[i].x &&
        y + z > collidables[i].y) {
          // Handle collision
    }
  }

```

When a player collides with a wall I halve their speed and bounce them back.
This is not working optimally, but it's fine for now.

The same logic is used to check bullet collision and possibly collision with monsters in the future.

I'm currently using 3 different loops for the follwing:

1. Player vs Terrain collisions
2. Bullet vs Terrain collisions
3. Bullet vs Monster collisions

Since all of them have slightly different logic.

Should I put them all in the same loop or is using multiple loops fine? I feel like using multiple loops will slow down my server a lot once there will be some more terrain / players / monsters.

I chose square collisions because I think they are a lot faster than any other type of collision checking, and my game will have a LOT of collision checking.

I think I will allow between 50-100 players on a single server, with most likely hundreds of monsters and thousands of bullets flying around.

There will also be a rather big map that has to stay loaded on the server. But since the server doesn't actually have to draw anything this should be fine? Client-side the map is split up into smaller parts and only loads the parts near the player.

My game is working fine for now, but there's no real way to test with 50 players until people actually start playing.

I'm afraid I will find out way too late that my collision checking is taking up way too much server memory and/or cpu.

How can I improve the efficiency of my collision checks?

...

Here's a preview of my game in pre-alpha, it should make my question less abstract.

http://185.115.218.199:3000/

If I need to post any more info / code, please let me know and I will do so!

I'm currently running this game on a very small test-server with 512MB RAM and 1 VCPU (can't find the specifications)
This is scalable to up to 16GB RAM and 8 VCPU's and probably beyond that.

# Answer
> 10 votes
---

## Query only nearby objects

As you already know, you need to check only nearby objects. This means that you need a way to retrieve a list of nearby objects to check.

To do that, you need to divide the map in areas, and each area has a list of objects that are currently there. Then, you can solve collisions within each area※.

※: Areas do not overlap. Yet, there could be collisions between objects from one area to an adjacent one. Two solutions: 1) Add objects to more than one area, 2) check with objects in the current area and adjacent ones.

To keep these lists of objects that are in a area, every time an object moves, you need to remove it, and add it to the new one (or new ones).

---

**On a grid**

You can divide the world in grid, and make each cell one of the collision areas.

You can optimize the query of finding a cell from coordinates using a very simple locality-sensitive hash: just truncate the coordinates, concatenate them, and that is the index of the cell.

About your grid, you want to pick a size that would make it rare that an object is in two or more grids. Therefore, you want large cells. However, you do not want your cells to be too large that you get a large list of objects in each grid. There will be an optimal size for your game. Test.

---

**On a tree**

You can divide the world in a tree, for example using binary space partitioning (good for labyrinth like zones) or simply working with a recursive grid (that would make an quad tree). The process should give a tree where each leaf is one of the collision areas.

Using the tree, it is trivial to find adjacent nodes, which is what you would do to narrow the list of nodes where an object could have gone.

---

**Note**: Beyond this point I will describe more optimizations, however, they are not a good fit for every game. So, do not forget to test.

---

## Discarding checks instead of collision

I will talk to you in terms of relational databases for a moment. Imagine you have a table that has all your objects, and we want to check for collisions, so we query a join of this table with itself, and each result is a potential collision.

However, this gives us sorted pairs. The first thing we want to avoid - which should be obvious - is to check the same collision both ways. We want to check collision regardless of the order in which we receive the objects.

Now, there would be rules to discard collisions (for example, a flying entity does not collide with ground obstacles).

However, we can think in terms of discarding checks... each case, has a check one way, and a check the other way, if we discard both, we discard the collision.

What we do, in practice, is have a loop that goes over each object in the collision area, and then inside another loop that goes over each other object in the collision area that we haven't checked yet.

Imagine we have a large number of objects that do not move. Only a few objects move. It is much more efficient to go over each moving object and check against nearby objects, than going over each stationary object, and check if they collide with a moving object.

That is, we can discard the collision checks that starts with the stationary objects.

---

## Query objects by their kind

As I was saying above, it is useful to know if an object is stationary. In fact, you want to separate objects that move from those that do not (terrain obstacle, for example). With that, you can also avoid checking if an object has changed from one collision area to another, just because it is stationary.

An optimization you will find in physic engines is to declare an object that has no or negligible speed stationary. You can choose to do the same.

Also, **not everything can collide with everything**. For example, you may have flying units that do not collide with terrain, or you may not have friendly fire (meaning that bullets from allies do not hit), or whatever. Usually, projectiles will not collide with each other (at least not with projectiles from the same faction).

Separate objects by what they can collide with... then, each collision area will not just have a list of objects, but a dictionary where you can get a list of objects of each given kind.

---

**Dumb objects**

While classifying objects as described above can separate objects that move from those that do not. We are also interested in objects that follow a simple predictable motion.

For example, your projectiles. Unless you have seeking projectiles that pursue their target, can bounce or something like that, I bet your projectiles follow a line with a fixed starting position and a velocity. Perhaps with a maximum travel distance.

**Note**: For large maps, you want a maximum travel distance for projectiles. It helps reducing the number of moving objects. *In real life, a projectile that has traveled for a long time will just fall to the ground*, and it will help with the optimization I describe below.

As you know, you need to put them in a collision area... do it in advance. Add to your collision area a dictionary (ideally a circular buffer) of dumb objects, and the key to the dictionary will be time. Now, you can add your projectile to all the areas it would pass ahead of time... and when you query for objects in your collision area, you take the list of dumb objects that correspond to the current time.

Eventually, the projectile will collide, and then you remove it. In addition, of course, you want to remove lists of dumb objects that are too old.

As Philipp was explaining spatial data structures speed up collision checks, they slow down updates. What I describe here will speed updates back up but will slow down creation and destruction. As always, it is tradeoffs. However, going from something you do for every object each update cycle to something you do for every object once is very good on my book.

---

## Systematic Collision Detection

There are two approaches for collision detection (and physics in general): Discrete and continuous. You seem to be doing Discrete, which is also simpler to understand, so let us start there...

---

**Discrete physics simulation**

You update the positions and velocities of each object (depending on their kind) each update cycle. Thus, each update cycle the objects will have a new position. Then we check at that position if there is a collision.

The problem with discrete physics is that it can allow tunneling. A naive solution is to increase the update frequency. A more advance solution is to find potential collisions pairs first, and then consider the movement of these pairs at more fine time steps.

To find our potential collision pairs - aside from looking only within our current collision area and considering objects by their kind - we can consider for each object a rectangle that covers the initial and final position of the object, then, collide these rectangles.

---

**Continuous physics simulation**

Instead of considering the objects at a finite amount of time steps, we will consider their trajectory.

That means:

1. Get the potential collision pairs.
2. Create a collision volume that takes into account the time between updates and the object speed. This is a bounding box of the positions of object.
3. Collide these volumes.
4. Figure out the collision moment, and decide if they did or if they just missed each other.

If you need it, you can also extract the contact points for physics simulation.

There are multiple approaches to do do this, thus, I will not go into detail. What matters for performance is to organize the code in such way that you can discard the cases where there was no collision as soon as possible.

---

**Notes**

1. There will be an ideal time step for your hardware and load. Too fast and your CPU is busy doing very little, too slow and each update require a lot of work. Test.
2. remember that your client can do (and arguably should be doing) simulation and prediction for their local space at a higher rate than the server does for the whole map.
3. If you work with squares instead of rectangles, your collision detection reduces to a Manhattan distance check. You can describe your objects as a set of squares at different resolution, and this would converge to pixel perfect collision detection. **Errata**: A "circle" (all the points at the same distance from a point) using Manhattan distance is a square, but one rotated an eighth of a turn (45º). You would need to do this rotation transformation to use straight up Manhattan distance for collision checks.

---

## Can you trust the players?

You could let a client - selected by the server - simulate an area and then push to the server what happens.

*Sacrebleu!*

ROBLOX does this, there are articles describing it in more detail. Keep in mind that this is not a solution for a few thousand players, but for hundreds of thousands of players.

You can do something similar, letting the client simulate, however the server still needs to check that received simulation makes sense (all velocities are consistent, nobody did teleport, etc...). Having multiple clients doing this can allow the server to discard updates from cheaters.

*This also leads to some physics artifacts due to discrepancies in timing with the clients, in particular when an object passes from being simulated by a client to another or to the server. I would suggest to use the moment of collision to change the ownership of objects to hide the artifacts (that is, do not change ownership midair).*

---

## Other optimizations

Since you know the direction of movement of an object, you may check only objects on that direction. If you are checking adjacent collision areas, you can decide which to check by this.

Moreover, if you can organize the list of objects in each collision area by one axis, the speed of the object can allow you to discard checks with objects based on their position on the list. However, this is just discarding check, but not discarding collisions, since there could be collision between objects moving in the same general direction.

You can actually go beyond, and build a tree inside each collision area. That would result in a hybrid solution between using grid and a tree.

---

When picking your data structures, you may want to choose cache aware ones. In particular, many tree data structures are not cache aware. You want the memory of nearby objects to be nearby, so that it can stay in cache while checking collisions, minimizing trips to RAM.

---

It can also be useful to set a maximum speed you will see in the game. Many fast collision detection solution have problem with fast moving objects... well, do not have fast moving objects.

Using that maximum speed, you can ensure that an object will not completely skip a collision area in one update cycle (or, conversely, decide how deep you have to do into adjacent collision to check). It is also useful to decide if an object is close enough to an adjacent area to add it there (or check collision there).

---

Is the server having too much trouble with collisions? Slow down time (thank EVE online for the idea). I do not mean to reduce the frequency of the update cycle, but to reduce speeds. A very simple implementation is to clamp the time between updates, so you do not mess with your speeds, but you make time actually pass slower. Less time per update cycle means less collision per update cycle.

The interesting part about the approach that EVE online took for this is to apply it in different areas proportionally to how dense they are. Meaning that players that are on part that currently have very little action are not affected.

---

Consider using parallelism to check for collisions. This would be hard to implement on node.js, as it does not really have threads... however, you can have multiple processes on the same server. You will find that collision detection has a lot of opportunity for parallelism. You can run different collision areas in parallel, you have collision detection for different pairs of objects happening in parallel, or even there are chances for parallelism in the checks for a single pair of objects.

Finally, another thing that would be hard to implement (but not impossible) with node.js is GPU-Assisted Collision Detection. If everything else fails, research this.

# Answer
> 3 votes
> My game is working fine for now, but there's no real way to test with 50 players until people actually start playing.

There is. Just write a bot client for stress-testing your gameserver. While it is hard to write a convincing bot which behaves exactly like a real player would behave, it is usually not that difficult to write one which just logs in, joins a game and performs some simple automated actions to generate some server load. The bot should be simple and lightweight, so you can easily run a lot of instances of it (i.e. no graphic output). Run 50 instances of your bot on your local workstation and have them connect to the server.

By the way, you might notice that such a bot can be used to automate a lot of other tedious testing tasks. You could even go so far and implement a whole automatic integration test suit by having some bots play preprogrammed matches and check automatically if it still turns out the way it is supposed to.

Checking every object in the game against every other object in the game is an algorithm with a time complexity of `O(n²)`. That means the execution time raises quadratically with the number of objects in the game. When you notice that the amount of collision checks creates notable performance degradation, look into ways to reduce the number of objects you need to compare every object with.

One useful method is to divide the game map into sections, keep track of which section contains which objects and only check collisions between objects in the same or in neighboring sections.

Another is to store all your game objects in a spacial tree like an octree or 3-d tree which allows you to quickly iterate all objects in a given area.

But keep in mind that while spacial datastructures speed up collision checks, they slow down movement because you need to update these structures whenever something moved. That means they work best for objects which move rarely or never. A section-based approach (sometimes referred to as "spatial hashing") does not have that much overhead for moving objects, because all you need to do when an object moves from one section into another is remove it from the old section and add it to the new one. So you could also try a hybrid approach. Use trees for checking collisions between game objects and walls and use sections for checking collisions between game objects and other game objects.

# Answer
> 1 votes
There are different ways to deal with collision, but we should always prioritize efficiency. A brute force algorithm such as the one you’ve implemented runs n^2 times, or at O(n^2), which is expensive and will greatly decrease your speed the more objects you have to compare.

As already mentioned, you want to compare only objects that are close enough to where collision is even possible. To achieve this, you should use Quad-trees for 2D games or Oct-trees for 3D games.

Think of your scene as a graph with four quadrants, starting with the top-right quadrant going counter-clockwise, labeling 0-3 respectively. Each quadrant can have a maximum number of objects (x) and level number (n). When a quadrant contains the maximum number of objects, this is where the level number will come into use because the quadrant will be split into another four quadrants and the same rules will apply for those as well. The new quadrant will be assigned level number n+1.

Using this recursive algorithm to assign an index (quadrant) and level number to each object, you will have a significantly less amount of checks by returning the list of objects that are in the same quadrant and objects that may overlap boundaries. This runs at O(nlog(n)). So much better. Same applies to OctTrees with eight quadrants.

Here’s a good link for further details: https://gamedevelopment.tutsplus.com/tutorials/quick-tip-use-quadtrees-to-detect-likely-collisions-in-2d-space--gamedev-374

---
Tags: collision-detection, javascript, performance, optimization, node.js
---


# Question
Title: Unity C# order of execution for multiple start functions?
I have a scene in my project where a lot objects need to access different objects to share data with.

Some objects have functions that need to be executed only once during the void Start function. These call a predefined function in a different class.

So now you know a bit what is happening I am experiencing an issue. During the Start function they call a method that only works when the Start function of that class has already been progressed.

**Example:** Class A has certain values to calculate and set. Once this has happened function A will work. Class B, C and D have a function B that is called at the last line of the Start function. Function B does some magic and then calls function A from Class A. The problem here is however that the void Start from class B, C and D executes before the Start from Class A. This results in not all values being set properly. I only discovered this through debugging and tracking timings of when each function was executed.

Is it possible for Class A to make the void Start execute before the void Start from the other classes? For example is the order of execution based on alphabetical values or something *awake (per class) -\> start (class A) -\> start (class B) -\> update (per class)*? So that start A would happen before start B with a simple change of class name?

If I put this code in the awake call I will have the same issues since the awake in other classes might happen before or after the current awake will be executed.

To clarify, they all happen at the same time, but line 12 gets executed before line 13. Which is fairly logical, but how do you know which Start gets executed before the other Start? Or am I simply completely wrong?

I do realize that this might be a confusing read so please don't hesitate to ask questions so that I can explain my issue better.

# Answer
Script Execution order will solve your problems, but it's also kind of a crutch and is easy to accidentally break when changing / importing project settings or refactoring code.

The biggest thing to remember is that you don't have to use the built in Monobehavior callbacks. Create a manager class with a start method, and inside that call your init methods in whatever order is necessary. This can be done with any of the execution callbacks to ensure that dependency chains are satisfied.

This also lets you break away from making everything a monobehavior and enables more flexible design options and lightweight classes / structs.
> 4 votes

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


# Question
Title: SDL2 Draw scene to texture. SDL2 RenderTexture like SFML
I've been developing a 2D Engine using SFML + ImGui.

The editor is rendered using ImGui and the scene window is a `sf::RenderTexture` where I draw the GameObjects and then is converted to `ImGui::Image` to render it in the editor.

Now I need to create a 3D Engine during this year in my Bachelor Degree but using SDL2 + ImGui and I want to recreate what I did with the 2D Engine.

I've managed to render the editor like I did in the 2D Engine using this Example that comes with ImGui.

But I don't know how to create an equivalent of `sf::RenderTexture` in SDL2, so I can draw the 3D scene there and convert it to `ImGui::Image` to show it in the editor.

If you can provide code will be better. And if you want me to provide any specific code tell me.

Thanks!

# Answer
Afaik this function could be of help:

https://wiki.libsdl.org/SDL\_SetRenderTarget

Do you really need to rely on SDL2? SFML has built-in support for OpenGL and would be the better choice.
> 1 votes

---
Tags: opengl, c++, sfml, sdl2, rendertexture
---


# Question
Title: How can I find the position of a corner of a transformed sprite in SFML?
I need help with calculating the end points of a stick (a sprite) in my stick game.

First, I set up it's position by some coordinate (x,y) after that I rotate it by theta degrees.

I know the width and height (427, 17), but I can't figure out how to calculate it's end points after the rotation (I need them for intersect detection algorithm).

Moreover, I can't figure out how to detect when I clicked on it with the mouse, because `getGlobalbounds.contains(mouse)` gives me its bounding box, but I want to detect that I was clicked exactly on the entity..

# Answer
> 1 votes
This is why SFML provides the sf::Transform and sf::Transform classes. Given a sprite with width and height \[32, 32\], we know that SFML treats the origin as the upper left corner. When you set a position for a sprite, the internal transform is modified and will be applied when you draw the sprite.

The position of that upper left corder (unless you changed the origin) is the position you get when you call getPosition() on the sprite. In the local coordinates of the sprite itself, untransformed, the position of that vertex is \[0, 0\]. Now if you want to get the position of the upper right corner, \[32, 0\], you can use the sprites internal transform and transform a vector with this position.

```
sprite.getTransform().transformPoint(32, 0); // Get position of upper right corner
sprite.getTransform().transformPoint(32, 32); // get position of lower right corner
sprite.getTransform().transformPoint(32, 32); // get position of lower left corner

```

Now keep in mind that this is limited to this case. If you change the origin of the sprite, the math changes. I would suggest that you familiarize yourself with linear algebra and linear transformations, to help you understand and solve geometric problems in a new way.

And for finding if a vector is contained by the sprite, not by the bounding box, you can use the axis aligned local bounding box. Take the inverse transform of the sprite and use it to transform the vector you want to test.

```
sf::Vector2f localPosition = sprite.getInverseTransform().transformPoint(somePosition);
if (sprite.getLocalBounds().contains(localPosition)) {
    // do something
}

```

# Answer
> 0 votes
Consider the centre point of the stick. You are rotating one end around the centre by x radians/degrees, and the other end also by the same amount, plus or minus 180 degrees / pi radians. So if you always treat your stick's centre as its actual position, it is easy enough to use matrices or even basic trigometry (which matrices rely on) to rotate the two ends of the stick. Of course, this assumes you will always be rotating a stick by its centre, but it gives you a basis for considering the rotation of the stick from any point. It should be clear that the degree by which each end rotates, is directly proportional to how close you are from either end, e.g. when we rotate around centre, we are splitting the rotation 50-50 for each end of the stick, hence they experience equal rotation.

You will also want to look into either PPCD, or some numerical / geometric method of determining whether the mouse click falls within the stick's rotated bounds.

---
Tags: c++, collision-detection, sfml
---


# Question
Title: How to render gameobjects with same size and same position in unity
canvas can be fixed for all screen sizes but **I want to fit gameobjects which is not in canvas, for all sizes of screen.**

*This is the transform of my game object*

*The game object's size and position variation*

My question is **how to render the gameobject with same size and same position for all screens**

# Answer
If you want to do this with UI objects, then it's pretty straight forward using anchors.

Since your case seems to be with 3d objects, it all depends where you want to place the object. Here's some math:

```
// This is the value on the Z axis, where the object can be placed
// You can populate it with something like `posZ = myObj.position.z;`
float posZ;

// This is your scene's camera, based on its field of view and aspect, it will calculate positions
Camera cam;

// This is the width and height of the "plane" that is visible on the screen on position `posZ`
float height = (Mathf.Tan(cam.fov *Mathf.Deg2Rad*0.5f) *posZ *2f) /10f;
float width = height *cam.aspect;

```

Credits for this code go to this answer on stackoverflow

Based on this, you can use the `width` and `height` to calculate the screen's edges and place objects there. For example placing a cube on position `(width/2, 0, 10)` (assuming `posZ = 10;`) then the center of the cube would be placed on the right part of the screen, making it partially visible.

If you want to place the cube in such a way that it is touching the right part of the screen, and is almost fully visible, then you can assign its position to something like `(width -cubeWidth/2, 0, 10)`.

You can get a `Mesh`'s size with `myMesh.GetComponent<MeshRenderer>().mesh.bounds.size` which is a `Vector3` with the object's dimensions. Note that this shows the bounding box of the mesh, keep that in mind when handling complex meshes.
> 1 votes

# Answer
and the answer is unity will automatically do this ♂we don't need to care of screen resolution for gameobjects.In game window of unity the position and size will be different but in real time case of testing in different resolution mobiles,the unity will resize and position it correctly.
> 0 votes

---
Tags: unity, platformer
---


# Question
Title: How to avoid rows on screen when cutting spritesheet tiles?
I'm having a problem with my spritesheet, I generate a map but when I zoom in on it I can observe these lines as in the image below:

When I used the tiles each in their separate image, that did not happen, how do I avoid this case?

I'm drawing like this, the problem happens when I give a "ctx.scale":

```
ctx.drawImage(
    imgSolos.img,
    (imgSolos.width * resultSolo), // resultSolo is current frame in the spritesheet
    0,
    32,
    32,
    x,
    y,
    imgSolos.width,
    imgSolos.height
);

```

# Answer
Keep in mind that context.scale does not change the internal resolution of the canvas. It just adds a multiplication factor to all coordinates you pass to the drawing functions. Due to floating point inaccuracies on scale factors which are not factors of 2, those coordinates might no longer be pixel-perfect. The result is what you see in that screenshot.

Possible solutions are:

* Implement scaling by changing the width and height of the destination rectangle of your `drawImage` calls. Use the same number of pixels for the x- and y-increments in your map drawing loops. Use integers only.

Note that this might still cause artifacts between the tiles because you will have blurring on each individual tile but no blurring across tile borders.
* Draw your map to a second, invisible canvas *without* scaling. Then draw that invisible canvas to the visible canvas *with* scaling. That way the whole map will get scaled as one image (this might seem inconvenient, but most 2d engines end up adding such an additional layer of indirection sooner or later for a variety of reasons)
* Use CSS to change the size of the canvas in the HTML document. The browser will then stretch the output of the canvas. This actually has the same effect as the previous method, but moves the implementation to the browser's rendering engine
* Only use scale factors which are either integers, or 1 divided by a powers of 2 (0.5, 0.25, 0.125...).
> 4 votes

---
Tags: 2d, javascript, tilemap, tiles
---


# Question
Title: Centre of mass not recalculated after scaling
I am spawning a prefab object at runtime (actually, in the `Start()` method of another object), and I need to apply a scaling to the object. I made a little component to handle this:

```
public class Spawner : MonoBehaviour {

  public Transform SpawnPrefab;
  public Vector3 Scale;

    void Start () {
      var spawn = Instantiate(SpawnPrefab, Vector3.zero, Quaternion.identity);
      spawn.localScale = Vector3.Scale(spawn.localScale, Scale);
      // spawn.GetComponent<Rigidbody>().ResetCenterOfMass();  // Has no effect
    }
}

```

The pivot point of the prefab I am spawning does not coincide with the centre of mass of the object. Therefore, the rescaling means that the centre of mass location relative to the pivot will change. However, it's *not* being updated automatically, so my spawned object has unexpected physics.

I tried adding a call to `GetComponent<Rigidbody>().ResetCenterOfMass()` immediately after the call to `Scale()` (the commented-out line above), but this has no effect.

However, if I put the call to `ResetCenterOfMass()` in the `Start()` method of a separate little component added to the spawned object, e.g.

```
public class COMReset : MonoBehaviour {
  void Start() {
    GetComponent<Rigidbody>().ResetCenterOfMass();
  }
}

```

this *does* cause the centre of mass to be recalculated correctly. However, the spawned object appears to have already been through at least one physics update with the wrong COM by this time, and so has already acquired some unexpected momentum.

Why isn't the COM being automatically recalculated, without me having to call `ResetCenterOfMass()` explicitly? And if I must trigger it manually, can I do that immediately after the calls to `Instantiate()` and `Scale()`, rather than deferring like this?

# Answer
With thanks to @DMGregory for the suggestion, a call to `Physics.SyncTransforms` before invoking `Rigidbody.ResetCenterOfMass` fixes the problem:

```
public class Spawner : MonoBehaviour {

  public Transform SpawnPrefab;
  public Vector3 Scale;

    void Start () {
      var spawn = Instantiate(SpawnPrefab, Vector3.zero, Quaternion.identity);
      spawn.localScale = Vector3.Scale(spawn.localScale, Scale);
      Physics.SyncTransforms();
      spawn.GetComponent<Rigidbody>().ResetCenterOfMass();
    }
}

```

Evidently this direct modification of the transform scale isn't being automatically passed through to the physics engine, but `Physics.SyncTransforms` lets us manually flush those changes down to PhysX, so that the `ResetCenterOfMass` computation is then based on the correctly scaled transform.
> 2 votes

---
Tags: unity
---


# Question
Title: Cable for Kinect - XBox 360 and cable for Kinect - Xbox One
I dont have any of the above and hence wanted to ask if anyone knows if the cable running from Kinect v1 to Xbox 360 and the cable running from Kinect v2 to Xbox One is identical?

I want to use Kinect V2 just for PC ( without Xbox ) and hence was looking for cheap solutions ( avoiding to buy the expensive usb adaptor from microsoft )

# Answer
> 3 votes
No, the cables and their connectors are not the same.

The original Kinect for Xbox 360 uses a proprietary connector that looks similar to USB-A, but with traces on both sides and a beveled corner. It uses more power than standard USB. Later 360 models included a dedicated port for this connector so it could be hooked up directly. To use it with a PC or the earlier Xbox 360 models, you need an additional adapter that forks it off into a regular USB-A cable and an AC transformer plug.

The Kinect for Xbox One uses an L-shaped proprietary connector with two internal slots. Connecting it to the PC requires using a more elaborate adapter with two connection boxes: one that converts it into USB-A and a DC power input, and a separate AC transformer block.

Note that even with this adapter, not every USB 3 port will support the high bandwidth required by the device.

There's also a Kinect for Windows model, similar to the Kinect for Xbox One but outputting to USB directly (still with an extra cable for power, included in the package). So this might be an option for you, though anecdotally I've experienced stability issues with this model that I did not see with the Kinect for Xbox One + adapter. The problems only showed up after repeated sensor connections & disconnections in a single session, so they might not manifest for every application.

---
Tags: kinect
---


title: Artifacts in unity shading

text:
# Question
Title: Artifacts in unity shading
I created block of 3x3x3 cubes, disabled shadows, set directional lighting color to white and ambient to black. And I'm getting this:

Any idea what is going on and how to fix it? Effect is visible when object isn't moving but with a lot less artifacts. It doesn't matter what is moving, camera or cubes. I would guess that this is precision problem but is there anything that can be done about it?

//EDIT

Here is a screenshot of cubes:

Also this is how it looks after static batching (this happens because of `Lightmap Static` in `Mesh Renderer` is on):

# Answer
It looks like there is z-fighting between the shared edge of 2 planes. (where the cubes share an edge)

The plane facing away from the light is colored black, and the plane facing the light is colored gray, but the shared edges have the exact same 3d coordinates.

This is not a trivial problem to solve.

1. You could update the geometry to just show the outward facing surface when cubes are connected.
2. You could use shared vertex normals that face away from the cube center, but the color of the surface wouldn't be uniform across the surface.
> 2 votes

---
Tags: unity, rendering, lighting
---


# Question
Title: In Text ui in the Inspector when showing text sometimes the text is bigger sometimes smaller how can I set it to be the same size in each case?
This is the Text component settings in the Inspector:

The script DialogueManager:

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

public class DialogueManager : MonoBehaviour
{
    public Text dialogueText;
    public float sentencesSwitchDuration;
    public bool animateSentenceChars = false;

    private Queue<string> sentence;

    // Use this for initialization
    void Start ()
    {
        sentence = new Queue<string>();
    }

    public void StartDialogue(Dialogue dialogue)
    {
        Debug.Log("Starting conversation with " + dialogue.name);

        sentence.Clear();
        foreach(string sentence in dialogue.sentences)
        {
            this.sentence.Enqueue(sentence);
        }

        DisplayNextSentence();
    }

    public void DisplayNextSentence()
    {
        if (this.sentence.Count == 0)
        {
            EndDialogue();
            return;
        }

        string sentence = this.sentence.Dequeue();
        dialogueText.text = sentence;

        StopAllCoroutines();
        StartCoroutine(DisplayNextSentenceWithDelay(sentence));
    }

    public IEnumerator DisplayNextSentenceWithDelay(string sentence)
    {
        if (animateSentenceChars)
        {
            dialogueText.text = "";
            foreach (char letter in sentence.ToCharArray())
            {
                dialogueText.text += letter;
                yield return null;
            }
        }

        yield return new WaitForSeconds(sentencesSwitchDuration);
        DisplayNextSentence();
    }

    void EndDialogue()
    {
        Debug.Log("End of conversation.");
    }
}

```

Then the DialogueTrigger:

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

public class DialogueTrigger : MonoBehaviour
{
    public Dialogue dialogue;

    public void TriggerDialogue()
    {
        FindObjectOfType<DialogueManager>().StartDialogue(dialogue);
    }
}

```

And last Dialogue:

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

[System.Serializable]
public class Dialogue
{
    public string name;

    [TextArea(3, 10)]
    public string[] sentences;
}

```

Then in the editor in the Dialogue Trigger in the Inspector I added some text to each of the 3 sentences:

Now when I'm running the game the text is changing between the 3 sentences. But since each sentence have different amount of letters(text content) it display it in a different size:

This is the first sentence when the game is running it seems like to me a good size for the text:

The second sentence. It seems like to me the text size is too small.

The last sentence is the same size like sentence 2.

How can I make that the text will be the same size in each sentence ? And how can I make that the lines will start from the same position from the left ?

How in other games they are aligning the text ?

# Answer
This field, internally, is called `resizeTextForBestFit` and has the description, "Should the text be allowed to auto resized."

https://docs.unity3d.com/ScriptReference/UI.Text-resizeTextForBestFit.html
> 1 votes

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


# Question
Title: How to receive broadcast message in Unity?
I am trying to get the broadcasted message in overridden method of NetworkDiscovery.OnReceivedBroadcast(). For that what I had done is below:

1. I create class which implements NetworkDiscovery where I override the method OnReceivedBroadcast() to capture the broadcast messages.
2. In Unity Editor, I created an empty GameObject where I add the class in step #1 as component.

Now in code, I started the custom NetworkDiscovery class as below:

```
Discovery.Initialize();
Discovery.StartAsClient();

```

Now, when I start the broadcast in server, I am not receiving any broadcast message in OnReceivedBroadcast().

Below is my custom NetworkDiscovery class.

```
public class CustomNetworkDiscovery : NetworkDiscovery
{

// Use this for initialization
void Start()
{

}

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

}

public override void OnReceivedBroadcast(string fromAddress, string data)
{
    base.OnReceivedBroadcast(fromAddress, data);
}
}

```

One thing I noted is, If I use the NetworkDiscovery component directly in step #2; instead of using custom NetworkDiscovery class. I am able to see broadcast messages in it's default GUI.

How can I receive the broadcast message in the inherited class?

Any help will be appreciated. Thanks.

# Answer
Refer this thread for solution http://forum.unity3d.com/threads/onreceivedbroadcast-doesnt-supply-port-number.381833/
> -1 votes

# Answer
I had the same problem. Turns out the class that inherits from NetworkDiscovery **is not allowed to have it's own Update() function**.
> 1 votes

# Answer
I suggest to use source code of the network discovery. In their script there is a void OnGUI() method that controls the GUI control.
> 0 votes

# Answer
I have the same issue but I solved it by un-checking the "Use NetworkManager" and add anything in the broadcast data. I can pass now any data inside my script like

```
discovery.broadcastData = "Hello World"

```

The only problem is you can only broadcast data at once. right after that you are unable to update the broadcasted message
> 0 votes

---
Tags: unity, unity-networking
---


title: How to store shader output to VRAM?

text:
# Question
Title: How to store shader output to VRAM?
This is really ungrateful question to Google.

Basically, I would like to know, regarding openGL, what are various methods to do some kind of computation in one of the shaders and have the results stored in VRAM to be used and accessed at a later time?

# Answer
Some helpful google-able terms will include:

render to a texture use framebuffer object read from a texture using glReadPixels

Hopefully by "computation" you mean "drawing" of some kind. Hope that helps!

http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-14-render-to-texture/

https://stackoverflow.com/questions/32149512/opengl-how-to-read-back-texture-buffer
> 2 votes

---
Tags: opengl, shaders
---


# Question
Title: 3D World coords to on-screen coords in an ancient engine
I've been googling for past 2 hours and I couldn't find a satisfying solution that wouldn't require you to use Unity, OpenGL or Unreal Engine.

My issue is, I was given a task to make a game on an ancient 3D engine built purely from scratch (no OpenGL etc.).

The task I was given is - draw text above every chest the player can see.

In OpenGL I would do a simple transformation seeing how I've got all what I need built in, but in here I have to do the math myself.

The game from top-down looks like this:

Hearts represent chestboxes, the rest is marked.

So here's what I know for sure that might be useful:

* I know XYZ positions of these hearts
* I know the maximum angle after which chest disappears fully from my sight is -32.5 for the left edge and 32.5 for the right screen edge - which made me conclude that FOV is 75.
* The game window (viewport dimensions) is 1024x768
* I can calculate pitch/yaw easily for any two vectors, be it player-\>camera, player-\>chest, camera-\>chest etc.

What I don't know is - where do I go from there?

Any help appreciated, thanks!

PS: The language I'm allowed to write in is C#, but I'm only looking for help with formula so.

# Answer
You have to do the same thing as you would do using OpenGL or DirectX. Simply create a projection matrix using the fov and resolution, then get the coordinates of the chests relative to the camera (which you can get by multiplying the positions of them by the view matrix) and finally multiply these two together to get the screen coordinates of those objects.
> 1 votes

---
Tags: c#
---


# Question
Title: Solving a recursive problem in the geometry (or any other) shader
I would like to calculate an effect of an external force on a binary tree (wind on a tree).

It's a recursive function - take a (parent) node and calculate the angle to rotate all of the nodes "younger" than the parent around the parent for the same angle according to the force applied. Then do it for the child nodes and repeat until you reach the leaves. If I'm calculating it right this is a problem of O(k * 2^n) complexity, where n is the depth of the tree and k number of nodes.

Since we rotate a lot of stuff (which is a nice matrix multiplication), it would be really nice to do it on the GPU. The problem is that this code needs to run as many times as the depth of the tree, and not all of it can run in parallel.

For each node (vertex) I have to modify all the nodes (vertices) downstream that vertex. This, however, ruins the parallelism of the GPU, since child nodes cannot be calculated before their parents, but the effect should lessen further up the tree I traverse. How do I make the GPU do this efficiently, if you consider the fact that I'll be having multiple trees in the scene?

Basically, on one hand, I have the same code that needs to execute for every vertex in the same way, but on the other, it needs to be executed in order, only vertices on the same level can run concurrently.

Any idea on how to solve this problem and what to do?

If I were to use Vulkan instead, would that broaden my options?

# Answer
> The problem is that this code needs to run as many times as the depth of the tree, and not all of it can run in parallel.

...which is the prime indicator NOT to process this *as such* on the GPU. GPU architecture suits problems where the individually-processed elements are independent of one another.

> If I were to use Vulkan instead, would that broaden my options?

No. Using a different API doesn't change the underlying GPU architecture, which doesn't suit this kind of problem *as such*. In any case, you may be better off using compute (OpenCL, CUDA) here.

> Any idea on how to solve this problem and what to do?

Break down the problem to enable the sort of massively parallel processing where the GPU excels. At any given pass (phase), there can be no data dependencies, which is your current problem.

Run through multiple kernel passes, where each pass represents a depth in the tree; this would take in parent transforms from `currentDepth-1` and output the child transforms for `currentDepth`.

**Queueing work on the GPU**

In OpenCL we submit *commands* via the *command queue*; in CUDA we submit *streams*. These will then run on the GPU in the same order as you have specified them in your CPU-side code.

These terms should help you to find the resources you need to code up a solution.
> 2 votes

---
Tags: opengl, geometry-shader, vulkan, compute-shader
---


# Question
Title: Can a sprite be rendered with thickness in Unreal Engine?
Is there a convenient way to have a 2D pixel art image with clip transparency (not partial transparency) rendered with thickness in Unreal Engine? Paper2D does exactly what I want, except it's a flat plane.

I'm able to achieve the effect by making an SVG outline and using Blender to make a model and map UVs, then import that into Unreal, but it seems like a lot of steps for a somewhat simple model. I am new to both of these tools and models in general, so I may be missing something obvious.

# Answer
> 1 votes
I would build the mesh at load time, i.e. during your initial startup/preload sequence. Pseudocode:

```
//create / triangulate front and back planes
for each texel in texture
    if texel is not transparent
        for each corner in 4 corners of texel
            //front
            create 4 vertices for front texel (at z=0)
            push these 4 vertices into mesh vertices list
            triangulate them - 2 triangles form a square texel
            push these 2 triangles into mesh triangle-indices list
            //rear
            create 4 vertices for rear  texel (at z=1)
            push these 4 vertices into mesh vertices list
            triangulate them - 2 triangles form a square texel
            push these 2 triangles into mesh triangle-indices list

//triangulate mesh sides
for each pair of adjacent corners/vertices on front face
    find matching pair of corners/vertices on back  face
        triangulate between these 4 points with 2 triangles

```

...a naïve approach that leaves out a lot of detail as I don't want to have to write this up myself, but should get you going. Not sure about mesh generation in Unreal but here is the docs link for Unity.

A slightly more efficient approach avoids duplicating the same corner vertices between texels, which is wasteful. This is achieved by first running through all non-transparent texels and adding their corners to a set or dictionary so there are no duplicates. Then add to these to the mesh vertices list, then triangulate between these.

A much more efficient approach involves creating only the outermost / silhouette vertices, and triangulating row-by-row between its left- and rightmost vertices. If your image has holes, you'll do this multiple times per row. This leads to a smaller vertex buffer being pushed up to the GPU.

---
Tags: 2d, 3d, models, unreal
---


# Question
Title: How to make an enemy spawner that selects from a list of potential enemies? (Unity)
I'm just making a practice version of a basic 2D RPG, but I'm trying to build a spawner kind of object that could be scaleable across the entire game. That is, there would be multiple types of enemies, and each instance of such a spawner would have a specific set of enemies that it would spawn.

I'm sure the answer is very simple, but I'm at the beginning stages of all of this. I guess really I just want a simple list that I can attach to my object and add the enemy names to it so that it can draw from that to figure out what they would spawn.

# Answer
> 2 votes
I guess it is. Simply add a public array of type GameObject and drag and drop your enemy prefabs in it inside the inspector panel. Use Random.Range(x,y) to get a random int and use it this way:

```
r = Random.Range(0, enemyTypes.Length); //random.range normally gives back a float, therefore, you may need to use 1 instead of 0
Instantiate(enemyTypes[r], position, rotation);

```

Hope that was enough & I was able to help you :)

---
Tags: unity
---


# Question
Title: Unity 2D Tap to shoot at mouse position on android device
Hello everyone i am really stuck at the moment and would appreciate any help if possible. I have my game where i move the player up and down with 2 buttons on the bottom left of screenshot.

I also have a button over the entire screen for tap to shoot and this moves the weapon to my finger position where i have tapped and it shoots towards that position using mouse.position.

Now the problem is when i am on my android device and i am moving up and down but when i also tap to shoot the gun it moves towards my up and down buttons and this is not what i want.

i want to be able to move with my finger and also shoot towards the second finger.

Any ideas would be greatly appreciated.

Here is my Tap to shoot button code!

```
public void ShootButton()
{
 timer = 0;
 Face = true;
 //if finger presses Shootbutton
 //then activate this

 Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) -
 transform.position;
 // subtracting the position of the player from the mouse position.
 difference.Normalize(); //normalizing the vector meaning all the sum of the
 vector will be = to 1.

 float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;//find
 the angle in degree.

 WeaponTrans.transform.rotation = Quaternion.Euler(0f, 0f, rotZ +
 rotationOffset);
 if (reloading == false)
 {
     if (fireRate == 0)
     {
         {
             Shoot();
         }
     }
     else
     {
         if (Time.time > timeToFire)
         {
             timeToFire = Time.time + 1 / fireRate;
             Shoot();
         }
     }
 }
}

```

# Answer
I´m not sure what you exactly meant. But I guess you mean on a touchscreen. And your weapon jumps around once you click any of the up & down buttons. 1) use Input.Touch instead of Input.mousePosition 2) use a foreach loop like this:

```
foreach(Touch t in Input.Touches)
 {
   //now you have different posibilities:
   //one of them could be
   if(t.position is inside of the button)
   {
     //do not use it for detecting direction
   }
   else
   {
     //the touch position is not inside a button => execute shoot code
   }
 }

```

also, you said you have a button over the entire sceen to detect touches: That´s bad practise you can use touch phases like this:

```
switch(touch.phase)
{
  case Touchphase.Began:
  //code executed when the finger touches the screen
  break;
  case Touchphase.Ended:
  //code executed when the finger leaves the screen
  break;
}

```

I guess that takes to long to explain but there are tons of good videos out there. This one might explain it good.

If you have more questions feel free to comment and ask on specific. I might able to answer more specific then
> 1 votes

---
Tags: unity, c#, rotation, input, raycasting
---