# Question
Title: Bullet Physics DebugDraw Unexpected Results
I'm integrating Bullet Physics into my project for collision detection and have just gotten some debug draw functionality to work. However, the results are not what I'm expecting. I have tried to draw a sphere and box shape, but each time they turn out looking like below (this specific screenshot is how a btBoxShape is being rendered):

Relevant code is as follows:

```
//From CollisionWorld.h
class CollisionWorld {

private:
    btCollisionConfiguration*   bt_collision_configuration;
    btCollisionDispatcher*      bt_dispatcher;
    btBroadphaseInterface*      bt_broadphase;
    btCollisionWorld*           bt_collision_world;
    btScalar                    scene_size = 500;
    unsigned int                max_objects = 1000;
    CollisionDebugDrawer        collision_debug_drawer;

public:
                                CollisionWorld(bool debug = false);
                                ~CollisionWorld();
    void                        draw();
    CollisionDebugDrawer&       getCollisionDebugDrawer();
};

//From CollisionWorld.cpp
CollisionWorld::CollisionWorld(bool debug){

    bt_collision_configuration = new btDefaultCollisionConfiguration();
    bt_dispatcher = new btCollisionDispatcher(bt_collision_configuration);

    btVector3 worldAabbMin(-scene_size, -scene_size, -scene_size);
    btVector3 worldAabbMax(scene_size, scene_size, scene_size);
    bt_broadphase = new bt32BitAxisSweep3(worldAabbMin, worldAabbMax, max_objects, 0, true);

    bt_collision_world = new btCollisionWorld(bt_dispatcher, bt_broadphase, bt_collision_configuration);
    if (debug) {
        bt_collision_world->setDebugDrawer(&collision_debug_drawer);
    }

    /*btCollisionObject* sphere = new btCollisionObject();
    sphere->getWorldTransform().setOrigin(btVector3((btScalar)0, (btScalar)2, (btScalar)0));
    btSphereShape* sphere_shape = new btSphereShape(2);
    sphere->setCollisionShape(sphere_shape);
    bt_collision_world->addCollisionObject(sphere);*/

    btCollisionObject* box = new btCollisionObject();
    box->getWorldTransform().setOrigin(btVector3((btScalar)0, (btScalar)2, (btScalar)4));
    btBoxShape* box_shape = new btBoxShape(btVector3((btScalar)1, (btScalar)1, (btScalar)1));
    box->setCollisionShape(box_shape);
    bt_collision_world->addCollisionObject(box);

}

CollisionWorld::~CollisionWorld(){}

CollisionDebugDrawer& CollisionWorld::getCollisionDebugDrawer() {
    return this->collision_debug_drawer;
}

void CollisionWorld::draw() {
    this->bt_collision_world->debugDrawWorld();
}

//From CollisionDebugDrawer.h
class CollisionDebugDrawer : public btIDebugDraw {

private:
    Shader      debug_shader;

public:
                CollisionDebugDrawer();
                ~CollisionDebugDrawer();
    Shader&     getDebugShader();
    void        drawLine(const btVector3& from, const btVector3& to, const btVector3& color) override;
    void        drawContactPoint(const btVector3 &, const btVector3 &, btScalar, int, const btVector3 &) override;
    void        reportErrorWarning(const char *) override;
    void        draw3dText(const btVector3 &, const char *) override;
    void        setDebugMode(int p) override;
    int         getDebugMode(void) const override;
};

//From CollisionDebugDrawer.cpp
CollisionDebugDrawer::CollisionDebugDrawer() :
    debug_shader(GlobalConstants::DEBUG_VERTEX_SHADER,
    GlobalConstants::DEBUG_FRAGMENT_SHADER) {};

CollisionDebugDrawer::~CollisionDebugDrawer() {};

Shader& CollisionDebugDrawer::getDebugShader() {
    return this->debug_shader;
}

void CollisionDebugDrawer::drawLine(const btVector3& from, const btVector3& to, const btVector3& color) {

    // I know this is highly inefficient, but this is just to insure everything is working as expected,
    // I plan on implementing a better solution once everything clicks

    unsigned int VBO2, VAO2;

    GLfloat points[6];

    points[0] = from.x();
    points[1] = from.y();
    points[2] = from.z();
    points[3] = to.x();
    points[4] = to.y();
    points[5] = to.z();

    glGenVertexArrays(1, &VAO2);
    glGenBuffers(1, &VBO2);
    glBindVertexArray(VAO2);

    glBindBuffer(GL_ARRAY_BUFFER, VBO2);
    glBufferData(GL_ARRAY_BUFFER, sizeof(points), &points, GL_STATIC_DRAW);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), 0);
    glEnableVertexAttribArray(0);

    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glDrawArrays(GL_LINES, 0, 2);

    glBindVertexArray(0);
    glDeleteBuffers(1, &VBO2);
    glDeleteVertexArrays(1, &VAO2);

}

void CollisionDebugDrawer::drawContactPoint(const btVector3&, const btVector3&, btScalar, int, const btVector3&) {}
void CollisionDebugDrawer::reportErrorWarning(const char*) {}
void CollisionDebugDrawer::draw3dText(const btVector3&, const char *) {}
void CollisionDebugDrawer::setDebugMode(int p) {}
int CollisionDebugDrawer::getDebugMode(void) const { return 3; } // TF is 3?

//From Scene.cpp (where all of this is called)
void Scene::render(float alpha) {

    GameState lerp_render_state = lerpRenderState(alpha);

    // Set player_actor point (debug only)
    player_actor.getModel().setTranslation(lerp_render_state.player_point.position + glm::vec3(0.0f, 0.0f, -3.0f));

    // Select a color to clear the screen with and clear screen
    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // Same shader used for all models (collision_world uses it's own shader)
    shader.use();

    // Draw the stage
    shader.setMat4("mvp", camera.getProjectionMatrix() * camera.getViewMatrix() * stage.getModel().getModelMatrix());
    stage.getModel().draw(shader);

    // Draw the player capsule (wouldn't normally do this as capsule is for collision only)
    shader.setMat4("mvp", camera.getProjectionMatrix() * camera.getViewMatrix() * player_actor.getModel().getModelMatrix());
    player_actor.getModel().draw(shader);

    // Debug draw for collision world
    collision_world.getCollisionDebugDrawer().getDebugShader().use();
    collision_world.getCollisionDebugDrawer().getDebugShader().setMat4("vp", camera.getProjectionMatrix() * camera.getViewMatrix());
    collision_world.draw();

}

```

Does anything stick out as being horribly incorrect? I feel like this is probably something simple I've missed.

# Answer
> 0 votes
Issue wound up being something simple as expected. I was using the incorrect value for the stride parameter in the `glVertexAttribPointer` function

This:

```
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), 0);

```

Should have been this:

```
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0);

```

---
Tags: opengl, c++, bullet-physics
---


title: How do I make a C# script in Unity?

text:
# Question
Title: How do I make a C# script in Unity?
I was watching a tutorial on how to script, and I got stuck making the script in the first place. I use Unity 2019.3.0a5

# Answer
# From Game Object

1. Create a game object or use an existing one.
2. Go to the inspector (panel on the right side).
3. Click on "Add Component", it will open a small pop up.
4. The last option is called "New Script". Click that. You can also write "New Script" on the search bar or just write the name of your new script. If that name doesn't exist, Unity will ask you to if you want to make a new script.

# From Hierarchy folder

1. Press secondary click on the bottom panel (folder views).
2. Click create.
3. Click C# Script (old versions \[as fair I know\] allowed you to make UnityScript, Boo Script or Javascript).
> 2 votes

# Answer
1. create (eg) a empty Game Object
2. look at its inspector
3. click on "Add Component"
4. New Script

Hope this helped. :p
> 1 votes

---
Tags: unity
---


title: Snake game steering with Java FX

text:
# Question
Title: Snake game steering with Java FX
I am currently trying to make a snake game with Java FX, I read several posts about it and I understand on theory how to move the snake body (for each part of the snake reference the previous one and move it to its former location) but I am facing some issues, my snake is not able to turn around properly:

I would just like it to react as a normal snake, when the head steers into a direction then the other body parts follow one by one.

In my case I created a vector class to store positions and velocity (I use velocity to be able to move all the part at the same speed and therefore be able to keep the 3 pixel gap between them).

I usually trying my best to resolve issues but this time I've spent almost 3 hours knowing the theory and groping for a proper way to do it but without any improvements.

I tested different approaches but this one seems to be the clearest and the nearest to the solution to me:

I got 2 simple classes that are Vector (only holding reference to X and Y) and Block that holds references such as Position, Velocity for the current motion, `nextVelocity` to anticipate steering, Previous for the previous block in the snake body.

I initialize my snake like that :

```
    public Snake(){
    this.head = new Block(250,250);
    for(int i = 0; i < 5; i++){
        if(i == 0){
            body.add(i, new Block(new Vector(head.getPosition().getX() - 18 , head.getPosition().getY())));
            body.get(i).setPrevious(this.head);
        }else{
            body.add(i, new Block(new Vector(body.get(i-1).getPosition().getX() - 18, body.get(i-1).getPosition().getY())));
            body.get(i).setPrevious(body.get(i-1));
        }
    }
    this.head.setPrevious(body.get(0));
}

```

Then there are my `steer()` method for the head as well as my `follow()` method for the other body parts.

I used the variable `nextVelocity` that stores the velocity of the previous part if this one is different from the current one, in this case `nextVelocity` is passed to velocity at the next frame to avoid that the whole body moves at the same time in the direction taken by the head (which apparently doesn't work):

```
public void steer(Vector velocity){
    this.velocity = velocity;
    this.position.add(velocity);
    this.shape.relocate(this.getPosition().getX(), this.getPosition().getY());
}

public void follow(Block previous){
    if(this.velocity == null) {
        this.velocity = new Vector(previous.velocity);
    }else if(this.nextVelocity != null) {
        this.velocity = new Vector(this.nextVelocity);
        this.nextVelocity = null;
    }else if(this.previous.velocity != this.velocity){
        this.nextVelocity = new Vector(this.previous.velocity);
    }
    this.position.add(this.velocity);
    this.shape.relocate(this.getPosition().getX(), this.getPosition().getY());
}

```

And finally my move() method handling the whole snake moves:

```
public void move(Vector direction){
    this.head.steer(direction);
    for(int i = 0; i < body.size(); i++){
        if(i == 0){
            body.get(i).follow(this.getHead());
        }else{
            body.get(i).follow(body.get(i-1));
        }
    }
}

```

If anyone could point me into the right direction or just let me know where I am mistaking it would be amazing.

# Answer
What you need is to store a path.

Keep a collection of positions the head has been. On each tick you will add a new position to the collection. You may also remove positions that are too far back. Because you will be adding and removing, a circular list would do.

How big should the capacity of the circular list be? It needs to be long enough to accommodate the whole snake.

An optimization you should do is to add only if the new position has changed more than some minimun distance form the last one. That will get rid of redundant positions wasting space in the circular list. Also, if you know the minimun distance, you know the capacity you need in the circular list by dividing the length of the snake.

---

Once you have a path, your job is to place the parts of the snake along the path, keeping their distance. Thus, each tick, you set the position of each segment (iterating from head to tail) a given distance from the previous segment.

This means that the body will follow the same path as the head (a follow steering behaviour will have the segments try to cut ahead). It also means that the velocity of the head will not cause the snake to compress (we can imagine a simple follow steering behaviour will have snake body collapse to the position of the head when it stops) or stretch (if you use a follow steering behaviour the snake will become longer when the head accelerates).
> 1 votes

---
Tags: java, game-mechanics, javafx, snake
---


# Question
Title: Gameobject becomes a Cube when uploading it to Unity from Blender
I'm making a 3d mobile game, for one of my gamemodes i need "Hexagon" gameobject.

According to my research I can create unique gameobjects in blender. So I tried to make a hexagon and export it as an wavefront(.obj) but when uploading it to unity, all i can see was cube.

**Edit:** I've tried to export it as an FBX, Wavefront and even Blender file, but none of them works.

# Answer
I've solved the problem by deleting start-up objects in the blender by simply selecting them and pressing "X".
> 0 votes

---
Tags: unity, graphics, blender
---


# Question
Title: How do you partition a level and create screen transitions out of these partitions?
The levels in Castlevania games, you walk forward and then come to a point on the level where the screen stops scrolling but is not a deadend and there's no door either. They just wanted to transition to the next room for some reason (like a hallway transitioning to another room).

I want to create something like this in Unity, using 2.5d (3d characters constrained in 2d plane); question is, do I separate each transition to a scene? But that seems kinda wasteful (I don't know, maybe). Or just one scene and develop the level as a whole and do some camera programming for the transition making sure everything lines up?

# Answer
Both options are viable.

But separating your game into multiple scenes can have various advantages. It's better for performance to have less "stuff" in the scene at once (while Unity *can* do some culling on its own to reduce the overhead of rendering things which are not on the screen, some overhead still remains) and most importantly it allows multiple level designers to work on different parts of the game at the same time.

The downside is that it makes the transitions a bit more complicated to handle, because you need to load one level, do the transition and unload the old. All without interrupting the game.

The easiest one is a fade-to-black transition where you use a post-processing effect to turn the screen dark, switch to the next level, and then turn the screen bright again. See "What is the proper way to handle data between scenes?" for how to make sure your gamestate information survives the transition. Another option is to load the new scene with `LoadSceneMode.Additive` so both scenes coexist at the same time, do the transition, and then unload the old scene.

There are also various other approaches you could take. Which one is "best" depends on what aesthetic you are aiming for in your level transition and what fits into the architecture of your game.
> 1 votes

---
Tags: unity, side-scroller
---


# Question
Title: How can a NamMeshAgent be configured to always look towards its next path position, but never move there?
I'd like to have something like an on-screen panel that appears in the direction that you are supposed to go.

The panel is a NamMeshAgent with a speed of 0. I was hoping something like this would work:

In `Start`: `agent.updateRotation = false;`

In `Update`: `this.transform.LookAt(agent.nextPosition);`

But no luck.

Should be straight forward, I'm just not too familiar with the Unity 2019 nav mesh and can't find the answer online. Thanks.

# Answer
> -1 votes
I came up with the following mediocre solution that works for me.

```
    void Start()
    {
        agent = GetComponent<NavMeshAgent>();
        agent.destination = Target.transform.position;
    }

    void Update()
    {
        if(Random.value < 0.01) this.agent.Warp(Player.transform.position);
    }

```

Warping every frame prevents the turning from working so I just warp it randomly. Speed and acceleration on nav mesh agent also have to be above zero... I don't like how the agent moves towards the destination, but it's okay in my case because the whole thing is a placeholder for a particle effect, so the particles (being simulated in world-space) shouldn't jitter.

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


# Question
Title: Player doesn't move smoothly, when trying to follow position between cursor and player
When my player moves, moving the camera looks like the camera is teleporting to the player, and then after loading teleporting again. I want to make it move smoothly.

When the camera is following the player position, it is moving smoothly.

Camera following code:

```
private void Update()
{
    Vector3 position = GetFollowingPoint();
    position = new Vector3(
        Mathf.Clamp(position.x,
                    Bounds.bounds.min.x + Camera.orthographicSize * Screen.width / Screen.height,
                    Bounds.bounds.max.x - Camera.orthographicSize * Screen.width / Screen.height),
        Mathf.Clamp(position.y,
                    Bounds.bounds.min.y + Camera.orthographicSize,
                    Bounds.bounds.max.y - Camera.orthographicSize),
                    transform.position.z);

    transform.position = position;
}

```

GetFollowingPoint():

```
return Player.transform.position + (cursor.transform.position - Player.transform.position) / 3;

```

Player movement: rigidbody.velocity = Vector in FixedUpdate(), Input with Input.GetKey() and Vector += Vector2.up/down/left/right.

Interpolation in Rigidbody set to Interpolate.

# Answer
The problem lies with the call of `transform.position = position;`

When you assign your new position directly to the transform of the object, you are hard-setting the position. You have to do what is called "Interpolation" which calculates an appropriate point between the current position and the destination you want it to approach. This smoothes out the movement per frame to a more reasonable amount.

The call you want to make is `Vector3.MoveTowards(_current_position, _new_position, _speed);`

You can see an example in the Unity Manual for Vector3.MoveTowards
> 1 votes

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


# Question
Title: What is the purpose of the macro UNITY_EDITOR?
I found on a tips guide in Unity that I can do:

```
#if UNITY_EDITOR
do_something()
#endif

```

And `do_something()` will only be executed on Unity editor. Even more, when I build the game, that section of the code won't be compiled.

I found that as something very interesting, I thought it could be useful for example to use it on DrawGizmos methods since they can only be used on Unity Editor, and you don't need them on a finished product.

What has it been designed for? Is there anything bad that could come from using it?

# Answer
For one game I created a level editor which didn't run in the editor but was actually integrated into the game itself. It was able to save levels as assets in the project directory. This required to reference classes from the `UnityEditor` namespace. But if you use such classes, then your game only runs in the editor and you can no longer build it for distributeion.

By using the `#if UNITY_EDITOR` preprocessor directive I was able to dummy out the map editor specific code and was again able to build my game without sacrificing the map editor.

> Is there anything bad that could come from using it?

Yes.

You now have a codebase which intentionally works differently in the editor than it works in the build. That means you need to do a lot more testing to make sure that your game still works on your target platform. Testing your builds is something you should be doing in regular intervals anyway. But the more you use platform-dependent code, the more likely it gets that you run into problems you can only reproduce in the build. And in that case you have a lot less tools available to troubleshoot the problem.
> 6 votes

# Answer
these are called Preprocessor Tags and used for Platform Dependant Compilation. It is a feature of `C#` and Unity has its own directives (see here).

They are very useful and I use them quite a lot. There are various use-cases for them, especially if you are developping cross-platform (e.g. android and ios).

For instance, I use them when implementing Ads or InAppPurchases on mobile.

```
    private void InitializeUnityAds()
    {
#if UNITY_ANDROID
        string gameId = "2969998";
#elif UNITY_IOS
        string gameId = "2969999";
#else
        string gameId = "";
#endif
        Advertisement.Initialize(gameId, TestMode);
    }

```

(the `#elif` is not a typo, it's the syntax)

But I've also used it to exclude Editor code which is placed on a non-editor class (which may be a code smell, but still). Editor code cannot be built into a release and Unity will throw an error. Placing it in preprocessor tags will strip them from the build, but allow you to use the functionality inside the Unity Editor.
> 6 votes

# Answer
Pre-processor defines like UNITY\_EDITOR can be used to include or remove code from a file.

Before a file is compiled a it is "pre-processed." Code that falls between a preprocessor block like #if UNITY\_EDITOR will get removed from your source code if UNITY\_EDITOR is undefined.

UNITY\_EDITOR is only defined when you run your game from within the editor. When you make a stand alone build of your game UNITY\_EDITOR is not defined and any editor code for debugging, and development is removed.
> 3 votes

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


# Question
Title: how to set the first color of the list in the sprite
```
public List<SpriteRenderer> spritebox = new List<SpriteRenderer>();
public List<Color> colorbox = new List<Color>();

void Start() {
    var renderer = GetComponent<SpriteRenderer>();
    colorbox.Add(renderer.color);//I did so, except that it sends the color of the sprite to the list and in the last slot

    spritebox = GetComponent<SpriteRenderer>();
    colorbox = spritebox.color;//I did that too but it did not work

}

```

I'm trying to make the first color of the list in case the element 0 send the color to the sprite,would have any tips to help me?

# Answer
> 0 votes
In arrays and C# lists (which are wrappers for arrays that allow dynamic resizing) you should access elements by index in square brackets.

Examples:

This will get the first color from `colorbox` and store it in variable `color`:
`Color color = colorbox[0];`

This will assign color `color` to the first `SpriteRenderer` from `spritebox`:
`spritebox[0].color = color;`

You can put a variable or an expression inside brackets.

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


title: How do I warp the player?

text:
# Question
Title: How do I warp the player?
I'm new to unity, and I have two problems.

1. I need to make an invisible area so that, when touched, the player warps back to the start.
2. I need to make a cube that's when touched, it takes the player to a place that shows the player that they won.

# Answer
> 1 votes
These can both be accomplished using Unity's box colliders.

1. First, Create your cube object. Expand the box collider options in the inspector and select 'Is Trigger.' Now object will no longer just collide with the object, they will pass through it and your code can then detect the collision.
2. Next, add a script to your trigger cube. Click the 'add component' button at the foot of the inspector and click the 'new script' option and name it whatever you like.
3. Add the OnTriggerEnter method to execute code when the object collides with the box collider. Then you can warp the player using this code where you replace x, y, and z with the actual coordinates you want the player to be moved to.

```
    public class <your script name> : MonoBehaviour
    {
        // OnTriggerEnter is called when your rigid body enters the cube
        void OnTriggerEnter(Collider other) {
            // Transform (move) player's position to x, y, and z (Remember to set these values)
            Transform.position = new Vector3(x, y, z);
        }
    }

```

Now you just need to make two of these. One that takes the player to the end goal, and one that takes them back to the start.

One final note, make sure any game object you want to collide with these triggers have a Rigid Body **or else it will not trigger the script**

---
Tags: unity
---


# Question
Title: Unity Menu navigation using keyboard/controller input?
I am trying to create a character stats menu that uses keyboard/controller input to navigate between options instead of the mouse. I have not found any tutorials for this kind of UI navigation.

In this way, pressing "Up"/"Down" will highlight the closest button above/below the current selection, and pressing "Left"/"Right" will highlight the closest button to the left/right of the current selection.

This is how console menus, especially for popular JRPG's, worked. Two example images of what I am talking about:

In this top-level menu, only the 8 options in the upper right are selectable, although not all options are necessarily present when the game begins. The finger-pointer icon is used to highlight a button:

This is the Equip menu. Equipable items are pushed into this menu as they are collected and can be scrolled through with the cursor. If the user presses "left", the cursor will jump to whichever character's valid equipment slot is closest:

Could anyone explain (briefly or otherwise) how to make a menu like this?

WIP: The hand cursor does not move yet. It is supposed to snap to highlighted buttons.

# Answer
Use `Input.GetKeyDown(KeyCode.DownArrow)` and `Input.GetKeyDown(KeyCode.UpArrow)` to be able to tell when the user is going up and down the list. Then have an int to keep track of which option the user is on. To visually show the user what option they are on you can do something such as changing the color of the text.

This script will allow you to use the up and down arrow on some text options. It will highlight the currently selected option by changing it's color to white. I left out the gamepad support for going up and down, however, if that is something you need then this should help you out: http://wiki.unity3d.com/index.php?title=Xbox360Controller

```
using UnityEngine;
using UnityEngine.UI;

public class menu : MonoBehaviour {

    public Text option1;
    public Text option2;
    public Text option3;

    private int numberOfOptions = 3;

    private int selectedOption;

    // Use this for initialization
    void Start () {
        selectedOption = 1;
        option1.color = new Color32(255, 255, 255, 255);
        option2.color = new Color32(0, 0, 0, 255);
        option3.color = new Color32(0, 0, 0, 255);
    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKeyDown(KeyCode.DownArrow) /*|| Controller input*/)
        { //Input telling it to go up or down.
            selectedOption += 1;
            if (selectedOption > numberOfOptions) //If at end of list go back to top
            {
                selectedOption = 1;
            }

            option1.color = new Color32(0, 0, 0, 255); //Make sure all others will be black (or do any visual you want to use to indicate this)
            option2.color = new Color32(0, 0, 0, 255);
            option3.color = new Color32(0, 0, 0, 255);

            switch (selectedOption) //Set the visual indicator for which option you are on.
            {
                case 1:
                    option1.color = new Color32(255, 255, 255, 255);
                    break;
                case 2:
                    option2.color = new Color32(255, 255, 255, 255);
                    break;
                case 3:
                    option3.color = new Color32(255, 255, 255, 255);
                    break;
            }
        }

        if (Input.GetKeyDown(KeyCode.UpArrow) /*|| Controller input*/)
        { //Input telling it to go up or down.
            selectedOption -= 1;
            if (selectedOption < 1) //If at end of list go back to top
            {
                selectedOption = numberOfOptions;
            }

            option1.color = new Color32(0, 0, 0, 255); //Make sure all others will be black (or do any visual you want to use to indicate this)
            option2.color = new Color32(0, 0, 0, 255);
            option3.color = new Color32(0, 0, 0, 255);

            switch (selectedOption) //Set the visual indicator for which option you are on.
            {
                case 1:
                    option1.color = new Color32(255, 255, 255, 255);
                    break;
                case 2:
                    option2.color = new Color32(255, 255, 255, 255);
                    break;
                case 3:
                    option3.color = new Color32(255, 255, 255, 255);
                    break;
            }
        }

        if (Input.GetKeyDown(KeyCode.Return) ||  Input.GetKeyDown("joystick button 0")){
            Debug.Log("Picked: " + selectedOption); //For testing as the switch statment does nothing right now.

            switch (selectedOption) //Set the visual indicator for which option you are on.
            {
                case 1:
                    /*Do option one*/
                    break;
                case 2:
                    /*Do option two*/
                    break;
                case 3:
                    /*Do option two*/
                    break;
            }
        }
    }
}

```

Be sure to attach your menu options to the script like so:

This script is not perfect and there is a lot you can do to optimize and clean it up but this should give you the idea of how this is done and will work fine.

**With Pointer**

Add `public Image pointer;` and link the pointer in the scene. You can update the position of this using `pointer.transform.position = new Vector3(/*PUT X VALUE OF POINTER LOCATION HERE */, option1.transform.position.y);` and replace the `/*PUT X VALUE OF POINTER LOCATION HERE */` comment with the x position (as they are all lined with the same x).

If you need the x value to change (such as for the quit option) you can manually put it in for the option in the switch statement or you can replace where the comment is hard coded to get the start of the text/button.

Here is how it would look implemented into the above code.

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

public class menu : MonoBehaviour {

    public Image pointer;

    public Text option1;
    public Text option2;
    public Text option3;

    private int numberOfOptions = 3;

    private int selectedOption;

    // Use this for initialization
    void Start () {
        selectedOption = 1;
        option1.color = new Color32(255, 255, 255, 255);
        option2.color = new Color32(0, 0, 0, 255);
        option3.color = new Color32(0, 0, 0, 255);

        pointer.transform.position = new Vector3(/*PUT X VALUE OF POINTER LOCATION HERE */, option1.transform.position.y);
    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKeyDown(KeyCode.DownArrow) /*|| Controller input*/)
        { //Input telling it to go up or down.
            selectedOption += 1;
            if (selectedOption > numberOfOptions) //If at end of list go back to top
            {
                selectedOption = 1;
            }

            option1.color = new Color32(0, 0, 0, 255); //Make sure all others will be black (or do any visual you want to use to indicate this)
            option2.color = new Color32(0, 0, 0, 255);
            option3.color = new Color32(0, 0, 0, 255);

            switch (selectedOption) //Set the visual indicator for which option you are on.
            {
                case 1:
                    option1.color = new Color32(255, 255, 255, 255);
                    pointer.transform.position = new Vector3(/*PUT X VALUE OF POINTER LOCATION HERE */, option1.transform.position.y);
                    break;
                case 2:
                    option2.color = new Color32(255, 255, 255, 255);
                    pointer.transform.position = new Vector3(/*PUT X VALUE OF POINTER LOCATION HERE */, option2.transform.position.y);
                    break;
                case 3:
                    option3.color = new Color32(255, 255, 255, 255);
                    pointer.transform.position = new Vector3(/*PUT X VALUE OF POINTER LOCATION HERE */, option3.transform.position.y);
                    break;
            }
        }

        if (Input.GetKeyDown(KeyCode.UpArrow) /*|| Controller input*/)
        { //Input telling it to go up or down.
            selectedOption -= 1;
            if (selectedOption < 1) //If at end of list go back to top
            {
                selectedOption = numberOfOptions;
            }

            option1.color = new Color32(0, 0, 0, 255); //Make sure all others will be black (or do any visual you want to use to indicate this)
            option2.color = new Color32(0, 0, 0, 255);
            option3.color = new Color32(0, 0, 0, 255);

            switch (selectedOption) //Set the visual indicator for which option you are on.
            {
                case 1:
                    option1.color = new Color32(255, 255, 255, 255);
                    pointer.transform.position = new Vector3(/*PUT X VALUE OF POINTER LOCATION HERE */, option1.transform.position.y);
                    break;
                case 2:
                    option2.color = new Color32(255, 255, 255, 255);
                    pointer.transform.position = new Vector3(/*PUT X VALUE OF POINTER LOCATION HERE */, option2.transform.position.y);
                    break;
                case 3:
                    option3.color = new Color32(255, 255, 255, 255);
                    pointer.transform.position = new Vector3(/*PUT X VALUE OF POINTER LOCATION HERE */, option3.transform.position.y);
                    break;
            }
        }

        if (Input.GetKeyDown(KeyCode.Return) ||  Input.GetKeyDown("joystick button 0")){
            Debug.Log("Picked: " + selectedOption); //For testing as the switch statment does nothing right now.

            switch (selectedOption) //Set the visual indicator for which option you are on.
            {
                case 1:
                    /*Do option one*/
                    break;
                case 2:
                    /*Do option two*/
                    break;
                case 3:
                    /*Do option two*/
                    break;
            }
        }
    }
}

```
> 2 votes

---
Tags: unity, gui
---


# Question
Title: UI background animation makes camera render beyond canvas, need fix?
I have a background animation for a menu where I have to make the background larger than the canvas and drag it over it. Even though I am using a panel the same size as the canvas as a mask, this causes the camera to render beyond the canvas. How can I get this same effect while only rendering what's on the canvas?

w/o mask (so you can see how big this background is):

w/ mask:

running in editor (looks good):

running build of the game from executable (camera shows more than it should but nothing was changed):

The camera bounds are fixed to the canvas, as it should be, if I remove the animated background, so that is the major cause.

(BTW, I know the gifs look crappy but the animation is seamless; I just had to crop the gifs to reduce file size.)

Also, you guys might not be able to see, but the tiling pattern has a slight white border where the tiles meet (the sprite it uses is only like 227x227 on "repeat"), does anybody know how to avoid that?

UPDATE @ 1:12am PST: upscaling turd texture to 256x256 eliminates white border, as suggested by **trollingchar**.

# Answer
Maybe the resolution of editor screen differs from build screen. try setting `Render Mode` in `Canvas` component as `Screen Space - Camera` and selecting your UI rendering camera as `Render Camera`.

If still have any issue, Change `UI Scale Mode` in `Canvas Scaler` component from `Constant Pixel Size` to `Scale With Screen Size` and change `Match` depending on what you desire.
> 2 votes

---
Tags: unity, animation, camera, gui
---


# Question
Title: Unity - Blender models/animations showing gaps
As part of a college project, a member of my group has made some simple chests with an open animation. Importing these into Unity though, I instantly noticed there were gaps where the faces should be. After a bit of experimenting, I figured it was because the Normals were facing the wrong way. The outside seemed fixed, but faces were missing when the chest opens during its animation. I'm guessing the inside of the chest will need another layer of faces with the Normals facing the right way...? Though surely this would means having doubles...?

# Answer
> 2 votes
You shouldn't put two faces with inverted normals instead, you have to use a **Double Sided Shader** in unity to show the backfaces too. if it's a custom shader, you can write `Cull Off` in your shader code, if not, you can download one from asset store or google.

You can also make your shader double sided in shader graph like shown in the following image:

There is a `Two Sided` toggle field in shader settings.

---
Tags: unity, models, blender, normals
---


# Question
Title: How to draw a diagonal sine wave line renderer
I'm trying to use a `LineRenderer` component to draw a sine wave from point A to B and I'm using mouse position. However what I did so far is not working as expected, it just draws a sine wave along the x-axis and it's not diagonal.

```
private void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        Vector3 newPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        newPos.z = 0;
        CreatePointMarker(newPos);
        GenerateNewLine();
    }
}

private void CreatePointMarker(Vector3 pointPosition)
{
    Instantiate(linePointPrefab, pointPosition, Quaternion.identity);
}

private void GenerateNewLine()
{
    GameObject[] allPoints = GameObject.FindGameObjectsWithTag("PointMarker");
    Vector3[] allPointPositions = new Vector3[allPoints.Length];
    var pointList = new List<Vector3>();
    for (int i = 0; i < 50; i ++)
    {
        var dir = allPoints[0].transform.position - allPoints[1].transform.position;
        float x = dir.x * i;
        float y = Mathf.Sin(x * Time.time);
        var sine = new Vector3(x, y, 0f);
        var tangentLine = allPoints[0].transform.position + sine;
        pointList.Add(tangentLine);
    }
    SpawnLineGenerator(pointList.ToArray());
}
private void SpawnLineGenerator(Vector3[] linePoints)
{
    GameObject newLineGen = Instantiate(lineGeneratorPrefab);
    LineRenderer lRend = newLineGen.GetComponent<LineRenderer>();

    lRend.positionCount = linePoints.Length;
    lRend.SetPositions(linePoints);
}

```

# Answer
> 4 votes
I simplified your code but the math is the same, hope it helps you:

```
using System.Collections.Generic;
using UnityEngine;
public class SineWaveGenerator : MonoBehaviour
{
    public Transform A;
    public Transform B;
    public int Resolution = 50;
    public Material material;
    public float WaveScale = 1f;

    Camera cam;
    private void Start() {
        cam = Camera.main;
    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Vector3 newPos = cam.ScreenToWorldPoint(Input.mousePosition + cam.transform.forward * 10);
            newPos.z = 0;
            B.position = newPos;
        }
        GenerateLine(); //Moved it out to see the effect of WaveScale and Resolution
    }
    private void GenerateLine()
    {
        // Create or select a line renderer on the current game object
        LineRenderer thisLineRenderer = GetComponent<LineRenderer>();
        if(!thisLineRenderer)
            thisLineRenderer = gameObject.AddComponent<LineRenderer>();

        // set visuals of the line renderer
        thisLineRenderer.material = material;
        thisLineRenderer.startWidth = thisLineRenderer.endWidth = 0.1f;
        thisLineRenderer.startColor = thisLineRenderer.endColor = Color.white;

        // set resolution of the line renderer
        thisLineRenderer.positionCount = Resolution;

        for(int i=0; i<Resolution; i++){
            float Sin, Cos, rotatedX, rotatedY;
            Vector3 dir = i*(B.position - A.position)/ Resolution;

            float X = dir.magnitude;
            float Y = Mathf.Sin(X * WaveScale);

            float angle = Vector3.Angle(dir, Vector3.right) * Mathf.Deg2Rad;
            Sin = Mathf.Sin(angle);
            Cos = Mathf.Cos(angle);

            if(dir.y > Vector3.right.y){
                rotatedX = X * Cos - Y * Sin;
                rotatedY = X * Sin + Y * Cos;
            }else{
                rotatedX = X * Cos + Y * Sin;
                rotatedY = - X * Sin + Y * Cos;
            }

            thisLineRenderer.SetPosition(i, new Vector3(rotatedX, rotatedY, 0f));
        }
    }
}

```

Attach the code to a game object in an empty scene and add 2 more game objects called A and B and put them in the inspector, select default sprite material as your material and you can play with resolution and wave scale in the inspector to see the result.

I rotated the sin function with the `Rotation Matrix`:

https://en.wikipedia.org/wiki/Rotation\_matrix

---
Tags: unity, c#, game-mechanics, splines
---


# Question
Title: Count the number of Vulnerable and Invulnerable crops
I have this code that counts how many GameObjects (crops) in the scene

```
GameObject[] crops;

```

and the code to get the health component of each crops

```
    Health[] health;
    crops = GameObject.FindGameObjectsWithTag("Crop");
    health = new Health[crops.Length];
    for (int i = 0; i < crops.Length; i++)
    {
        health[i] = crops[i].GetComponent<Health>();
    }

```

I can now access the state of these crops using

```
    health[i].Invulnerable //this is a bool from the Health.cs script

```

now I want to count the crops that are Vulnerable and Invulnerable. How can I achieve that? Thanks!

# Answer
> 2 votes
Is there something wrong with a simple `for` loop?

```
int vulnerable = 0;
int invulnerable = 0;
for (int i = 0; i < health.Length; ++i) {
    if (health[i].Invulnerable) {
        invulnerable++;
    }
    else {
        vulnerable++;
    }
}

```

# Answer
> 2 votes
Alternatively, you can use the Linq lambda like so:

```
GameObject[] crops;
int invulnerable_count = 0;
int vulnerable_count = 0;

public void your_function(){
    if(crops != null){
        //List has plenty of nice iteration functions
        invulnerable_count = crops.ToList().Where(crop => isInvulnerable(crop)).Count;
        //since Invulnerable is a boolean, you can subtract to get the complement
        vulnerable_count = crops.Length - invulnerable_count;
    }
}

private boolean isInvulnerable(GameObject crop){
    Health health = crop.GetComponent<Health>();
    return health != null && health.Invulnerable;
}

```

# Answer
> 0 votes
your code is right but as you may know its not opptimized and not the best approach. if the scene is so big finding objects by tag or even layer can be time consuming an heavy even with unity new approach on searching objects.try to add your corps objects to a list in a manager or any singleton class when they are instantiated then just find your corps from that list. it can be much faster and no hiccups.

---
Tags: unity, gameobject, boolean
---


# Question
Title: Unity - SpriteRenderer. Trying to make sprite from code using Texture2d.whitetexture
I have been trying to write a method that fills a rectangle with a color. I've tried it as a new 2D and 3D project just in case, but this gives the same results.

Basically, i want the script to make a new GameObject, give it a SpriteRenderer component and then fill the given rectangle with the given color.

I have tried to work from the Unity docs and other sources of info, but no matter how much I look around, this now looks correct to me but doesnt work.

The result (as pictured) shows the new object with the sprite renderer and even shows the right size (there are blue 'corner' icons in the scene view I can see but no sprite or rectangle of any kind.

```
using UnityEngine;

public class GameBoard : MonoBehaviour
{
    const ushort cellCount_x = 10;
    const ushort cellCount_y = 24; // only 20 will be visible to player
    const ushort cellsize = 50;

    GameObject testBlock;
    SpriteRenderer testBlockRen;

    private void Start()
    {
        testBlock = new GameObject();
        testBlockRen = testBlock.AddComponent<SpriteRenderer>();
        testBlockRen.sprite = CreateRectSprite(new Rect(0, 0, cellsize, cellsize), Color.red);
    }

    Sprite CreateRectSprite(Rect rect, Color color)
    {
        Texture2D tex = Texture2D.whiteTexture;
        tex.SetPixel(0, 0, color);
        tex.Resize((int)rect.width, (int)rect.height);
        Sprite sprite = Sprite.Create(tex, rect, Vector2.zero);
        return sprite;
    }
}
```

By the way: I have made sure the camera 'z' is less than 0 (it's -10). And the camera is centred where the sprite is supposed to appear.

Note: I can get a sprite to render fine if I create a texture in gimp and then use Resources.Load() . But I am trying to create the sprite using no source texture whatsoever (other than Texture2d.whitetexture)

# Answer
> 1 votes
You can make sprite with code by using `Sprite.Create`

> https://docs.unity3d.com/ScriptReference/Sprite.Create.html
>
> Sprite.Create creates a new Sprite which can be used in game applications. A texture needs to be loaded and assigned to Create in order to control how the new Sprite will look. In the script example below a new Sprite is displayed when the button is pressed. The new sprite is created in Start.

red rectangle

```
using UnityEngine;

public class SimpleRectangle: MonoBehaviour
{
    private Sprite mySprite;
    private SpriteRenderer sr;
    public Color color = Color.red;

    void Awake()
    {
        sr = GetComponent<SpriteRenderer>();
        sr.color = color;

        transform.position = new Vector3(1.5f, 1.5f, 0.0f);
    }

    void Start()
    {
        Texture2D tex = new Texture2D(500,250);
        mySprite = Sprite.Create(tex, new Rect(0.0f, 0.0f, tex.width, tex.height), new Vector2(0.5f, 0.5f), 100.0f);
        sr.sprite = mySprite;
    }
}

```

another example , simple checker texture with code: try to change height and width in editor

```
using UnityEngine;

[ExecuteInEditMode]
public class SimpleChecker: MonoBehaviour
{
    [Range(1,10)]
    public int height = 10,width = 10;

    private void Update() {
    Texture2D texture = new Texture2D(128, 128);
    GetComponent<SpriteRenderer>().sprite = Sprite.Create(CreateTexture(texture), new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100.0f);

    }
    public Texture2D CreateTexture(Texture2D texture){

        for (int y = 0; y < texture.height; y++)
        {
            for (int x = 0; x < texture.width; x++)
            {
                Color color = (x/height % 2 + y/width % 2 ) == 1 ? Color.white : Color.black;
                texture.SetPixel(x, y, color);
            }
        }
        texture.Apply();
    return texture;
    }
}

```

# Update

your code didn't work because you forgot to use `tex.Apply();`

```
using UnityEngine;

public class GameBoard : MonoBehaviour
{
  const ushort cellCount_x = 10;
    const ushort cellCount_y = 24; // only 20 will be visible to player
    const ushort cellsize = 50;

    GameObject testBlock;
    SpriteRenderer testBlockRen;

    private void Start()
    {
        testBlock = new GameObject();
        testBlockRen = testBlock.AddComponent<SpriteRenderer>();
        testBlockRen.sprite = CreateRectSprite(new Rect(0, 0, cellsize, cellsize),Color.red);
    }

    Sprite CreateRectSprite(Rect rect,Color color)
    {
        Texture2D tex = Texture2D.whiteTexture;
        tex.Resize((int)rect.width, (int)rect.height);
        for (int x = 0; x < (int)rect.width; x++){
             for (int y = 0; y < rect.height; y++){
                 tex.SetPixel(x, y, color);
             }
         }
        tex.Apply();
        Sprite sprite = Sprite.Create(tex, rect, Vector2.zero);
        return sprite;
    }
}

```

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


# Question
Title: What is the connection between these LibGDX concepts?
In LibGDX, what is the connection between these concepts: stage, camera, viewport, batch (spritebatch), projection matrix, tiledmap?

Currently my game has

**3 stages:**

* UI stage
* entity stage
* tiledmap stage

**2 cameras:**

* hud camera (for UI)
* map camera (for map)

**2 batches:**

* spritebatch for rendering particles
* batch from the tiled map renderer (used in map and entity stage)

**3 viewports:**

* for entity stage
* for UI stage
* for tiled map stage

I am very confused at this point at how all these components connect. My whole game works, except when I resize my main menu screen, the particles in my next screen get drawn in the wrong position. Meaning that the resize information does not reach the particle drawer.

I feel like the reason I am having a lot of trouble debugging it, is because I don't understand well enough how they relate to each other.

Can anyone help me clarifying this structure?

# Answer
> 0 votes
I'll try to explain this based on my own experience so this might be not correct. For more trusted information check this out in case you didn't know: https://github.com/libgdx/libgdx/wiki/Scene2d

**Stage**

Imagine the stage as the container holding all your elements that need to be rendered/updated.

**Camera**

Determines what parts of the stage are visible (based on the viewport)

**Batches**

Are responsible for rendering everything (doing all the needed open gl stuff)

**Viewport**

Manages the camera and controls how the stage is displayed on the screen (aspect ratio etc)

To help you with your problem some screenshots / code pieces would be useful but sounds like after resizing the new viewport dimensions are not send to the batch rendering the particles

I hope this helped a bit but again for better information take a look in the wiki.

Blakk

---
Tags: java, libgdx
---


# Question
Title: Algorithm for a dense crowd of people who avoid the player?
I want to make a game like this. When player moves other humans will move too. And other humans will push people around. Are there any algorithm for this ? How can i solve this very efficient way ?

I dont want to check all objects at scene with loop. And i dont want people overlap.

Video:

https://youtu.be/V5ZMicq05LQ

# Answer
> 4 votes
If you create a grid of weights, you can have each person's AI be fairly simple and go towards the lowest weighted location nearby.

I kind of imagine this as representations of gravity, but instead of making pits and attracting, they're forming mountains and repelling. They're all smelly and want to move away from each other.

Since we want the player to have plenty of space and override pretty much everything else, they can have ridiculously large values to ensure the AI people move away.

When calculating where each person should move, they should ignore their own aura they're adding to the grid *(probably by subtracting their values or something)*.

This should work well and not be too noticeable it's a grid if you make the grid small enough.

# Answer
> 0 votes
It's very simple, you can measure the distance of the humans to the player, if it's below a certain threshold, move them away from the player. The vector for the last step is simply the position of the human minus the position of the player.

# Answer
> 0 votes
its a good question but its too general. avoidance can be compeletly different in different scenarios and styles of game. first of all if you are not good in math, learn about vector math. but the most basic scenario is when you are moving forward, the other object as enemy or civilian people should move aside(let or right). so you have a forward vector. to find movement direction of avoiding object, just calculate the Perpendicular vector of player forward movement. next step is to check if there is open space in left o right or add some random direction for reality or randomness.

---
Tags: algorithm, ai
---


title: Using grids from a different script

text:
# Question
Title: Using grids from a different script
I suspect there is a very simple answer to this one but I have been scratching my head trying to figure it out for a while.

I have this piece of code that works fine. It effectively adds the location of the children of my GameObject to a grid array.

```
  public void AddToGrid()
       {
        Transform[,] grid = new Transform[totalGridWidth, totalGridHeight];
        foreach (Transform children in transform)
           {
               int roundedX = Mathf.RoundToInt(children.transform.position.x);
               int roundedY = Mathf.RoundToInt(children.transform.position.y);
               grid[roundedX, roundedY] = children;

           }
       }

```

However, I need to modify it so that rather than taking the children of the GameObject that runs this script - I need it of the children of a different GameObject.

i.e. this script sits on GameObject A, however I need to change it to grab the position of the children on GameObject B. I don't want to simply add this script also to B as there is other stuff in the script that won't make any sense and I need to keep the array in A.

I suspect (hope) there is an easy answer here, but am struggling to figure it out. Thanks for the assistance.

# Answer
Yes, there's an easy way. See how in line 4 above you are using the lowercase transform? That is a shortcut in the Monobehavior class that is a convenience to give you a reference to the transform of the GameObject you are located on.

The equivalent more-explicit line would be:

```
foreach (Transform children in this.transform)

```

So what you actually want to do, inspect the transform and hence the children of ANOTHER game object, coincidentally that very same "transform" shortcut exists on a GameObject as well, also as a convenience.

If you declare a public GameObject, like so:

```
public GameObject TheOtherThingIWannaGetChildrenFrom;

```

And drag the target object into that field in your inspector, then you can recode line 4 above to do it to that new object, like so:

```
foreach (Transform children in TheOtherThingIWannaGetChildrenFrom.transform)

```

You could also modify the function to accept an arbitrary GameObject and operate on it that way.

That entire mechanism is kind of how scripts and GameObjects and Transforms and hierarchies and everything is connected up in Unity, so check it out and jump right in!
> 1 votes

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


# Question
Title: Font rendering, how do you align glyphs of a font?
I'm trying to render text quad using texture generate by `BitmapFontWriter` of `libgdx`. For the font I can get `size`, `PaddingTop`, `PaddingRight`, `PaddingBottom`, `PaddingLeft`, `LineHeight`, `CapHeight`, `Baseline`, `Ascent`, `Descent`.

For each glyph I can get `u`, `v`, `width`, `height`, `x offset`, `y offset`, `x advance`

The chars rendered are `OPQZ[\\]^_`abcdefg你好,`. If I just render the quad. I get:

`Q`, `g` and the ```are definitely incorrect. The brackets and notdef are a little large. The only thing that I find meaningful for me is `y offset`. If I shift the quad with it, I get:

`Q` is not changed at all. `g` gets slightly better. Lots of them get worse.

# Answer
> 0 votes
Will answer by linking to a few resources, but effectively, you need to create an offset for each font. By the looks of it, you aren't quite doing the maths right on each glyph, which means that they will look like they are jumping up and down.

To work out the correct size, you will need to know the base height of the font (the reference height) then subtract the height of the glyph from reference to get the offset value. intended position = actual position + offset. In this case the offsety = (lineheight - y offset) or something similar, the xoffset will also be involved

This has been solved a few times by different people, I in particular started with Codehead's Bitmap Font Generator with it's file format and loaders to guide you through -\> http://www.codehead.co.uk/cbfg/

Or you can go more complex and start using Heiro's SDF font generator which has the file format included. See here -\> https://github.com/libgdx/libgdx/wiki/Hiero

The links I have posted above will help you understand some of the principals of loading in font sheets. But in general, each glyph could be represented by a container class.

Good luck

---
Tags: fonts
---


title: Alternate Answer for collision problem?

text:
# Question
Title: Alternate Answer for collision problem?
I am building a top-down game in unity which works well. In this game, I have a 3D object (red cube) which a player has to control and there are other cubes like white, yellow and black cubes which spawns in the interval of 5 seconds. In each 5 seconds, prefabs of these three villain cubes instantiates and follows the player.

There is also a text that says yellow, black and white and changes constantly. For instance, the text is now white and it changes to black within certain interval of time and changes to white in certain interval of time (this is random) So, the **player has to collide with the cube same as the the text otherwise the player will die.**

Now, the problem is I have built the game just fine and can't get to deactivate player when the player hits the unrelated cube.

The script is(for instantiating:-)

```
public class ColorChecker : MonoBehaviour {
    public GameObject[] text;
    public int hold;

    public float startTime;
    public float startTimebtwSpawn;
    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        startTimebtwSpawn -= Time.deltaTime;
        if (startTimebtwSpawn <= 0) {
            startTimebtwSpawn = startTime;
            hold = Random.Range (1, 4);
        }
        if (hold == 1) {
            text [0].SetActive (true);
            text [1].SetActive (false);
            text [2].SetActive (false);

        } else if (hold == 2) {
            text [1].SetActive (true);
            text [0].SetActive (false);
            text [2].SetActive (false);

        } else if (hold == 3) {
            text [2].SetActive (true);
            text [0].SetActive (false);
            text [1].SetActive (false);
        }
}
}

```

The script for destroying the object is:-

```
public class DestroyCubes : MonoBehaviour {
    public ColorChecker colorchecker;
    // Use this for initialization
    void Start () {

    }

    void OnCollisionEnter (Collision col){
        if (colorchecker.hold == 1 && col.gameObject.tag == "CubicMonster1") {
            Destroy (col.gameObject);
        } else if (colorchecker.hold == 2 && col.gameObject.tag == "CubicMonster2") {

            Destroy (col.gameObject);
        } else if (col.gameObject.tag == "CubicMonster3" && colorchecker.hold == 3) {
            Destroy (col.gameObject);
        }

    }
}

```

Now, I can obviously check if it is unrelated by a long code like

```
if (colorchecker.hold == 1 && col.gameObject.tag == "CubicMonster2" && so on){

Destroy (gameObject);

}

```

Rather than writing a long if statement like this, Is there a better way that I can handle this ?

# Answer
> 0 votes
You can create a component like the next one:

```
public class EnemyType: MonoBehaviour
{
    public int TypeOfEnemy;
}

```

Of course it can be made far better. For example instead of "int TypeOfEnemy" it can be an enum or even a list of enums. The whole idea is to avoid the poor Unity tags and make your own (multi)tag component and to be able to compare it with the numbers you use with ColorChecker.hold. But we will leave that beautifying for a homework :)

Anyway, assign that component to your enemies.

Then in your DestroyCubes component you can simply:

```
void OnCollisionEnter (Collision col)
{
    if (colorchecker.hold == col.gameObject.GetComponent<EnemyType>().TypeOfEnemy)
    {
         Destroy(col.gameObject);
    }
}

```

BTW I would instead move(and rework) the DestroyCubes from being part of the player to be a component on the colored cubes. Every game entity better be responsible for its own stuff and not one entity controlling the other. It's far easier to manage when things start to grow.

Finally I would have a code on a player component that "kills" the player:

```
if (colorchecker.hold != col.gameObject.GetComponent<EnemyType>().TypeOfEnemy)
{
    Destroy(gameObject);
}

```

Note: I have not tested the code and it may contain some error.

P.S. It is good idea in general to avoid having hardcoded strings in your code, i.e. not have string literals like "some text". Imagine you decide to rename some of your tags, then your code will suddenly stop working correctly and you would never know that because there would be no error displayed. One day you will just notice your cubes no longer disappearing and you would have no idea why.

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


# Question
Title: Efficient Algorithm for the boundary of a set of tiles
I have a grid of tiles of a known finite size that forms a map. Some of the tiles inside the map are put into a set known as a territory. This territory is connected, but nothing is known about its shape. Most of the time it would be a fairly regular blob, but it could be very elongated in one direction, and it could potentially even have holes. I am interested in finding the (outer) border of the territory.

That is, I want a list of all the tiles that touch one of the tiles in the territory without itself being in the territory. What is an efficient way of finding this?

For extra difficulty, it happens that my tiles are hexes, but I suspect this doesn't make too much difference, each tile is still labelled with an integer x and y coordinate and, given a tile, I can easily find its neighbors. Below are a few examples: The black is the territory, and the blue the border I want to find.  This in itself, is not a difficult problem, One simple algorithm for this, in pseudo-python, is:

```
def find_border_of_territory(territory):
    border = []
    for tile in territory:
        for neighbor in tile.neighbors():
            if neighbor not in territory and neighbor not in border:
                border.add(neighbor)

```

However this is slow and I would like something better. I have an O(n) loop over the territory, another loop (a short one, but still) over all the neighbors, and then I have to check membership over two lists, one of which is of size n. That gives an awful scaling of O(n^2). I can reduce that to O(n) by using sets instead of lists for border and territory so that membership is fast to check, but it still isn't great. I expect there to be many cases where the territory is large but the border is small due to a simple area vs line scaling. For example if the territory is a hex of radius 5, it is of size 91 but the border is only of size 36.

Can anyone propose something better?

**Edit:**

To answer some of the questions below. The territory can range in size, from about 20 to 100 or so. The set of tiles forming the territory is an attribute of an object, and it's this object that needs a set of all the border tiles.

Initially the territory is created as a block, and then mostly gains tiles one by one. In this case, it is true that the fastest way is just to keep a set of the border and only update it on the tile that is gained. Occasionally a big change to the territory might happen - so it will need to be recalculated fully then.

I'm now of the opinion that doing a simple border-finding algorithm is the best solution. The only additional complexity this raises is to ensure that the border is recalculated every single time it might need to be, but not more than that. I'm pretty confident that this can be done reliably in my current framework.

As for timing, in my current code I have some routines that need to check every tile of the territory . Not every turn, but on creation and occasionally afterwards. That takes over 50% of the running time of my suit of test code even though it is a very small part of the complete program. I was therefore keen to minimise any repeats. HOWEVER, the test code involves a lot more object creation than a normal running of the program (naturally), so I realise this might not be very relevant.

# Answer
> 11 votes
Finding an algorithm is usually best done with a data structure that makes the algorithm easy.

In this case, your territory.

The territory should be an unordered (O(1) hash) set of borders and elements.

Whenever you add an element to the territory, you iterate over adjacent tiles and see if they should be a border tile; in this case, they are a border tile if they are not an element tile.

Whenever you subtract an element from the territory, you ensure that its adjacent tiles are still in the territory, and you see if yourself should become a border tile. If you need this to be fast, have the border tiles keep track of their "adjacent count".

This takes O(1) work whenever you add or remove a tile to or from a territory. Visiting the border takes O(border length). So long as you want to know "what the border is" significantly more often than you add/remove elements from the territory, this should win.

# Answer
> 9 votes
If you need to find edges of holes in the middle of your territory too, then your linear in the area of the territory bound is the best we can do. Any tile on the interior could potentially be a hole that we need to count, so we need to look at every tile in the area bounded by the territory's outline at least once to be sure we've found all the holes.

But if you're only concerned with finding the outer border (not interior holes), then we can do this a bit more efficiently:

1. Find one edge separating your territory. You can do this by...

* (if you know at least one territory tile, and know that you have exactly one connected territory blob on your map)

    ...beginning at an arbitrary tile in your territory, and moving toward the closest edge of your map. As you do so, remember the last edge where you transitioned from a territory tile to a non-territory tile. Once you hit the edge of the map, this remembered edge is your starting edge.

    This scan is linear in the diameter of the map.
    * or (if you don't know where any of your territory tiles are in advance, or your map may contain several disconnected territories)

    ...beginning at an edge of your map, scan along each row until you hit a terrain tile. The last edge you crossed from non-terrain to terrain is your starting edge.

    This scan could be at worst linear in the *area* of the map (quadratic in its diameter), but if you have any bounds to constrain your search (say, you know the territory almost always crosses the middle rows) you can improve this worst-case behaviour.
2. Beginning at your starting edge found in step 1, follow it around the perimeter of your terrain, adding each non-terrain tile on the outside to your border collection, until you return back to the starting edge.

This edge-following step is linear in the *perimeter* of your terrain outline, rather than its area. The downside is that the code is more complicated because you need to account for each kind of turn the edge can take, and avoid double-counting border tiles at inlets.

If your examples are representative of your real data size to within a couple orders of magnitude, then myself I'd go for the naive area search - it will still be blazingly fast on such a small number of tiles, and is substantially simpler to write, understand, and maintain (typically leading to fewer bugs!)

# Answer
> 7 votes
**Notice**: Whether or not a tile is on the boundary only depends on it and its neighbors.

Because of that:

* It is easy to run this query lazily. For instance: You do not need to search for the boundary on the whole map, only on what is visible.
* It is easy to run this query in parallel. In fact, I could image some shader code that does this. And if you need it for something other that visualization, you can render to a texture and use that.
* If a tile changes, the boundary only changes locally, which means you do not need to compute the whole thing again.

You can also pre compute the boundary. That is, if you are populating the hex, you can decide if a tile is boundary at that moment. That means that:

* If you use a loop to populate the grid, and it is the same you use to decide what is a boundary.
* If you start with an empty grid and pick tiles to change, then you can update the boundary locally.

---

Do not use a list for the boundary. Use a set if you really have to (*I do not know what do you want the boundary for.*). However, if you make whatever a tile is boundary or not an attribute of the tile then you do not have to go to another data structure to check.

# Answer
> 2 votes
Move your area up one tile, then up-right, then down right, etc.. Afterwards remove the original area.

Merging all six sets should be O(n), sorting O(n.log(n)), set difference O(n). If the original tiles are stored in some sorted format, the merged set can be sorted in O(n) too.

I don't think there is an algorithm with less than O(n), since you need to access each tile at least once.

# Answer
> 1 votes
I just wrote a blog post about how to do this. This uses the first method that @DMGregory mentioned starting with an edge cell and marching around the perimeter. It's in C# instead of Python but should be pretty easy to adapt.

https://dillonshook.com/hex-city-borders/

# Answer
> 0 votes
ORIGINAL POST :

I can't comment on this site so I'll try to answer with a pseudocode algorithm.

You know every single territory has at most six neighbors that are part of the boundary. For every tile in the territory, add the six neighboring tiles to a potential border list. Then subtract every tile in the territory from the border and you are left with only the border tiles. It will work best if you use an unordered set to store each list. Hope I was helpful.

EDIT There are much more effective ways than simple iteration. As I tried to state in my (now deleted) answer below, you can achieve O(1) in the best cases and O(n) in the worst case.

Adding a tile to a territory O(1) - O(N) :

In the case of no neighbors, you simply create a new territory.

In the case of one neighbor you add the new tile to the existing territory.

In the case of 5 or 6 neighbors you know it is all connected, so you add the new tile to the existing territory. These are all O(1) operations, and updating the new border territories is O(1) as well, since it is a simple merge of one set with another.

In the case of 2, 3, or 4 neighboring territories you may have to merge up to 3 unique territories. This is O(N) on combined territory size.

Removing a tile from a territory O(1) - O(N) :

With zero neighbors erase the territory. O(1)

With one neighbor remove the tile from the territory. O(1)

With two or more neighbors, up to 3 new territories may be created. This is O(N).

I spent my spare time over the last few weeks developing a demonstration program that is a simple hex based territory game. Try to raise your income by placing territories next to each other. 3 players, Red, Green, and Blue compete to generate the most revenue by strategically placing tiles on a limited game field.

You can download the game here (in .7z format) hex.7z

Simple mouse control LMB places a tile (can only place where highlighted with hover). Score on top, income on bottom. See if you can come up with an effective strategy.

Code can be found here :

Eagle/EagleTest

To build from source code you need Eagle and Allegro 5. Both build with cmake. Hex game builds with CB project currently.

Turn those downvotes upside down. :)

---
Tags: python, maps, hexagonal-grid, graph
---


# Question
Title: Return the success or failure of an event occurring with a given percentage C#
I'm working on a skill based system that does away with the concept of RNG despite player skill. Basically, my concept is this:

A player's chance to make something is based on `their knowledge in the materials they're working with + their experience in making the actual item *(# of times they've successfully made it)* + their experience in the actual activity *(in this case, crafting)*`. All values have a numerical value and the percentage of making it is determined later.

So given the following:

```
PlayerSkillRating = 15 + 0 + 20 = 35;
ChanceToMake = (PlayerSkillRating / Item Skill Required To Make) * 100

```

Longsword

```
Quality      Item Skill Required To Make
Bad          15
Low          15 * 2.5 = 37.5
Good         37.5 * 2.5 = 93.75
High         93.75 * 2.5 = 234.4
Great        234.4 * 2.5 = 586
Excellent    586 * 2.5 = 1465
Master       1465 * 5 = 7324.22
Perfect      7324.22 * 5 = 36621.1

```

Plugging in the formula, we get the chance this particular player can make the item at each quality tier successfully.

```
Bad = 233%
Low = 93.3%
Good = 37.3%
High = 15%
Great = 6%
Excellent = 2.4%
Master = 0.5%
Perfect = 0.1%

```

So a player who has never crafted a longsword before, will still have a high chance to make a low quality item and a decent chance to make a good quality item because they know the materials they're working with and they have experience in the skill itself.

If the chance to make a quality item exceeds 100%, that tier basically 'drops off', meaning the player will never make that tier item again\*(it basically resets to 0)\*.

So I have this pseudo code, I know how I want it to work, but my question is, how do I implement it in code? Do I still generate a random number when the skill is used and compare it to the player's chance to make percentage?

```
OnSkillUse()
{
    var randNum = new Random();

    if((ChanceToMake / 100) > randNum)
        return "Failure";
    return "Success";
}

```

From what I understand, this is similar to how it's done today and I'm still basing the entire system on RNG to figure out whether it was successful or not.

Is there a better way of accomplishing this since I basically already know the probability of making the item every time the player uses the skill? Or am I simply just repeating a system that's already being used?

# Answer
> 1 votes
Well, you need a RNG (Random Number Generator) that works with the probabilities you come up with. *Yeah, you are not getting rid of RNG, in fact, what you describe is not unheard of in gaming.*

What you want is take a randomic: a random variable with uniform distribution in the range (0, 1\]. And then mold the randomic to the probability distribution you want.

You should be able to get a randomic in virtually every platform. You will rarely be programming in a platform that does not have a library with a suitable random. And if there isn't (GLSL comes to mind), then go ahead an implement some kind of congruential random number generator (I suggest the Linear congruential generator, for its ease of implementation, unless you have more specific requirements).

**Notes**:

* I am assuming we do not need a Cryptographically secure random.
* Yes, this is all "pseudorandom". I just didn't want to write "pseudo" everytime. It is meaningless knowing the context.

---

What I will describe here is inteded for a discrete list of values with their probabilities.

Usually the first step is to normalize the distribution. The total probability of all the cases must be 100%.

However, you have an special requirement that a porbability beyond 100% will become 0%, so let us start there...

```
Input distribution:

    Bad = 233%
    Low = 93.3%
    Good = 37.3%
    High = 15%
    Great = 6%
    Excellent = 2.4%
    Master = 0.5%
    Perfect = 0.1%

Adjusted distribution:

    Bad = 0%
    Low = 93.3%
    Good = 37.3%
    High = 15%
    Great = 6%
    Excellent = 2.4%
    Master = 0.5%
    Perfect = 0.1%

```

To normalize, we will add the probabilities and divide

```
Adjusted distribution:

    Bad = 0%
    Low = 93.3%
    Good = 37.3%
    High = 15%
    Great = 6%
    Excellent = 2.4%
    Master = 0.5%
    Perfect = 0.1%

Total: 154.6%

Normalized distribution:

    Bad = 0 / 154.6 = 0%
    Low = 93.3 / 154.6 = 60.349288486%
    Good = 37.3 / 154.6 = 24.126778784%
    High = 15 / 154.6 = 9.702457956%
    Great = 6 / 154.6 = 3.880983182%
    Excellent = 2.4 / 154.6 = 1.552393273%
    Master = 0.5 / 154.6 = 0.323415265%
    Perfect = 0.1 / 154.6 = 0.064683053%

 Total: 99.999999999% (100% within rounding error)

```

**Notes**

* This would work even if the input values were not meant to be probabilities, they are just weights.
* Scaling all input values by a given factor will not affect this result.
* We have to decide where will the rounding error be chocked to. I will suggest to leave the error on the last category (which is what happens naturally with this method).
* If you can work with arbitrary precision or with fractional number, you can do this without rounding error. It is usually not worth it.

The next step is to figure out the accumulated distribution:

```
Normalized distribution:

    Bad = 0%
    Low = 60.349288486%
    Good = 24.126778784%
    High = 9.702457956%
    Great = 3.880983182%
    Excellent = 1.552393273%
    Master = 0.323415265%
    Perfect = 0.064683053%

Accumulated distribution:

    Bad = 0%
    Low = 60.349288486% + 0% = 60.349288486%
    Good = 24.126778784% + 60.349288486% = 84.47606727%
    High = 9.702457956% + 84.47606727% = 94.178525226%
    Great = 3.880983182% + 94.178525226% = 98.059508408%
    Excellent = 1.552393273% + 98.059508408% = 99.611901681%
    Master = 0.323415265% + 99.611901681% = 99.935316946%
    Perfect = 0.064683053% + 99.935316946% = 99.999999999%

```

*In case that wasn't clear, we are adding the previous total each step, so that we are accumulating the values. We should get 100% (within rounding error) at the end.*

Finally, we take our randomic and choose...

*pseudo code:*

```
var randomic = rand();
if (randomic < 0%)
{
    return "Bad";
}
if (randomic < 60.349288486%)
{
    return "Low";
}
if (randomic < 84.47606727%)
{
    return "Good";
}
//...
if (randomic < 99.935316946%)
{
    return "Master";
}
return "Perfect"; // <- no check, sleight of hand on the rounding error

```

You can imagine how you could turn your data into a dictionary, and then the code above would become a loop. And of course the randomic is in the range \[0, 1), so you need your probabilities in the range \[0, 1). I leave that to you.

---

**Addendum 1**: I totally ignored the fact that we are talking C#. `Random.NextDouble` is where you get your randomic. And to store the distribution, an `IEnumerable` of tuples or `KeyValuePair` will do.

---

**Addendum 2**: On your code:

```
OnSkillUse()
{
    var randNum = new Random();

    if((ChanceToMake / 100) > randNum)
        return "Failure";
    return "Success";
}

```

*By the way, that is not valid C#*

Flip the conditional:

```
OnSkillUse()
{
    var randNum = new Random();

    if(randNum < (ChanceToMake / 100))
        return "Failure";
    return "Success";
}

```

That is the same thing I have above - assuming `randNum` is the randomic - except you only have two cases: "Success" and "Failure". The accumulated probability of "Failure" is only the probability of "Failure" because there are no more cases before.

By the way, note that if `ChanceToMake` is 0, then `randNum` will never be less than `ChanceToMake` (if `ChanceToMake` is 0 then `ChanceToMake / 100` will never be more than `randNum`)... which means that it will never enter the if, therfore it will always lead to "Success". *I do not think you meant to say that a `ChanceToMake` of 0 means certain "Success". I'm guessing you have "Success" and "Failure" inverted.*

---

**Addendum 3**

> Is there a better way of accomplishing this since I basically already know the probability of making the item every time the player uses the skill?

If you know the the *probability* \- yet not know the result - then You need a RNG.

---

We could talk about entropy. You see, your RNG uses a seed, which should be a source of entropy. When you say `new Random()` you are leaving that to the system, however you could take control of the seed. Knowing the seed, your random number generator will be completely predictable (hence, "pseudorandom")... so, one option is to seed it with something with less entropy ("less random").

*For what you say, you do not want to depend on player skill, so that beyond the question.*

You could even have your own source of entropy and feed it from a server to the client.

See Using seeds for rng. A reliable way of saving bandwidth?.

---
Tags: c#, game-design, game-mechanics
---


# Question
Title: How to detect collision direction in Phaser 3
Please consider this scene. Developed using PhaserJS 3.

I want to make the slider move left when the player touches the right hand side of it, and move right when the player touches the left hand side of it.

This is the code I'm currently using in the collision callback to decide what to do:

```
  hitSlider: function (player, slider) {
    // ...
      if (player.body.touching.left) {
        slider_actions.moveSliderLeft(slider)
      } else if (player.body.touching.right) {
        slider_actions.moveSliderRight(slider);
      }
  // ...
  }

```

This works in most cases, EXCEPT that it doesn't check if the player is touching the slider on the left, just that they're touching something on the left.

My screenshot contains an example. If the player stands on top of the slider, and walks left, they are both colliding with the sider and touching something on the left. So the slider moves left.

How can I detect the direction of the collision event itself instead?

# Answer
> 1 votes
Since the slider can only collide with the player and the player can collide with many other objects, it would be best to do your checks on the slider(s) instead of the player.

This means that your code will look something like so:

```
  hitSlider: function (player, slider) {
    // ...
      if (slider.body.touching.left) {
        slider_actions.moveSliderLeft(slider)
      } else if (slider.body.touching.right) {
        slider_actions.moveSliderRight(slider);
      }
  // ...
  }

```

---
Tags: collision-detection, phaser
---


# Question
Title: Behaviour of containers in Phaser 3 framework
I don't understand the behaviour of containers in this example:

Phaser example

The part I don't unerstand is line 41. Why is lastContainer assigned to newContainer? In line 40, newContainer is added as a child of lastContainer; my intuition would be that the effect of line 40 is so that the rotations can be performed on lastContainer (or, rather, on containerTails, which seems to contain four nested container structures, one for each arm), and propagated to its children.

It makes no sense to me that the variable containing the parent container should be assigned to its own child; how does that not overwrite the nested structure of containers, effectively removing the parent container from the picture?

# Answer
> 0 votes
No no, see the lastContainer variable is stored outside of the loop (line 23). So what the code is doing from line 39 is creating a new container, adding it to the previous container and setting the new container as the lastContainer this way the next container can add itself to the newContainer.

    var lastContainer;

    // ...

    for (var index = 0; index < count; ++index) {
        // In an if statement
        {
            // Create the new container (only if this is false index === 0
            var newContainer = this.make.container({x: image.width, y: 0, add: false});

            // Now add it to the previous container
            lastContainer.add(newContainer);

            // And set the lastContainer to the new container so that the loop does update the same container over and over again
            lastContainer = newContainer;
        }
        // ...
    }
```

---
Tags: javascript, phaser
---


title: Scene graph or just plain container?

text:
# Question
Title: Scene graph or just plain container?
I'm trying to understand if it makes sense to call what I have a scene graph or not.

Im doing an asteroid-like game, where all objects in the game are described in world space coordinates (an asteroid will be at X 50, Y 50 and it wont have objects orbiting, the player avatar is at X 100, Y 100 and it does'nt have a turret rotating the base of the ship. Objects are all described in world space, not in relationship to each other cause it just dose'nt make any sense).

For clarity (on why I will be mentioning a view matrix and a projection matrix bellow) - this is a 3D game with 3D objects in it, but the camera is locked facing one direction.

What I have is an object with a set of vectors containing all the objects visible in the scene. To me, this is still a scene graph - it just happens to be a flat graph where everything in the scene is a single node, not a child of a parent. The scene graph also stores the projection and view matrix, as these are common to all objects scene (the view and projection matrix are static, only world space coordinates are updated). One could consider this view matrix as a transformation "node" that will be applied to all the children in the scene graph I guess.

So my question is - am I stretching it calling this a a "Scene Graph" and should I use another name for it?

# Answer
> 1 votes
In your case it is not a scene graph because you don't have object hierarchies, e.g. your objects are stored in flat lists and not in a tree like datastructure. Now flat lists are in mathematical sense some kind of graph, but in a scene graph you can have a node with more than two links, whereby in a list node only the information about the previous node and next node can be known. Even more your objects transformations are not interrelated or dependent on another.

Remove your one object (the root container) and you end up with a set of vertices and a flat list of objects which you can easily iterate through inside a simple while render loop.

Please don't call the list implementation a graph in your tutorial because that can mislead people into thinking wrong about the concepts of local space and world space! Best example for a transformation graph is solar system or legs connected to torso, e.g. minecraft characters.

---
Tags: terminology, scene-graph
---


# Question
Title: How to set up Azure Spatial Anchors with Unity Android project?
I'm building an AR app in which I wish to use Microsoft's Azure and it's web service Spatial Anchors. I cannot seem to get the sample demo, which I downloaded from https://github.com/Azure/azure-spatial-anchors-samples, to work for storing spatial anchors on the external server.

Following their tutorial I can create the Azure account, set up the resource group and individual Spatial Anchors resource. However, in the Unity project, there is a config file called 'AzureSpatialAnchorsDemoConfig' which requires that you specify an account id(I have this), a primary key(i also have this), and a base sharing url: which is what I am struggling to find and is what I assume is the cause of being unable to store my anchors to the cloud.

This is a snippet from the tutorial that I'm having issues with, if I fill in the address in my web browser I can't even find that ip.

> In the Inspector pane, enter the Sharing Anchors Service url (from your ASP.NET web app Azure deployment) as the value for Base Sharing Url, replacing index.html with api/anchors. It should look like this:
>
> https://\<app\_name\>.azurewebsites.net/api/anchors.

# Answer
According to another tutorial, based on the same git repo's sample, after the creation of the resource, there also needs to be an Azure Cosmos DB resource to create the base sharing URL.

For anyone reading this that got stuck this is where you get the three values you need for demo config:

1. Under your azure portal, locate the spatial anchors resource from your dashboard
2. Account ID is located on the right hand side of the overview pane
3. Primary key is in the keys page.
4. Deploy an Azure Cosmos DB from the spatial anchors sample solution, using https://docs.microsoft.com/en-us/azure/spatial-anchors/tutorials/tutorial-share-anchors-across-devices
5. The base sharing URL is https://\<\>.azurewebsites.net/api/anchors

Where \<\> is the name of the web service you deployed with the tutorial in 4
> 1 votes

---
Tags: unity, c#, android, augmented-reality
---


title: PyGame Inconsistent Framerate

text:
# Question
Title: PyGame Inconsistent Framerate
This is the first game I have tried to make on PyGame, and I have followed the PyGame Primer tutorial (https://realpython.com/pygame-a-primer/) to do so. I'm practically done, but when I run the game, it runs incredibly slowly when I provide no input. when I spam-click an arrow key, the game will run smoothly, but if I don't do anything or hold down a key, it will run at \< 10 FPS. How could I change it so that it will run consistently regardless of input? This is my code:

```
import pygame
import random
from pygame.locals import *

FPS = 25
fpsclock = pygame.time.Clock()

class Player(pygame.sprite.Sprite):
    def __init__(self):
        super(Player, self).__init__()
        self.image = pygame.image.load('Images/Star-Rider.png').convert()
        self.image.set_colorkey((0, 0, 0), RLEACCEL)
        self.rect = self.image.get_rect()

    def update(self, pressed_keys):
        if pressed_keys[K_UP]:
            self.rect.move_ip(0, -20)
        if pressed_keys[K_DOWN]:
            self.rect.move_ip(0, 20)
        if pressed_keys[K_LEFT]:
            self.rect.move_ip(-20, 0)
        if pressed_keys[K_RIGHT]:
            self.rect.move_ip(20, 0)

        if self.rect.left < 0:
            self.rect.left = 0
        elif self.rect.right > 800:
            self.rect.right = 800
        if self.rect.top < 0:
            self.rect.top = 0
        elif self.rect.bottom > 600:
            self.rect.bottom = 600

class Enemy(pygame.sprite.Sprite):
    def __init__(self):
        super(Enemy, self).__init__()
        self.image = pygame.image.load('Images/Hand-Projectile.png').convert()
        self.image.set_colorkey((0, 0, 0), RLEACCEL)
        self.rect = self.image.get_rect(center=(random.randint(820, 900), random.randint(0,600)))
        self.speed = random.randint(5,20)

    def update(self):
        self.rect.move_ip(-self.speed, 0)
        if self.rect.right < 0:
            self.kill

pygame.init()

screen = pygame.display.set_mode((800,600))

ADDENEMY = pygame.USEREVENT + 1
pygame.time.set_timer(ADDENEMY, 1000)

player = Player()

enemies = pygame.sprite.Group()
all_sprites = pygame.sprite.Group()
all_sprites.add(player)

running = True

while running:
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                running = False
        elif event.type == QUIT:
            running = False
        elif event.type == ADDENEMY:
            new_enemy = Enemy()
            enemies.add(new_enemy)
            all_sprites.add(new_enemy)

        pressed_keys = pygame.key.get_pressed()

        if pressed_keys:
            player.update(pressed_keys)

        enemies.update()

        screen.fill((135,206,250))

            screen.blit(entity.image, entity.rect)

        if pygame.sprite.spritecollideany(player, enemies):
            player.kill()

        pygame.display.flip()

        fpsclock.tick(FPS)

```

Thank you for taking the time to read this! Any advice would be much appreciated!

# Answer
Your logic is uuh, ordered incorrectly. You're doing

* While the game is running
    + For each event
        - Handle the event
        - Render a frame

Your logic should be

* While the game is running
    + For each event
        - Handle the event
    + Render a frame

Indentation matters in python. You probably want to unindent everything from pressed\_keys and down.
> 2 votes

---
Tags: pygame
---


title: Select Neighboring X or Y Tiles

text:
# Question
Title: Select Neighboring X or Y Tiles
I have a randomly generated set of tiles, and I am trying to select neighboring x or y tiles to perform functions on them based on if they are a certain value of tile, like so:

```
var IsometricMap = new Object();

      IsometricMap.tiles = [
        // "images/dirt.png",
        "images/dirtHigh.png",      // 0
        "images/grass.png",         // 1
        "images/water.png",         // 2
        "images/waterBeachCornerEast.png",  // 3
        "images/waterBeachCornerNorth.png", // 4
        "images/waterBeachCornerSouth.png", // 5
        "images/waterBeachCornerWest.png",  // 6
        "images/waterBeachEast.png",    // 7
        "images/waterBeachNorth.png",   // 8
        "images/waterBeachSouth.png",   // 9
        "images/waterBeachWest.png"]

var blockcount = 10;

    let generate_row = _=> Array(blockcount).fill().map(_=>Math.floor(Math.random()*3));
     IsometricMap.map = Array(blockcount).fill().map(generate_row);

    console.log(IsometricMap.map);

    for(let x = 0; x < IsometricMap.map.length; x++){

        for(let y = 0; y < IsometricMap.map.length; y++){

            if ((IsometricMap.map[x-1][y]) == 2) {
            //IF THE TILE IS WATER, DO ALL THIS:

            alert("SUCCESSFULLY SELECTED THE " + IsometricMap.map[x-1][y] + " TILE");

            //DONE WITH WATER TILES
            }

        }

    }

```

So far this is not yielding any results, its as if it cant find the tile I am trying to specify. Is there something wrong with my scope here?

# Answer
> 0 votes
Could it be that the program is throwing an exception for an out of range index? On the first pass of the loop, x-1 evaluates to -1.

Also I think Math.Random() returns values less than 1.0, so if you multiply by 3 you may only get values 0..2 out.

# Answer
> 0 votes
Yea, this can be very annoying at times, but you have to check that the `[x - 1]` position exists. So your `if` statement becomes:

```
    if (!!IsometricMap.map[x - 1] && IsometricMap.map[x - 1][y] == 2) {
        // Place your alert here
    }

```

---
Tags: javascript, html5, html-canvas, isometric
---


# Question
Title: Why are meshes limited to 65k indices or uint16 in most game engines?
Why are most game engines like unity limiting their meshes to 65k indices by default, or enforcing to use **uint16** as the default datatype for indexbuffers?

I know that its better for performance to use uint16 indexbuffers, but I think there might be more reasons, because webGL 1.0 specification allows **only** uint16 vertexbuffers. I know that it's possible to use uint32 indexbuffers in webGL if the "OES\_element\_index\_uint" extension is available in webGL 1.0 devices.

How big is the performance impact when using uint32 indexbuffers instead of uint16 indexbuffers? I think the only difference is in the memory bandwidth during the initial upload of the indices and should not matter much during runtime.

# Answer
> 2 votes
I think DMGregory has answered part of this, timing test of 16 vs 32 definitely needs to be done. BUT, the performance is also dependent on the needs of your scene also. The 65536 indice limitation does mean that now you may need to deal with multiple objects to composite a more complicated \> 65536 indice model. Which means different different calculations and logic to handle various components. Which means switching out buffers for different buffers, which all impacts the time to render.

It's not a simple 16 is smaller and faster, this only holds true in the purest of examples. If like myself, you use \> 65536 indices then you may feel the trade off is worth it in terms of performance. The other thing, modern GPUs are using more the 32 bit aligned space, meaning that in some cases you feed in a 16 bit, its converted to a 32 bit index anyway.

At the end of the day, benchmark it and understand that your purest test may not reflect the real world needs you have.

---
Tags: index-buffer
---