# Question
Title: How to tap a square and draw "Cross (X)" on tic-tac-toe for iibGdx
I am having much difficulty trying to figure out how to draw the cross in the square of where the person just touched.

I have made a class called 'CellPositions', by making 9 invisible squares around my board Texture; Example of CellOne...

```
public CellOne cellOne;

public CellPositions(Board board) {
    load(board);
}

public void load (Board board) {
    cellOne = new CellOne(board);

}

public class CellOne {
    public Rectangle square = new Rectangle();

    public CellOne (Board board) {

        square.x = board.boardRect.x;
        square.y = (board.boardRect.y + board.boardRect.height) - (board.boardRect.height / 3);
        square.width = board.boardRect.width / 3;
        square.height = board.boardRect.height / 3;
    }
}

```

I have made a 'Controller' class to handle my input and a 'Renderer' class to handle rendering images to the game.

What I want to do is draw the "Cross" on the square the person touched. For eg. if he/she touches the first square - cellOne - how would i render my "cross" to that specific square.

I've tried making a class called "Cross" and made the x and y coordinates Gdx.input.getX() and Gdx.input.getY(), but the 'cross' was not in the square, but intersecting the lines.

Please help! I am trying to get used to libGdx by making a simple game like tic-tac-toe, but it's really not so simple when trying to draw your cross on a certain square.

Here is my board class for further info

```
private TextureRegion reg;
public Rectangle boardRect;

public Board () {
    init();
}

private void init () {
    reg = Assets.instance.board.boardRegion;
    boardRect = new Rectangle();
    boardRect.set((Constants.SCREEN_WIDTH / 2) - (340 / 2), 15,
            340, 340);

}

public void render (SpriteBatch batch) {
    batch.draw(reg, boardRect.x, boardRect.y,
            boardRect.width, boardRect.height);
}

```

I have made my screen width and height be 480x480.

# Answer
> 0 votes
I have a multiple-step solution for you:

1. Change your cell classes to be more generic. You currently have one class for each cell position (I assume from your code). You should just have one `Cell` class that you re-use for every cell.

```
public class Cell {
    public Rectangle square;

    public Cell (float x, float y, float width, float height) {
        square = new Rectangle(x, y, width, height);
    }
}

```
2. Set the position of the cell when you create it (probably in your `init()` method of your board class).

```
float width = boardRect.width / 3f;
float height = boardRect.height / 3f;

for(int y = 0; y < 3; y++) {
    for(int x = 0; x < 3; x++) {
        // Create new cell att appropriate position and
        // add it to a list of all 9 cells.
        // You might need to offset the x & y position by your boards
        // position as well. In that case just do:
        // x * width + boardRect.x
        // y * height + boardRect.y
        cells.add(new Cell(x * width, y * height, width, height);
    }
}

```
3. When you click you search thorough all cells and see which one you clicked in.

```
int mouseX = Gdx.input.getX();
int mouseY = Gdx.input.getY();

for(Cell cell : cells) {
    if(cell.square.contains(mouseX, mouseY) {
        // We pressed in this tile. Draw image here and size
        // it to be the same size and in the same position
        // as the cell.
        float x = cell.square.x;
        float y = cell.square.y;
        float width = cell.square.width;
        float height = cell.square.height;
        // Draw image at (x, y) with size (width, height).
        // If you're using sprites do this:
        crossImage.setBounds(x, y, width, height);
        // If you're using textures do this:
        batch.draw(crossImage, x, y, width, height);
    }
}

```

# Answer
> 0 votes
<sub>(alternative to my first answer)</sub>

You can round the clicked position to get which cell you clicked in.

```
int mouseX = Gdx.input.getX();
int mouseY = Gdx.input.getY();

// Move coordinates so we are relative to origin (0, 0).
// This makes calculations easier.
mouseX -= boardRect.x;
mouseY -= boardRect.y;

// Divide x and y by cell width and height.
mouseX /= (boardRect.width / 3);
mouseY /= (boardRect.height / 3);

// Check if you clicked outside the board.
if(mouseX > 2 || mouseY > 2) {
    // You clicked outside of the board. Do something.
}

// mouseX & mouseY is now in the range [0, 2].
// Multiply by cell width and height again.
mouseX *= (boardRect.width / 3);
mouseY *= (boardRect.height / 3);

// Move coordinates back so they match with the board position.
mouseX += boardRect.x;
mouseY += boardRect.y;

// mouseX & mouseY should now be in the correct position.
batch.draw(crossImage, mouseX, mouseY, boardRect.width / 3, boardRect.height / 3);

```

This might be a little confusing but this works because of integer division rounding (see this short wolfram alpha explaination). Basically after integer division the decimals (if they are present) are truncated. So for example `5 / 2 = 2.5` but since it is integer division decimals get removed so the result is `2`.

---
Tags: libgdx
---


# Question
Title: OnMouseDown() and Collision not working for game object created within another game objects script
I have created a game object (`Brick`) and added a script (`BrickScript`) to it. Within this script I create a Window game object if a certain condition is satisfied. Please see code below:

```
if (hasWindow) {
    if (window == null) {
        var size = gameObject.GetComponent<SpriteRenderer>().bounds.size;
        window = (GameObject)Instantiate (Resources.Load ("Prefabs/OtherPrefabs/Window"),
            new Vector3 (transform.position.x + 0.5 * size.x,
                        transform.position.y + 0.5f * size.y,
                        transform.position.z),
            Quaternion.Identity));
        window.name = gameObject.name + "Window";
    }
}

```

The `Brick` and `window` game objects actually overlap a bit. I realized that when `hasWindow = true` (the window is created) the condition in the code below is not satisfied and other game objects don't collide with the `Brick`. But when `hasWindow = false` (the window is not created), everything seems to work well. How can I solve this?

```
void OnMouseDown () {
    if (Input.GetMouseButtonDown(0)) {
        Debug.Log ("touch down");
        hasBeenTouched = true;
    }
}

```

# Answer
It looks like the overlapping is causing your issue since the collider will be already colliding with the window. You can solve this problem a couple ways. you can create a new layer and set the window object to that layer. then in physics 2d settings you can set the collision matrix to not collide with each other. Or you can possibly set the windows z position to be in a spot that wont collide.
> 1 votes

---
Tags: unity
---


title: Smooth movement in a tile based game

text:
# Question
Title: Smooth movement in a tile based game
How can we make our character move smoothly across tiles? He moves tile by tile, but that looks unprofessional. In addition, when you hold down the arrow keys he zips across the screen. How can we prevent that from happening?

# Answer
Smooth movement can be achieved in a number of ways. And it really depends on what kind of movement you want to allow.

* Movement still restricted to tiles. This type is the easiest for doing things like collision detection and other movement checks. For this type of movement you'll simply be interpolating the position over time as you transition between tiles. It can be as simple as adding something like the following to the update loop.

Pseudo code:

```
 if(GetDistance(position, targetposition) > minDistance) {
     position = MoveTowards(position, targetposition, deltatime);
 }

```

Where `MoveTowards` just takes the current position and adds a portion of the distance between it and the target position.

* Movement is not restricted to tiles. This gets a lot more tricky to implement. Essentially with this method you just store the position and update it via velocity. That is, change in position over time.

Holding down the arrow keys to move characters can also be implemented in a few different ways. Likely what you're doing is something like:

```
if(keydown(left))
   tilePosition.X--;

```

This would indeed cause the character to zip across the screen. Since you'd be updating the position many times per second. A bit better way to implement this would be to add a delay. Something like

```
if(keydown(left)) {
    if(leftKeyHeldTimer > movementDelay) {
        tilePosition.X--;
        leftKeyHeldTimer = 0;
    } else {
        leftKeyHeldTimer+= deltaTime;
    }
}

```

This will add a delay timer and only update the tile position when the `movementDelay` value has been met.
> 6 votes

# Answer
I can identify two issues. The first related to smooth movement and the second is related to the character zipping off screen.

To create a smooth movement, you can use a technique called Linear Interpolation or (LERP) to smooth movement. Basically how it works is between your starting point and end point you calculate a set of decreasingly small distances to emulate smooth movement and slowing down as the endpoint is nearly reached.

The simplest example of this function would be:

```
//point1 is the current position, will be starting position on first call
//point2 is the target position
//epsilon is the % of the distance between current and target you want
//to cover per game physics loop (a fixed realworld time based loop).
//The smaller the % the "smoother" the motion.

float lerp(float point1, float point2, float epsilon)
{
    return point1 + epsilon * (point2 - point1);
}

```

As the character moves closer to point 2 it will gradually slow down. Note though they will never actually touch point 2 but get infinitely close. You would need to correct this and if the player is less than an infinitely small distance from point 2 we can consider the player being on point 2.

The second issue you mentioned is related to your character flying offscreen. This is a result of the input being read every game loop refresh combined with the instant movement between tiles.

Ideally to solve this, in your code you need to decide

1. How much realworld time it would take for the character to move from point 1 to point 2.
2. Set your Lerp to run between point 1 and two over this duration
3. Read input again once point 2 has been reached to decide where to go
> 0 votes

---
Tags: java, movement, swing
---


# Question
Title: iOS: controlling size of assets designed in Cinema 4D when importing into Xcode?
A designer provided the attached two DAE files created in Cinema 4D. The characters in these DAE files are to be integrated into an `iOS` game.

Both assets are of comparable size inside of `Cinema 4D`. Both DAE files were produced with the same export process.

Importing the DAE files into a SceneKit scene, however, produces different results.

`Chango.dae` imports at a "normal" size with a bounding box of `~3x4x3`.

`Tiki.dae` imports at a huge size with a bounding box of `~155x325x140`. Its dimensions inside Cinema 4D is `122x283x142`.

Questions:

1) How do you make sure assets "fit" into a `SceneKit` scene? Are you supposed to scale down assets with the "scale" property of the `SCNNode`, or are you supposed to ask the designer to make the asset of a certain size? In `SpriteKit` and `UIKit`, this is straightforward. The asset size correlates directly to its screen size (e.g., `20x20` icon takes about that much screen space depending on resolution). However, what's the analog for `SceneKit`? If you want an asset to fit into a `1x1x1` `SCNNode`, what size do you ask the designer to make the asset?

2) If your asset is too large for a scene, how do you scale it down? In `UIKit`, for instance, you can scale an image to fit a `UIView` with something like `ScaleAspectFit`. There doesn't seem to be an analog for a `SCNNode`. Using the `SCNNode`'s `scale` property changes the appearance, but doesn't change the asset's bounding box. And even changing the appearance isn't precise. For instance, with `Tiki.dae`, the original height of the asset (as shown by the bounding box) is 324.36. If you set the Y-scale to 0.01, however, the height doesn't become ~3.24. It becomes smaller than 3, which you can prove by fitting it comfortably within a sphere of height 3 (radius of 1.5).

# Answer
You can always click on your `.dae` in the `Scene Graph View`, then adjust the scale in the Node Inspector. I'm using the same workflow from `C4D` to `Xcode` and I have to shrink things down to something absurdly small like `x: 0.0001 y: 0.0001 z: 0.0001` so there must be something I'm missing too.
> 1 votes

---
Tags: ios, assets, xcode, collada, cinema-4d
---


# Question
Title: Unity - Array of custom class with a superclass using generics does not show in the inspector
I want to create 2 classes for Scriptable Object: `Weapon` and `Armor`. Because both have similar functionality, I made a base class for both of them.

```
using UnityEngine;

public abstract class Gear<T> : ScriptableObject{

    public int price;
    public int level;
    public Sprite image;

    [Header("Levels List")]
    public T[] levels;

    public T CurrentLevel() {
        return this.levels[this.level];
    }

    public T NextLevel() {
        return this.levels[this.level + 1];
    }

    public bool UpgradesLeft() {
        return this.level + 1 < this.levels.Length;
    }

    public void Reset() {
        this.level = 0;
    }

    public bool Upgrade() {
        if (!this.UpgradesLeft()) return false;
        this.level++;
        return true;
    }
}

[System.Serializable]
public abstract class StatsLevel {
    public int price;
}

```

Both weapons and armors have the properties in common like they all have a price, they all have a Sprite Image, and so on... and more importantly they all have an array of Stat Levels. Meaning that every armor or weapon can have different levels, and depending on their level, the stats will be different. For that I used Generics.

So when I created the Armor, I did it this way:

```
using UnityEngine;

public enum ArmorStat { Low, Med, High, Super }

[CreateAssetMenu(fileName = "Armor", menuName = "NARG/Armor", order = 1)]
public class Armor : Gear<ArmorStatsLevel> {
    // Armor custom logic
}

[System.Serializable]
public class ArmorStatsLevel : StatsLevel {
    public int weight;
    public ArmorStat blunt, slash, range;
}

```

in this class I define the stats unique to an Armor. Up to here everything looks peachy. But the issue comes with the Inspector:

As you can see, the inspector is not showing the array with the list of Stats on different levels, and I after a lot of research, I think it has to do with the Generics. If instead of unifying the common code between Armor and Weapon on the Base, I duplicate it each subclass, the Array is shown without problem.

How could I make it so that the array information is shown in the inspector?

# Answer
> 1 votes
I've never worked with Unity assets so maybe I'm totally wrong here, but after pasting your code in an empty project and creating an `Armor` instance via `Assets/Create/NARG/Armor`, the inspector showed me everything:

Tested on Unity 5.6.1f1

---
Tags: unity
---


title: OpenTK Terrain - Triangle strip issue

text:
# Question
Title: OpenTK Terrain - Triangle strip issue
I'm currently trying to render terrain in an OpenGL application I'm making (using OpenTK in C#). Something really odd is happening and I'm not sure why.

Here is the code I use to load my terrain from a heightmap (Yes I know setting up indices the way I am at the moment is silly, but it's just so I can use the mesh renderer class I made). I render the terrain using Triangle Strips.

```
    public Terrain(string heightmapFile)
    {
        if (!File.Exists(heightmapFile)) throw new FileNotFoundException("File not found at path '" + heightmapFile + "'");

        using (var bitmap = new Bitmap(heightmapFile))
        {
            var vertices = new List<Vertex>();
            var indices = new List<int>();

            int index = 0;

            for (int y = 0; y < bitmap.Height - 1; y++)
            {
                for (int x = 0; x < bitmap.Width; x++)
                {
                    float z = bitmap.GetPixel(x, y).R / 127.5f - 1.0f;
                    float z1 = bitmap.GetPixel(x, y + 1).R / 127.5f - 1.0f;

                    vertices.Add(new Vertex(new Vector3(x, y, z)));
                    vertices.Add(new Vertex(new Vector3(x, y + 1, z1)));

                    indices.Add(index);

                    index++;
                }
            }

            AddVertices(vertices.ToArray(), indices.ToArray());
        }
    }

```

Here is the result:

What's going on here? What am I doing wrong?

# Answer
> 1 votes
You need to start a new triangle strip per y value.

If I remember right, a triangle strip draws one new triangle for each vertex you give it, reusing the previous two. It's trying to make one very long triangle strip by wrapping the end of row y==0 over to the beginning of row y==1. The vertex at y == 1, x == 0 is using the last two vertices from when y == 0, x == bitmap.Width - 1 and y == 0, x == bitmap.Width - 2.

You can either make a separate triangle strip object (probably easiest), or you can use primitive restart. Or maybe switch to non-strip triangles.

---
Tags: c#, opengl, opentk
---


# Question
Title: How is Forge Networking able to provide unlimited CCU?
I was wondering how Forge Networking could provide **unlimited** CCU for every user, since it is a **one-time** purchase. Is there something about networking I still do not understand or do they simply own a lot of servers?

# Answer
> 0 votes
My understanding is that Forge Networking doesn't "provide" unlimited CCU - rather, they "allow" it, and ***you*** provide it.

From https://developers.forgepowered.com/, under "What is Forge Networking?":

> You can host servers at no cost with this system. The catch is that you host them all yourself, manage them yourself and so forth.

They also provide tutorials on how to deploy a headless version of your server for self/cloud hosting, here: https://developers.forgepowered.com/Tutorials

I've found no mention anywhere that they provide hosting. I assume they are only mentioning the lack of DAU/CCU limits to address a common question (and, of course, to help sell the asset), not to imply that they are a hosting service without such limits.

---
Tags: unity, multiplayer, server, unity-networking
---


# Question
Title: What direction does directional audio come from for a 2D view?
In a 3D game, it makes sense that stereo balance is based on the angle between your camera direction and the directionto the audio source.

Is 2D audio just "fudge the left-right balance until it sounds good"? Are there games where the audio balance was still character-oriented rather than view oriented (so a character facing south causes stereo balance to be backwards)?

I'd be interested in answers supported by examples where a notable game was played by blind players using audio cues. The only one that comes to mind is Brood War

# Answer
> 5 votes
**The spatial audio should be relative to the camera.**

If you consider it, even in a 3D game, the audio is relative to the camera. Sounds that come from the right side of the screen are heard from the right speaker, and sounds that come from the left side of the screen are heard from the left speaker. It just happens that the avatar is looking in the same direction as the camera. (For example, an FPS with a cutscene that shows your avatar doesn't switch the direction of the audio when viewing your character's front side).

Remember that the reason you're implementing spatial audio is for the player. It would be rather unintuitive to hear a sound coming from your speakers and need to reference the direction the avatar is looking to determine which direction *they* heard it from. The audio is for the human playing the game, not the avatar in the game. With FPS style games, when in first person mode, audio is

The only reason you might implement spatial audio relative to the avatar instead of being relative to the player is if it was specific a game mechanic your game relied on.

---
Tags: 2d, audio, direction
---


# Question
Title: The rotation along z axis is not changing to zero?
Code:

```
function Start(){

  Cursor.lockState=CursorLockMode.Locked;

}

function OnGUI () {

  transform.Rotate(0,Input.GetAxis("Mouse X"),0);
  transform.Rotate(Input.GetAxis("Mouse Y"),0,0);
  transform.rotation.z=0;

}

```

But the rotation along z axis is not changing to zero.

# Answer
First of all, i believe you meant to use Update instead of OnGui;

Since altering a transform's position/rotation have implicity implications in phisics, every time you alter them, there's a bunch of callbacks inside Unity, mainly, OnTransformChanged()/OnRotationChanged(). So, every time you change the transform, do it only once, that's why Unity will not allow you to assign their values individually like this:

```
transform.position = new Vector3(0,0,0); // for example, instead of

transform.position.x = 0;
transform.position.x = 0;
transform.position.x = 0;

```

And you also need to use

```
transform.rotation = Quaternion.Euler (new Vector3 (bla,ble,0) );

```

to change a transforms angle.
> 0 votes

---
Tags: unity, unityscript
---


# Question
Title: Instantiate a prefab on button press and keep it dragged
So far the gameObject is created, but I need to click on the object a second time, in order to start the Drag event. Here's the script where I use the button to spawn a prefab

```
public void SpawnPrefab(Transform prefab)
{
    clicked = false;
    Vector3 mousePosition, targetPosition;
    mousePosition = Input.mousePosition;
    targetPosition=Camera.main.ScreenToWorldPoint(new Vector3(mousePosition.x,mousePosition.y,distance));
    prefab.position=targetPosition;
    if(isAlreadyClicked == false)
    {
        Instantiate(prefab, prefab.transform.position, prefab.transform.rotation);
        isAlreadyClicked = true;
        Debug.Log(clicked);
    }
}

```

I call this Drag event from another script inside the spawned gameObject though

```
void OnMouseDrag()
{
    cursor.setGrab();
    if(this.transform.parent == null || this.transform.parent != null)
    {
        //drag the component
        Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
        Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
        transform.position = curPosition;
        if(this.gameObject.CompareTag("Component"))
        {
            mainCanvas.transform.GetChild(1).gameObject.transform.GetChild(0).gameObject.transform.GetChild(4).gameObject.SetActive(false);
        }
        if(this.gameObject.CompareTag("NewComponent"))
        {
            mainCanvas.transform.GetChild(1).gameObject.transform.GetChild(0).gameObject.transform.GetChild(4).gameObject.SetActive(true);
        }
    }
}

```

Hope it's clear enough. Any ideas? Thanks in advance!

EDIT: So I found out that the SpawnPrefab() only works when mouse button is released. Is there any way I can make the buttons work on mouse pressed?

# Answer
> 1 votes
**When you spawn the element, set the isDragging to true.**

---

```
using UnityEngine;
using UnityEngine.EventSystems;

public class Draggable : MonoBehaviour , IPointerUpHandler, IBeginDragHandler {

    public bool isDragging;

    void Update () {
        if (!isDragging)
            return;
        // Put you dragging logic here
    }

    public void OnBeginDrag(PointerEventData data){
        isDragging = true;
    }

    public void OnPointerUp (PointerEventData data){
        isDragging = false;
    }

}

```

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


title: Unity coroutine vs threads

text:
# Question
Title: Unity coroutine vs threads
Whats the difference between a coroutine and a thread? Are there any advantages of using one over the other?

# Answer
While Coroutines seem to work like threads at first glance, they actually aren't using any multithreading. They are executed sequentially until they `yield`. The engine will check all yielded coroutines as part of its own main loop (at what point exactly depends on the type of `yield`, check this diagram for more information), continue them one after another until their next `yield`, and then proceed with the main loop.

This technique has the advantage that you can use coroutines without the headaches caused by problems with real multithreading. You won't get any deadlocks, race conditions or performance problems caused by context switches, you will be able to debug properly and you don't need to use thread-safe data containers. This is because when a coroutine is being executed, the Unity engine is in a controlled state. It is safe to use most Unity functionality.

With threads, on the other hand, you have absolutely no knowledge about what state the Unity main loop is in at the moment (it might in fact no longer be running at all). So your thread might cause quite a lot of havoc by doing something at a time it isn't supposed to do that thing. **Do not touch any native Unity functionality from a sub-thread**. If you need to communicate between a sub-thread and your main thread, have the thread write to some thread-safe(!) container-object and have a MonoBehaviour read that information during the usual Unity event functions.

The disadvantage of not doing "real" multithreading is that you can not use coroutines to parallelize CPU-intense calculations over multiple CPU cores. You can use them, though, to split a calculation over multiple updates. So instead of freezing your game for one second, you just get a lower average framerate over multiple seconds. But in that case you are responsible to `yield` your coroutine whenever you want to allow Unity to run an update.

Conclusion:

* If you want to use asynchronous execution to express game logic, use coroutines.
* If you want to use asynchronous execution to utilize multiple CPU cores, use threads.
> 31 votes

# Answer
Coroutines are what we in Computer Science call "cooperative multitasking." They are a way for multiple different streams of execution to interleave with eachother cooperatively. In cooperative multitasking one stream of execution has sole undisputed ownership of the CPU until it reaches a `yield`. At that point, Unity (or whatever framework you are using), has the option to switch to a different stream of execution. It then also gets sole undisputed ownership of the CPU until it `yield`s.

Threads are what we call "preemptive multitasking." When you are using threads, the framework reserves the right at *any* time to stop your thread mid-thought and switch over to another thread. It doesn't matter where you are. You can even be stopped part way through writing a variable to memory in some cases!

There are pros and cons for each. The cons of coroutines are probably the easiest to understand. First off, coroutines all execute on a single core. If you have a quad core CPU, coroutines will only use one of the four cores. This simplifies things, but can be a performance issue in some cases. The second con is that you must be aware that any coroutine can stop your entire program simply by refusing to `yield`. This was an issue on Mac OS9, many years ago. OS9 only supported cooperative multitasking, across the entire computer. If one of your program hung, it could halt the computer so fiercely that the OS couldn't even render the text of the error message to let you know what happened!

The pros of coroutines is that they're relatively easy to understand. The errors you have are far more predictable. They also typically call for fewer resources, which can be helpful as you climb up into the 10's of thousands of coroutines or threads. Candid Moon mentioned in the comments that, if you haven't studied threads properly, just stick to coroutines, and they're right. Coroutines are much simpler to work with.

Threads are a different beast entirely. You always have to be on guard against the possibility that another thread may interrupt you *at any time* and mess with your data. Threading libraries provide entire suites of powerful tools to assist you with this, such as mutexes and condition variables which help you tell the OS when it's safe for it to run one of your other threads and when it is unsafe. There's entire courses dedicated to how to use these tools well. One of the famous issues that arises is a "deadlock," which is when two threads both get "stuck" waiting for the other to free some resources. Another issue, which is very important for Unity, is that many libraries (like Unity) are not designed to support calls from multiple threads. You can very easily break your framework if you don't pay attention to which calls are permitted and which ones are forbidden.

The reason for this extra complexity is actually very simple. The preemptive multitasking model is really similar to the *multithreading* model which permits you to not only interrupt other threads, but to actually run threads side-by-side on different cores. This is incredibly powerful, being the only way to really leverage these new quad core and hex code CPUs that are coming out, but opens up pandoras box. The synchronization rules for how to manage this data in a multithreading world are positively brutal. In the C++ world, there's entire articles dedicated to `MEMORY_ORDER_CONSUME` which is one itty-bitty-teeny-weenie corner of multithreading synchronization.

So the cons of threading? Simple: they're hard. You can come across entire classes of bugs you've never seen before. Many are so-called "heisenbugs" that sometimes appear, and then dissapear when you debug them. The tools you are given to deal with these are very powerful, but they're also very low level. They're designed to be efficient on the architectures of modern chips rather than being designed to be easy to use.

However, if you want to use all your CPU power, they're the tool you need. Also, there *are* actually algorithms that are easier to understand in multithreading than they are with coroutines simply because you let the OS handle all the questions of where interruptions can take place.

Candid Moon's comment to stick to coroutines is my recommendation as well. If you do want the power of threads, then commit to it. Go out and *really* learn threads, formally. We've had several decades to figure out how to organize the best way to think about threads so that you get safe reliable repeatable results early, and add performance as you go. For example, all sane courses will teach mutexes before teaching condition variables. All ~~sane~~ courses that cover atomics will fully teach mutexes and condition variables before even mentioning that atomics exist. (Note: there is no such thing as a sane tutorial on atomics.) Try to learn threading piecemeal, and you're begging for a migraine.
> 11 votes

# Answer
In the simplest terms possible...

---

**Threads**

A thread does not decide when it yields, the operating system (the 'OS', e.g. Windows) decides when a thread is yielded. The operating system is almost entirely responsible for scheduling threads, it decides what threads to run, when to run them and for how long.

Additionally a thread might be run synchronously (one thread after another) or asynchronously (different threads running on different CPU cores). The ability to run asynchronously means threads can get more work done in the same amount of time (because the threads literally are doing two things at the same time). Even synchronous threads get lots of work done if the OS is good at scheduling them.

However, this extra processing power comes with side effects. For example, if two threads are trying to access the same resource (e.g. a list) and each thread can be randomly stopped at any point in the code, the second thread's modifications could interfere with the modifications made by the first thread. (See also: Race Conditions and Deadlock.)

Threads are also considered to be 'heavy' because they have a lot of overhead which means there's a considerable time penalty incurred when switching threads.

---

**Coroutines**

Unlike threads, coroutines are completely synchronous, only one coroutine can be running at any point in time. Additionally coroutines get to choose when to yield, and thus can choose to yield at a point in the code that is convinient (e.g. at the end of a loop cycle). This has the advantage of issues like race conditions and deadlocks much easier to avoid, as well as making it easier for coroutines to cooperate with each other.

However this is a major responsibility too, if a coroutine doesn't yield properly it could end up consuming a lot of processor time and it can still cause bugs if it modifies shared resources incorrectly.

Coroutines generally require no context switching and are thus quick to switch in and out of and are quite lightweight.

---

**In Summary:**

Thread:

* Synchronous or Asynchronous
* Yielded by OS
* Yielded randomly
* Heavy

Coroutine:

* Synchronous
* Yields self
* Yields by choice
* Lightweight

The roles of threads and coroutines are very similar, but they differ in how they get the job done which means that each is better suited to different tasks. Threads are best for tasks where they can focus on doing something on their own without being interrupted, then signalling back when they're done. Coroutines are best for tasks that can be done in lots of small steps and tasks that require cooperatively processing data.
> 2 votes

---
Tags: unity
---


title: FBX SDK Colors problem

text:
# Question
Title: FBX SDK Colors problem
I've imported control points, normals, and indices successfully and now i'm trying to import vertex colors, but something is not right. Here's the code:

```
        FbxLayerElementMaterial* pMaterialLayer = layer->GetMaterials();
        int numMatIndices = pMaterialLayer->GetIndexArray().GetCount();

        GLfloat *colors = new GLfloat[numMatIndices * 9];

        for (int i = 0; i <numMatIndices; i++)
        {
            //int matIndex = array->operator[](i);
            int matIndex  = pMaterialLayer->GetIndexArray()[i];

            FbxSurfaceMaterial *smat = mesh->GetNode()->GetMaterial(matIndex);
            if (smat->GetClassId().Is(FbxSurfaceLambert::ClassId))
            {
                FbxSurfaceLambert *lam = (FbxSurfaceLambert*)smat;

                FbxPropertyT<FbxDouble3> p = lam->Diffuse;
                FbxDouble3 info = p.Get();

                for (int j = 0; j < 3; j++)
                {
                    colors[i * 9 + j * 3 + 0] = (GLfloat)info[0];
                    colors[i * 9 + j * 3 + 1] = (GLfloat)info[1];
                    colors[i * 9 + j * 3 + 2] = (GLfloat)info[2];
                }
            }
        }

```

Here's what I exported from max, and what I got in my OpenGL application.

I was inspecting memory dump and all colors are like they should be (in the order material indices were written in fbx file). Three SAME colors for three vertices in one triangle (total nine floats for one triangle). How is it even possible to have different vertex colors in one triangle?

Does it have something to do because I'm using index buffer for drawing vertices? My VertexBufferObject contains vertex positions, normals, indices, and colors. I'm drawing with glDrawElements call.

Can anyone help me with this?

@EDIT For those who asked, here's whole method for importing mesh:

```
bool Mesh::Create(FbxMesh *mesh)
{
    FbxScene *scene = mesh->GetScene();
    FbxAnimEvaluator *eval = scene->GetAnimationEvaluator();
    FbxMatrix transform = eval->GetNodeGlobalTransform(mesh->GetNode());
    glm::mat4x4 glmMat = FbxMatToGlm(transform);

    // *************** VERTEX POSITIONS ***************

    int numVertices = mesh->GetControlPointsCount();
    GLfloat *vertices = new GLfloat[numVertices * 3];
    for (int i = 0; i < numVertices; i++)
    {
        FbxVector4 vec = transform.MultNormalize(mesh->GetControlPointAt(i));

        vertices[i * 3 + 0] = (GLfloat)vec.mData[0];
        vertices[i * 3 + 1] = (GLfloat)vec.mData[1];
        vertices[i * 3 + 2] = (GLfloat)vec.mData[2];
    }

    glGenBuffers(1, &vertexBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)* 3 * numVertices, vertices, GL_STATIC_DRAW);

    delete[] vertices;

    // ****************** INDICES ***************

    numIndices = mesh->GetPolygonVertexCount();
    int *indices = mesh->GetPolygonVertices();

    glGenBuffers(1, &indexBuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(int)* numIndices, indices, GL_STATIC_DRAW);

    delete[] indices;

    // *********** NORMALS *********

    FbxGeometryElementNormal *normalElement = mesh->GetElementNormal();
    if (normalElement)
    {
        int numNormals = mesh->GetPolygonCount() * 3;
        GLfloat *normals = new GLfloat[numNormals * 3];

        int vertexCounter = 0;

        for (int polyCounter = 0; polyCounter < mesh->GetPolygonCount(); polyCounter++)
        {
            for (int i = 0; i < 3; i++)
            {
                FbxVector4 normal = normalElement->GetDirectArray().GetAt(vertexCounter);

                glm::vec4 glmNormal = FbxVecToGlm(normal);
                glmNormal = glmMat * glmNormal;

                normals[vertexCounter * 3 + 0] = (GLfloat)glmNormal[0];
                normals[vertexCounter * 3 + 1] = (GLfloat)glmNormal[1];
                normals[vertexCounter * 3 + 2] = (GLfloat)glmNormal[2];

                vertexCounter++;
            }
        }

        glGenBuffers(1, &normalsBuffer);
        glBindBuffer(GL_ARRAY_BUFFER, normalsBuffer);
        glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)* 3 * numNormals, normals, GL_STATIC_DRAW);

        delete[] normals;

    }
    // ********* COLORS *************

    FbxLayer *layer = mesh->GetLayer(0);
    FbxLayerElementMaterial* pMaterialLayer = layer->GetMaterials();
    int numMatIndices = pMaterialLayer->GetIndexArray().GetCount();

    GLfloat *colors = new GLfloat[numMatIndices * 9];

    for (int i = 0; i < numMatIndices; i++)
    {
        //int matIndex = array->operator[](i);
        int matIndex = pMaterialLayer->GetIndexArray()[i];

        FbxSurfaceMaterial *smat = mesh->GetNode()->GetMaterial(matIndex);
        if (smat->GetClassId().Is(FbxSurfaceLambert::ClassId))
        {
            FbxSurfaceLambert *lam = (FbxSurfaceLambert*)smat;

            FbxPropertyT<FbxDouble3> p = lam->Diffuse;
            FbxDouble3 info = p.Get();

            for (int j = 0; j < 3; j++)
            {
                colors[i * 9 + j * 3 + 0] = (GLfloat)info[0];
                colors[i * 9 + j * 3 + 1] = (GLfloat)info[1];
                colors[i * 9 + j * 3 + 2] = (GLfloat)info[2];
            }
        }
    }

    glGenBuffers(1, &colorsBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, colorsBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)* 9 * numMatIndices, colors, GL_STATIC_DRAW);

    delete[] colors;

    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

    glBindBuffer(GL_ARRAY_BUFFER, colorsBuffer);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0);

    glBindBuffer(GL_ARRAY_BUFFER, normalsBuffer);
    glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, 0);

    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glEnableVertexAttribArray(2);

    return true;
}

```

# Answer
Beside the potentially wrong color you are seeing, it really looks like you also have normal issue witht the way I see the gradient being done on the triangle. I had something similar happening to me in the past, and it was the normals that were incorrect because I wasn't checking the mapping mode and reference mode of the my normal elements before fetching the values. I wonder if you have the same issue because you are also not checking either before doing this:

```
FbxVector4 normal = normalElement->GetDirectArray().GetAt(vertexCounter);

```

You can only do this if your `normalElement` mapping mode is `FbxGeometryElement::eByPolygonVertex` and if its reference mode is `FbxGeometryElement::eDirect`. This might be the reason why your normals look incorrect (if they are indeed incorrect).

Try doing the following to get your normals:

```
int vertexCounter = 0;

for (int polyCounter = 0; polyCounter < mesh->GetPolygonCount(); polyCounter++)
{
    int polygonSize = mesh->GetPolygonSize(polyCounter);
    for (int i = 0; i < polygonSize; i++)
    {
        FbxVector4 normal;
        switch (normalElement->GetMappingMode())
        {
            case FbxGeometryElement::eByControlPoint:
            {
                int controlPointId = mesh->GetPolygonVertex(polyCounter, i);
                switch(normalElement->GetReferenceMode())
                {
                    case FbxGeometryElement::eDirect:
                    {
                        normal = normalElement->GetDirectArray().GetAt(controlPointId);
                        break;
                    }
                    case FbxGeometryElement::eIndexToDirect:
                    {
                        normalIndex = normalElement->GetIndexArray().GetAt(controlPointId);
                        normal = normalElement->GetDirectArray().GetAt(controlPointId);
                        break;
                    }
                    default:
                    {
                        break;
                    }
                }
                break;
            }
            case FbxGeometryElement::eByPolygonVertex:
            {
                switch(normalElement->GetReferenceMode())
                {
                    case FbxGeometryElement::eDirect:
                    {
                        normal = normalElement->GetDirectArray().GetAt(vertexCounter);
                        break;
                    }
                    case FbxGeometryElement::eIndexToDirect:
                    {
                        normalIndex = normalElement->GetIndexArray().GetAt(vertexCounter);
                        normal = normalElement->GetDirectArray().GetAt(normalIndex);
                        break;
                    }
                    default:
                    {
                        break;
                    }
                }
                break;
            }
            default:
            {
                break;
            }
        }

        glm::vec4 glmNormal = FbxVecToGlm(normal);
        glmNormal = glmMat * glmNormal;

        normals[vertexCounter * 3 + 0] = (GLfloat)glmNormal[0];
        normals[vertexCounter * 3 + 1] = (GLfloat)glmNormal[1];
        normals[vertexCounter * 3 + 2] = (GLfloat)glmNormal[2];

        vertexCounter++;
    }
}

```

Make sure `FbxVecToGlm` doesn't do any funny business and free of typos/bugs.

As for the color, I can't really tell if what you are doing is correct or not since I don't have a lot of experience dealing with `FbxSurfaceLambert`. I usually get my vertex colors this way (very similar to the way I get my normals):

```
const FbxGeometryElementVertexColor* colorElement = mesh->GetElementVertexColor();

FbxColor color;
switch (colorElement->GetMappingMode())
{
    case FbxGeometryElement::eByControlPoint:
    {
        switch (colorElement->GetReferenceMode())
        {
            case FbxGeometryElement::eDirect:
            {
                color = colorElement->GetDirectArray().GetAt(controlPointId);
                break;
            }
            case FbxGeometryElement::eIndexToDirect:
            {
                int id = colorElement->GetIndexArray().GetAt(controlPointId);
                color = colorElement->GetDirectArray().GetAt(id);
                break;
            }
            default:
            {
                break;
            }
        }
        break;
    }
    case FbxGeometryElement::eByPolygonVertex:
    {
        switch (colorElement->GetReferenceMode())
        {
            case FbxGeometryElement::eDirect:
            {
                color = colorElement->GetDirectArray().GetAt(vertexId);
                break;
            }
            case FbxGeometryElement::eIndexToDirect:
            {
                int id = colorElement->GetIndexArray().GetAt(vertexId);
                color = colorElement->GetDirectArray().GetAt(id);
                break;
            }
            default:
            {
                break;
            }
        }
        break;
    }
    default:
    {
        break;
    }
}

```

Hopefully, that info will help you and/or someone else. It could very well be something else that is messing up your colors (and normals).

Good luck!
> 1 votes

---
Tags: opengl, c++, fbx
---


# Question
Title: How to determine when one game object contains another
I've got two game objects a circular (`circGO`) and rectangular (`retiGO`) objects, with the rectangular larger than the circular. I want to be know when `retiGO` contains `circGO`. I tried the following but it didn't work:

```
retiGOBounds = retiGO.GetComponent<Renderer>().bounds;
circGOBounds = circGO.GetComponent<Renderer>().bounds;

void Update () {

    if (retiGOBounds != null & circGOBounds != null)    {
        if (circGOBounds.Intersects (retiGOBounds)) {
            Debug.Log ("We Good");
        }
    }
}

```

Also I saw `Physics2D.OverlapArea` documentation, but didn't really understand how to use it to tell when one game object contains another.

# Answer
> 3 votes
Firstly, if you want to know when one set of bounds are wholly inside another one, don't test for intersection - that will return true even if the two bounds just barely touch.

The existing `Contains` method only works for points, but we can add our own as an extension method for convenience:

```
public static class BoundsExtension {

    // Note I skipped Z since you seem to be working in 2D.
    // The Bounds struct is shared between both 2D & 3D uses,
    // so we can write explicit Contains2D / Contains3D cases if needed.
    public static bool Contains (this Bounds container, Bounds other) {
        return container.min.x <= other.min.x
            && container.min.y <= other.min.y
            && container.max.x >= other.max.x
            && container.max.y >= other.max.y;
    }
}

```

Next, it's important to remember that `struct` instances like `Bounds` are what's called a "value type" in C# - like booleans, numbers, and enumrations. That means that when we read them into a variable, we're taking a *snapshot* or *shallow copy* of their current value.

This is in contrast to "reference types" like `class` instances, where reading them into a variable means storing a *reference* to the existing live instance, rather than copying its current contents.

(This also means a `struct` can't be `null`, only hold a default value - so that `null` check on the bounds is not meaningful here. You could use Nullable structs that hold an extra flag to express "no value set" but here we have better solutions)

So, if we want to keep track of where our objects are now, we first need to store references to the reference types we care about. Since we need a `Renderer` specifically to get bounds data from, we can make that explicit in our script's public variables - Unity will enforce this in the Inspector, so I can't accidentally assign a `GameObject` that has no `Renderer` attached into these fields.

(You can also get bounds from a `Collider2D` depending on your needs)

```
public Renderer container;
public Renderer contents;

```

Then we can ask for the current value of the bounds `struct` each frame when we want to do the test:

```
void Update() {
    // Doing a null check on the references tells us if we forgot to set them,
    // or if either of the Renderer components have been destroyed
    if(container == null || contents == null)
        return;

    // Compare our Renderers' current bounds using our shiny new Contains method.
    if(container.bounds.Contains(contents.bounds)) {
        Debug.Log("We Good");
    }
}

```

# Answer
> 1 votes
I guess you need to write your own function to check this type of intersection, because `Bounds.Intersects()` function checks if bounds "intersect" with other, not wholly contain the other bounds;

```
bool IsContaining(Bounds outerBounds, Bounds innerBounds){
        return (outerBounds.Contains(innerBounds.min)
        && outerBounds.Contains(innerBounds.max));
    }

```

**Note:** This function is pretty straightforward for your special case (checking for a circle is inside a rectangle, it will also work for two rectangles too).

---
Tags: unity
---


# Question
Title: Validating building "completion/enclosure" in infinite 2D tile map
I have a 2D infinite tile map game in which the player can place floors and walls to construct "buildings".

I'm trying to think of an efficient way to determine whether the player is inside a "complete" building, meaning it's fully enclosed by walls and a door.

Normally, the logic isn't difficult since it's easy to tell if the walls fully encircle an area - but in the case of an infinite map, the "building" may extend into unloaded areas of the game.

For example, if a player makes a complete rectangular building, 10x100 tiles long, only some of the chunks it covers will be loaded at once.

I have a few ideas:

* If a player is near candidate walls, follow them and load all necessary chunks to check completeness. This would work, but could load a moderate number of unused chunks.
* Cache a list of "complete" buildings *as they're completed*. So option #1 is applied only as the player builds the building. This would have to saved/loaded, and updated when integral walls/doors are removed, so it trades efficiency for a little overhead, which might be OK.
* Using a different metric to determine "indoors". I can't think of one though.

Anyone have any other ideas? Has this ever been implemented somewhere else, something I can at least use as an example?

# Answer
I'll try to extend your second option. Add a flag called "indoor" on your tiles. When you finish a building set the "indoor" true on all tiles inside the building. When the player is on a "indoor" tile he is inside a building. If you need to know in which building you are inside, make "indoor" a pointer to a building in your:

> list of "complete" buildings

.
> 2 votes

---
Tags: unity, c#, procedural-generation
---


title: Is Unity (and Unity Web Player) dead?

text:
# Question
Title: Is Unity (and Unity Web Player) dead?
I know that Chrome stopped supporting UWP a long time ago, but I recently tried to play a Unity game and I just couldn't. I tried all the browsers, even IE which UWP itself suggests, however I couldn't run it on any platform?

Can anyone play Unity games anymore, or are they all useless now?

Thanks,

# Answer
No, Unity is certainly not dead :) But the Web Player got deprecated in late 2015 after NPAPI support was dropped by most browsers.

It's still possible to develop for browsers in Unity by switching the target platform to HTML5/WebGL in the **Build Settings**. In contrast to the Web Player, HTML builds utilize standard APIs such as WebGL, asm.js etc. which allow you to run your application without installing any browser plugins.
> 10 votes

---
Tags: unity
---


# Question
Title: What would it take to program a game engine like the build engine
My favorite games of all time are thanks to Ken Silverman's BUILD engine, The engine that brought us DukeNukem 3D, Shadow warrior and Blood. I've read a few articles on the build engine however I haven't found any good ones that go in depth. Ive been programming in C for 3 and a bit years now and am reading through many books every day, so I believe I have minimal skills needed to take on this task.

I was wondering what it would take to make my own "Build engine". What sort of mathematics do I need to learn/know, What books would you recommend, what sort of programming do I need to know (I.E low level programming with bitwise operators or any thing else). My current goal is not to make a game like Duke nukem 3D but to merely make a engine that supports things like sloped walls, translucency, wall and floor sprites etc.

# Answer
(I was about to write the second comment and realized its actually an answer, so here we go :)

Start small, at the end every engine (better say library, engine is a full fledged thing that takes care of all parts of game development, also level-designer, build system and all sorts of things), every "engine" is more or less just a combination of a lot of 3rd party libs, for network, physics, rendering, game object communication. Id advice to start with using those 3rd party libs first, like i.e. bullet for physics, fmod for sound, raknet for network, bgfx for rendering and combine them as you go. And last but not least, have some real projects using it, they can be simple for starters

And dont let random people in the internet discourage you from doing this, its very common here to say "make a game not an engine" and for most people its true. But I for one made my entrance in the game industry with my own collection of game-libs as reference. They dont need to be perfect or anything, today I wouldnt show them to anybody anymore, but it was good to do it and learn.

*And* look at other libraries (a lot, really a lot), get involved in open source stuff and focus on managable goals, maybe multiplatform as well.

I wish you luck, and have fun!

**EDIT:** "managable goals" screw that, crazy goals are fine too, as long as they keep you motivated :)
> 3 votes

---
Tags: 3d
---


# Question
Title: How do i store blocks information in my Voxel game?
I am trying to make a voxel game.

Voxel games made by blocks and each block has it's own information such as durability, step sounds, strength, ...

How do i store these information inside of blocks? or is it true to save their information inside of themselves.

Do i store them on all blocks instances or static properties?

```
public class Block
{

    public virtual float durability
    {
        get
        {
            return 1f;
        }
    }

    public virtual float strength
    {
        get
        {
            return 1f;
        }
    }

    public virtual StepSound stepSound
    {
        get
        {
            return new StepSound ( "stone.ogg" );
        }
    }

}

```

Then create a class by inheriting `Block` class:

```
public class BlockDirt : Block
{

    public override float durability
    {
        get
        {
            return 0.5f;
        }
    }

    public override float strength
    {
        get
        {
            return 0.5f;
        }
    }

    public override StepSound stepSound
    {
        get
        {
            return new StepSound ( "dirt.ogg" );
        }
    }

}

```

Now i have all the above properties inside of any `BlockDirt` instances.

But it takes to much memory. just think i have 100 `BlockDirt`.

Or Do i create a base class:

```
public class Block
{

}

```

Then inherit it for creating blocks:

```
public class BlockDirt : Block
{

    public static StepSound stepSound = new StepSound ( "dirt.ogg" );
    public static float durability = 0.5f;
    public static float strength = 0.5f;

}

```

And use the `BlockDirt` static properties for all `BlockDirt` instances?

I don't know how to get static properties from class instance, but i know i can do it using **Reflection** but it takes more CPU and memory than instance based data.

What should i do?

Any help is appreciated.

# Answer
I would recommend you take a look at the flyweight pattern. It allows you to use objects such as tiles or blocks in very large numbers when a simple repeated representation would use an unacceptable amount of memory. The principle is well represented by this picture :

You basically have one object **Tree** that is instanciated and which defines all shared attributes between trees. You then just have to create position parameters to tell the engine where to display this single object.

Here is the full example applied to your problem if you want to know more.

**EDIT :** A few concrete examples :

* Creating Aliens on Unity (C#), comparing memory use. link
* Counter-Strike example (JAVA), reuse of the player models. link
* A live explaination by a youtuber (JAVA). link

I put Java examples as Java is pretty similar to C# in its syntax and structure. I'm sure you can find more example online, and perhaps better one.
> 3 votes

# Answer
I don't know how Minecraft did it, but very long ago, I once wrote a Minecraft clone. You could have a look on how I did it.

I am definitely not saying that this is how you should do it, or this is a good way to do it, but it worked. Note that I was probably only 17 back then and had little to no experience with this.
> 0 votes

---
Tags: unity, c#, procedural-generation, voxels, minecraft-modding
---


# Question
Title: Skill system in turn-based board-like RPG
I'm working on the implementation of a turn-based board RPG (like Descent: Journeys in the Dark) to improve my C++ skills and learn something about game-dev.

I have already done with general stuff, like Heroes and Monsters, their common action (move, attack) which they can do every turn. Now I want to add some skill system, and I'm not quite sure how to do it. I'm thinking about some skills that can be used after particular action is done (e.g. 'after attack dices are rolled, add +X to damage' or 'after another hero is revived, recover X HP'), some of those skill hero can gain by leveling up or with some item, but I don't know, how to implement this kind of skills. Maybe adding a checking for a game state could be a good idea, but that leads to tens of different options and doesn't look like efficient way to implement.

Could anyone please help me?

# Answer
> 1 votes
From the question it is unclear if your using an existing engine or building your own thing so I will try to keep this generic.

I would approach this by making a system that is data driven so that it can be reused and changed as needed. This would consist of an interface that defines what the skill affects (stats, appearance, etc), when the skill should take place (before action X, after action X, etc.), and a check for the skill that returns true when the skill finishes. Then you keep a collection of all the skills that a character has. You then iterate though the collection and ask if the skill should take effect, then once it does you check when the skill finishes you remove the modifiers that the skill is responsible for.

You could extend this to trigger visual effects and all sorts of stuff.

I hope this is what your looking for or at least close enough so that you can apply the idea to your specific use case :)

---
Tags: c++, rpg, turn-based, board-game
---


# Question
Title: Calculating the distance from a line to a point in 2D
I have a simple setup:

How do I calculate the orange distance?

It's the distance between the block on the left to the white line in the center (X & Z axes combined).

I don't have the intersection point. My only knowledge of the white line is that it goes through the point (0, 0, 0), running between (10, 0, -10) and (-10, 0, 10)

My problem is that I need to calculate this distance without the depth (Y value). Only on two planes combined: X & Z

# Answer
> 1 votes
You can rotate the point by -45 degrees, so that the x component becomes the distance.

If you always want to find the distance between the point and the XZ axes, then you can just precalculate the values:

```
| cos -45° -sin -45° |   | √2/2, -√2/2 |
| sin -45   cos -45° | = | √2/2,  √2/2 |

```

If we take the vector `(x; y)` the result is:

```
(√2/2 * x - √2/2 * y; √2/2 * x + √2/2 * y)

```

Then the distance is `abs(√2/2 * x - √2/2 * y)`

# Answer
> 1 votes
I think you should be able to get the position vector using Vector3.Project

```
 Vector3 vector = yourGameObject.GetComponent<Transform>().position ;
 vector.y = 0 ;
 Vector3 onNormal = new Vector3( 1, 0, 1 ) ;
 Vector3 projectionOnWHiteAxis = Vector3.Project( vector, onNormal ) ;
 float distance = (projectionOnWHiteAxis - vector).magnitude ;

```

# Answer
> 1 votes
```
float SignedDistanceFromLine(
    Vector2 sourcePoint,
    Vector2 lineDirection,
    Vector2 pointOnLine = default(Vector2))
{
     // Translate the whole situation to the origin.
     sourcePoint -= pointOnLine;

     // Construct a unit vector pointing 90 degrees right of our lineDirection.
     Vector2 perpendicular = (new Vector2(
               lineDirection.y,
              -lineDirection.x)).normalized;

    // Extract the component of our offset pointing in this perpendicular direction.
    return Vector2.Dot(sourcePoint, perpendicular);
}

```

This returns a signed distance, with positive values signalling that the `sourcePoint` is to the right of the line, and negative values to the left.

You can use this to get the positive distance like so:

```
Vector2 objectPosition = new Vector2(
               objectTransform.position.x,
               objectTransform.position.z);
float distance = Mathf.Abs(SignedDistanceFromLine(objectPosition, new Vector2 (1, -1)));

```

---
Tags: unity, vector, linear-algebra
---


# Question
Title: How to prevent Unity from triangulating faces of imported models?
I have an object that will be rendered with a wireframe shader. This means that line between vertices in a model would be drawn.

The problem is that Unity automatically triangulates all n-gons in my models. I want these n-gons to render as is.

Is there a way to prevent this?

# Answer
> 4 votes
Unity supports the following MeshTopology types:

* Triangles
* Quads
* Lines
* LineStrip
* Points

It does not, at the time of writing this answer, support topologies with 5 or more points per polygon.

To render a wireframe mesh containing pentagons or more complicated polygons, you can either...

* Render it as a collection of lines using `MeshTopology.Lines` / `LineStrip`.
* Render it as a solid surface, and use a suitable fragment shader to draw lines only along selected edges. (See other questions about drawing wireframe meshes for tips)

# Answer
> -1 votes
When you select your model, on the right hand side you can select an option that says "Keep Quads"

---
Tags: unity, models
---


# Question
Title: How to iterate through members of lists of members of lists within members of previous lists?
I'm sorry for the clumsy title, and for what will be the continuation of further clumsiness in my question - I'm not even sure how to properly ask this, so please allow me to illustrate:

I'm writing a game using XNA and C#.

I have 'nodes' in 2d space, and I'm trying to create a network of nodes representing traverse-able world-space.

The nodes themselves store a list of their 'neighbors', and an associated dictionary that refer to how an AI might travel from one node to a node's neighbor, either by walking, or jumping.

I'm trying to find a way that I may iterate from the list of one node's neighbors, to its neighbor's neighbors, to its neighbor's neighbor's neighbors, etc. etc. etc., to test each for contiguous neighboring connections based on whether or not they are all reachable to each other by 'Walk' (so I can find whole walkable platform segments).

# Answer
> 3 votes
I'd make it a bit simpler. Each Node will contain a single List of `NodeTransitions`.

A `NodeTransition` is something simple like:

```
public class NodeTransition {
    public Node node; //neighbor node
    public Action action; //how to get to neighbor node
}

```

You can then perform a breadth first search, of Nodes. Perhaps choosing a recursive algorithm. Once you find your target node, you can step back up to your starting node, keeping track of each `NodeTransition` along the way. You've just created a list that gives you each Node and the action required to get to that Node, to take you from point A to B.

If possible, you may want to structure things so you can at least get a direction for your neighbor nodes. This would allow for a A\* search, which would be much faster for the average path. (Technically this is available, but you'd have to look at each node to determine this).

# Answer
> 1 votes
This is just a recursive search through all the connected nodes.

For each node, iterate through all its immediate neighbors, adding it to your currently known connected set. Then recurse for any previously unseen nodes.

```
class Node {
    Dictionary<Node, Action> neighbors;

    public IEnumerable<Node> getNeighbors(Action actionType) {
        return from pair in neighbors
               where pair.Value == actionType
               select pair.Key;
    }
    public IEnumerable<Node> getAllConnected(Action actionType, HashSet<Node> currentlyKnown = null) {
        if (currentlyKnown == null)
            currentlyKnown = new HashSet<Node>();

        currentlyKnown.Add(this);
        foreach(var x in getNeighbors(actionType))
            if (!currentlyKnown.Contains(x))
                x.getAllConnected(actionType, currentlyKnown);

        return currentlyKnown;
    }

}

```

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


# Question
Title: Allow a Player to Navigate the 2D surface of a 3D mesh
**Edit:** Currently, I am looking for a method which will allow a player to control a 2D mesh and navigate along the surface of a 3D mesh. Visually, this would look like the player is inhabiting a 2D world. This 2D world would be the "wallpaper" (the surface) of a 3D object.

I've been trying to solve this problem by implementing a solution which can do realtime UV mapping of vertices. **Note, however, that this may not be the best or even proper solution to this problem and any alternatives which better solve the aforementioned problem are welcome.**

My current understanding of UV mapping is that any 3D mesh can be unwrapped so that its vertices, faces, and edges exist in a 2D space at which point a 2D texture can be mapped to these coordinates. If at a certain point in the 2D space, there is no defined face, but the texture is defined for that point, it is simply not applied to the model.

Example:

As you can see, only those parts of the texture defined within the bounds of the faces of the UV map on the right get mapped to the cube on the left.

I, however, am trying to implement a UV map for 2D meshes onto 3D meshes instead of 2D textures onto 3D meshes. I realize that to generalize this problem is too difficult at least for me, so I began with a UV map of a cube as shown above. The code is simple enough for defining a UV map for a cube. Simply define the bounds of each face and supply a function which maps each uv coordinate, based on which face it is located on to a corresponding location in xyz coordinates of the 3D mesh.

Using that rationale I came up with the following (pseudocode):

```
//define an enum of faces which can be returned from functions
//added NOFACE in case a function can't return any of the faces
enum face = {TOP,
              BOTTOM,
              SIDE1,
              SIDE2,
              SIDE3,
              SIDE4,
              NOFACE};

class UVMapCube
{
    private:
        //define the bounds for every face in the order of [xMin, xMax, yMin, yMax]
        top = [0,1,0,1];
        side1 = [0,1,1,2];
        side2 = [1,2,2,3];
        side3 = [-1,0,2,3];
        side4 = [0,1,3,4];
        bottom = [0,1,2,3];
        scale = 1;

    public:

        //constructor
        UVMapCube(scale)
        {
            //scale up bounds based on the size of the mesh
            for(i = 0; i < 4; i++)
            {
                top[i] = top[i]*scale;
                bottom[i] = bottom[i]*scale;
                side1[i] = side1[i]*scale;
                side2[i] = side2[i]*scale;
                side3[i] = side3[i]*scale;
                side4[i] = side4[i]*scale;
            }

            this.scale = scale;
        }

        //return which face a given vertex lies in based on its UV coordinates using the bounds of each face
        //this is set up so that there is no overlap of faces
        face getFace(vertU,vertV)
        {
            if(vertU >= top[0] && vertU <= top[1] && vertV > top[2] && vertV < top[3])
            {
                return TOP;
            }
            else if(vertU >= side1[0] && vertU < side1[1] && vertV >= side1[2] && vertV < side1[3])
            {
                return SIDE1;
            }
            else if(vertU >= bottom[0] && vertU < bottom[1] && vertV >= bottom[2] && vertV < bottom[3])
            {
                return BOTTOM;
            }
            else if(vertU >= side2[0] && vertU < side2[1] && vertV >= side2[2] && vertV <= side2[3])
            {
                return SIDE2;
            }
            else if(vertU > side3[0] && vertU < side3[1] && vertV > side3[2] && vertV < side3[3])
            {
                return SIDE3;
            }
            else if(vertU >= side4[0] && vertU < side4[1] && vertV >= side4[2] && vertV <= side4[3])
            {
                return SIDE4;
            }
            else
            {
                return NOFACE;
            }
        }
        //return x,y,z coordinates on a cube based on UV coordinates on the map
        Vector3 map(vertU, vertV)
        {
            face f = getFace(vertU,vertV);
            if(f == BOTTOM)
            {
                return Vector3(vertU, 0, 3*scale-vertV);
            }
            else if(f == TOP)
            {
                return Vector3(vertU, 1*scale, vertV);
            }
            else if(f == SIDE1)
            {
                return Vector3(vertU, 2*scale-vertV, 1*scale);
            }
            else if(f == SIDE2)
            {
                return Vector3(1*scale, vertU-1*scale, 3*scale-vertV);
            }
            else if(f == SIDE3)
            {
                return Vector3(0, -vertU, 3*scale-vertV);
            }
            else if(f == SIDE4)
            {
                return Vector3(vertU, vertV-3*scale, 0);
            }
            else
            {
                return null;
            }
        }
}

```

Graphically, it looks something like this:

I got this far. However, the problems begin to arise when considering the "realtime" component of this "realtime UV mapping" approach.

**Edit:** I am aware that UV maps break the connectivity of the 3D Mesh they represent. However, for my purpose, if I am to implement a realtime UV map, I would need some way to ensure the connectivity of the 3D mesh is represented in the UV map in some artificial way. In other words, what do I do to ensure the user remains on the 3D mesh despite having moved "off" to an undefined location on the corresponding UV map.

For example, where should I map the blue vertex in the example below:

The vertex location cannot be defined unless the vertex had some previous location on one of the defined faces of the map.

For one, if the vertex originates (its previous location before moving off the map) from Side1, it should be mapped somewhere on Side2. If it originates from Side2, it should be mapped somewhere on Side1. And if it originates from the corner of Bottom, Side1, and Side2, it should be mapped somewhere onto the edge shared by Side1 and Side2.

Am I missing something or will I have to simply figure out a bunch of special cases for mapping as I have been doing. Is there perhaps some mathematical approach which encompasses all of these cases completely or something known in the computer graphics community that I don't know?

Otherwise, if there is a better solution to my initial problem other than a "realtime UV mapping" approach, I would be glad to hear it.

Any help would be appreciated.

# Answer
> 1 votes
If you're doing "typical" operations, you can get away with a lot of intuitive shortcuts. They're intuitive because they're doing what the tool was intended to do. However, if you want to stretch beyond typical, it's best to understand what the math of UV mapping is really doing.

In all texture mapping, you're starting with a 3d mesh of triangles, and you're trying to assign a color to each point (whether that point is a vertex or simply a point inside the triangle). There are many ways to do this, of which UV mapping is only one method.

The fundamentals of UV mapping are very easy. You reduce the dimensional of the 3d mesh from 3 dimensions (x, y, z), to 2 dimensions which are given the labels u and v. You then use these 2 dimensions to decide what color to color each point (typically by doing a lookup from a 2d texture, as you have done). The key assumption is that, within any given triangle, a point's UV coordinates can be calculated by interpolating between the UV coordinates of each vertex (which turns out to be a really reasonable assumption in nearly all cases).

If you think formally like this, you can see that its possible there are points in this UV space that are not associated with a point on the mesh. Your blue dot is an example of that. It's a point in UV space that you simply cannot get by interpolating the UV values of the triangles on your particular mesh. That's all it is. So your question as to "where should I map the blue vertex" is a non sequitur. You don't have a blue vertex, you have a blue UV coordinate, which a vertex (or other point on a face) may be mapped to.

What that means to you is dependent on the precise problem you are trying to solve. To provide an example, if you are using the UV coordinates as a "hit map" of sorts, where you can click on the 2d bitmap and have it show you that point on the 3d mesh, then we can use the following rules:

* Project the 3d mesh into 2d space (which is a fancy way of saying take every triangle on the 3d mesh, and starting thinking of it in terms of just UV coordinates instead of XYZ).
* Whenever someone chooses a point on the bitmap, you can query this 2d mesh to see how many triangle contain that point.
    + If one triangle contains that point, you can use interpolation to identify the point in 3d space that associated with that UV coordinate
    + If multiple triangles contain this point, you can do the process on each triangle (its *very* common to abuse symmetry to have the left and right side vertices have the same UV coordinates).
    + If no triangles contain the point, then you are describing something that is "out of domain." You can decide what to do with this. For example, it may be very reasonable to pick the nearest triangle in the 2d space, and use it to extrapolate a 3d space point (outside of the triangle). If you did this, you'd find your point "vertex" outside of the object. This all depends on what is meaningful for your application. In some cases, where it's not obvious which triangle should "own" the out of domain point, you might even want to turn that 2d point into a 3d line or 3d curve to represent this information. It all depends on what your end user needs to visualize.

# Answer
> 0 votes
Let me try to rephrase the question as I understood it:

1. You have a 3D object surface unwrapped on to a UV map.
2. You want to be able to pick a point on the UV map and get its location on the 3D mesh?

In that case, the solution would be to either:

* make sure that whole UV map is "mapped". So there is not a single point on the UV map that is not belonging to some polygon.
* or come up with an algorithm, that will find nearest polygon/vertex on UV map and take its location.

P.S. You also might want to ensure that no point on UV map belongs to more than 1 polygon - otherwise it would be troublesome to choose the right polygon to map it to.

---
Tags: geometry, mesh, uv-mapping
---


# Question
Title: Unity: LineRenderer always behind Sprite
So I'm not sure what I'm missing here -- I created a bullet gameobject with a linerenderer (no sprite renderer) -- and it always renders behind my other sprites, regardless of what I set the z transform to. If I add a sprite renderer component to the bullet, regardless of the sorting layer, the bullet renders behind every sprite. Why is this happening, and how do I fix it? I believe it's due to my material used in the linerenderer -- I have the shader set to particles additive but when I change it to bumped diffuse it renders in front properly (but I want the visual effect to be additive).

I tried setting the sorting layer via script, and I can confirm that the sorting layer is set correctly but the linerender still doesn't render in front of the sprite.

# Answer
Add this script to your LineRenderer GameObject. It will allow you to set the SortingLayer and the SortingOrder in that Layer for your LineRenderer and correctly draw it with an additive material.

```
[ExecuteInEditMode]
public class SetSortingLayer : MonoBehaviour {
public Renderer MyRenderer;
public string MySortingLayer;
public int MySortingOrderInLayer;

// Use this for initialization
void Start () {
    if (MyRenderer == null)
        MyRenderer = this.GetComponent<Renderer>();
}

// Update is called once per frame
void Update () {
    if (MyRenderer == null)
        MyRenderer = this.GetComponent<Renderer>();
    MyRenderer.sortingLayerName = MySortingLayer;
    MyRenderer.sortingOrder = MySortingOrderInLayer;

    //Debug.Log(MyRenderer.sortingLayerName + " " + MyRenderer.sortingOrder);
}
}

```
> 1 votes

# Answer
Here's what I was able to come up with on Unity 5.6.1, for anyone who is looking for guidance on this in 2017.

```
public class SetLineRendererSortingLayer : MonoBehaviour
{

    public LineRenderer lr;
    public string SortingLayer;
    public int OrderInLayer;

    void Awake()
    {
        lr = this.GetComponent<LineRenderer>();
    }

    void Start()
    {
        lr.sortingLayerName = SortingLayer;
        lr.sortingOrder = OrderInLayer;
    }

}

```

Should be able to avoid this problem and many other similar ones by more closely reading about Unity's Sorting Layers.
> 0 votes

---
Tags: unity
---


# Question
Title: Why does the Debug.DrawRay return these weird lines
I am working on a small feature of a 2D mobile game where a indicator points towards a object in 2D space. I am trying to make the indicator turn towards the object, however the vector I am trying to construct that points towards the object is off a bit.

When I decided to draw a debug ray from the indicator position to the objects position it was also off a bit. I then decided to draw the debug ray the other way around which gave me a different line. If my understanding is correct, if you switch the starting point and the end point of a ray the line should stay exactly the same right?

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

public class Tracker : MonoBehaviour {

public GameObject goToTrack;
private List<Renderer> renderers = new List<Renderer>();

void Start(){
    foreach (Transform child in transform) {
        renderers.Add (child.gameObject.GetComponent<Renderer>());
    }
}

void Update () {

}

void OnGUI(){
    Vector3 v3Screen = Camera.main.WorldToViewportPoint(goToTrack.transform.position);

    // if the target is within the viewable screen the indicator shouldn't be rendered)
    if (v3Screen.x > -0.01f && v3Screen.x < 1.01f && v3Screen.y > -0.01f && v3Screen.y < 1.01f) {
        foreach (Renderer renderableObject in renderers) {
            //renderableObject.enabled = false;
        }
    }
    else
    {
        foreach (Renderer renderableObject in renderers) {
            //renderableObject.enabled = false;
        }

        v3Screen.x = Mathf.Clamp (v3Screen.x, 0.01f, 0.99f) -0.04f;
        v3Screen.y = Mathf.Clamp (v3Screen.y, 0.01f, 0.99f) -0.04f;
        transform.position = Camera.main.ViewportToWorldPoint (v3Screen);

        Debug.Log ("Target planet position: " + goToTrack.transform.position.ToString());
        Debug.DrawRay(Camera.main.ViewportToWorldPoint (v3Screen), goToTrack.transform.position, Color.red, 5.0f);
        Debug.DrawRay(goToTrack.transform.position, Camera.main.ViewportToWorldPoint (v3Screen), Color.green, 5.0f);

        //Debug.Log ("Tracker angle: " + angle);
        //transform.Rotate(0,0, angle, Space.Self);
    }

}
}

```

Output:

UPDATE: I have noticed that when i substract the second vector with the first vector of the Debug.DrawRay it draws the ray like i want it to.

From this I am taking that the Debug.DrawRay function draws the second vector on top of the first vector. (kind of like the the first vector is Vector(0,0,0) and the second vector is the actual ray you want to draw)

# Answer
> 4 votes
You're drawing Rays, not Lines. This means that the second parameter is a *direction* not a point in space.

https://docs.unity3d.com/ScriptReference/Debug.DrawRay.html

> Draws a line from `start` to `start + dir` in world coordinates.

That's why your two debug lines aren't the same. If you want to draw lines, use `Debug.DrawLine()` instead.

---
Tags: unity, c#, transformation, coordinates, debugging
---


# Question
Title: Movement in a text-based game using room class (Python)
I'm a newbie to game design and coding in general, and I've started working on a text-based adventure game project (like Zork) to work on my narrative writing skills while teaching myself Python. Any tips/pointing me in the right direction would be greatly appreciated.

Currently, I've established an inventory system, a room class, a player class, and an items class with a subclass for weapons.

The current thing that I'm stuck on is getting my player character to be able to move through the rooms in a consistent manner, and whether or not the code is actually reading the player character as being "in" certain rooms based on their position.

```
inventory = []

currentroom = 0

def addToInventory(item):
    inventory.append(item)

class player:
    def __init__(self, name, health, bag, position):
        self.name = name
        self.health = health
        self.bag = bag
        self.position = position

player.position = currentroom

player.bag = inventory

class Items:
    def __init__(self, name, info, weight, position):
        self.name = name
        self.position = position
        self.info = info
        self.weight = weight

class Weapon(Items):
    def __init__(self, name, info, damage, speed, weight, position):
        super().__init__(name, info, weight, position)
        self.damage = damage
        self.speed = speed

class Room:

    def __init__(self, description, exits, actions, roominv, position):  # Runs every time a new room is created
        self.description = description
        self.exits = exits
        self.actions = actions
        self.roominv = roominv
        self.position = position

sword = Weapon("Sword", "A sharp looking sword. Good for fighting goblins!", 7, 5, 5)
knife = Weapon("Knife", "A wicked looking knife, seems sharp!", 5, 7, 3)
stick = Weapon("Stick", "You could probably hit someone with this stick if you needed to", 2, 3, 3)
shackkey = Items("Shack Key", "A key! I wonder what it opens.", .01)
cottagekey = Items("Cottage Key", "An ornate key with an engraving of a small cottage on one side", .01)
Moonstone = Items("Moonstone", "A smooth white stone that seems to radiate soft white light", .05)
flower = Items("Flower", "A beautiful wildflower", .001)

introd = Room("You are in a forest, you can hear wildlife all around you. Your sword lies at your feet. There seems to be a clearing in the distance.", 'N' "clearing", {"Search the ground", "Go North"}, [sword], 0)

clearing = Room("You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating a bright white flower in the center of the clearing. To the South is the way you entered the forest. A well worn path goes to the East. In the distance a harp can be heard.", {'S': "introd", 'E': "forest path"}, {"Take flower", "Go south", "Go East"}, [flower], 1)

forest_path = Room("You begin walking down a well beaten path. The sounds of the forest surround you. Ahead you can see a fork in the road branching to the South and East. You can smell smoke coming from the South, and can hear a stream to the East", {'S': "cottage", 'E': "stream"}, {"Go South", "Go East"}, [stick], 2)

stream = Room("You come upon a relaxing stream at the edge of the woods. To your South is a rickety looking shack, to your West is the forest path you came down", {'S': "shack", 'W': "forest path"}, {"Go South", "Go West"}, [shackkey], 3)

shack = Room("In front of you is a shack, possibly used as an outpost for hunting. It looks dilapidated.", {'S': "inside shack", 'N': "stream"}, {"Go South", "Go North"}, None, 4)

insideshack = Room("The inside of the shack is dirty. Bits of ragged fur are scattered about the floor and on a table against the back wall. A sharp looking knife is on the table. There is a key hanging on the wall by a string.", {'N': "shack"}, {"Go North", "Take Knife", "Take Key"}, [knife, cottagekey], 5)

cottage = Room("A quaint cottage sits in the middle of a small clearing, smoke drifting lazily from the chimney.", {'N': "forest path", 'S': "inside cottage"}, {"Go north", "Go South"}, [Moonstone], 6)

```

I figured that I could use this to determine what room the player is in, however I'm not sure if this will do what I want it to do. For example, if player.position = 0 then according to my code they are in the introd room

How can I make it so the player only has access to their current room's attributes and not the attributes of the other Room instances?

Am I heading in the right direction with this or should I be using different structure?

Any tips would be much appreciated, currently browsing forums and youtube but still struggling with the logic.

I'm sorry if this is worded poorly/I'm being unclear here.

# Answer
> 0 votes
**The player and Basic Python Literacy**

This is something you'll get better with experience, but you don't seem to have a good grasp on how classes work yet. For example, you're setting variables directly on the player class.

```
# YOUR CODE
inventory = []
currentroom = 0

def addToInventory(item):
    inventory.append(item)

class player:
    def __init__(self, name, health, bag, position):
        ...

player.position = currentroom
player.bag = inventory

```

How I'd write this. Note that `world[room_name]` part. I'll get to it in a second:

```
class Player:
    def __init__(self, name, health, bag, room_name):
        self.name = name
        self.room = world[room_name])
        ...

player = Player("Bob", 100, [], "introd")

```

**Rooms and links between Rooms**

I think you need to have a global registry of room names, either as a `dict` or wrapped up in a class itself.

```
class Room:
    def __init__(name, description, links):
        ...

world = {}
world['introd'] = Room(
    "introd",
    "You are in a forest",
    {'N': 'clearing'}
)
world['clearing'] = Room(
    'clearing',
    'You are in a clearing surrounded by forest',
    {'S': 'introd'}
)

```

Then your player move function can:

```
class Player:
    ...
    def move(self, direction):
       if direction not in self.room.exits:
           print("Cannot move in that direction!")
           return
       new_room_name = self.room.exits['room']
       print('moving to', new_room_name)
       self.room = world[new_room_name]

```
1. take a direction (`N`)
2. look it up in the current room's exits. (`new_room_name` becomes `"clearing"`)
3. set the players new room

Now your core look can be something like

```
while True:
    command = raw_input('>>')
    if command in {'N', 'E', 'S', 'W'}:
        player.move(command)
    elif command == 'look':
        print(player.room.description)
        print('Exits', player.room.exits.keys())
    else:
        print('Invalid command')

```

---

**An aside on room links by name versus links by reference** An alternate design would be to not have the `world` dict at all, and just link rooms directly to each other:

```
forest = Room("a forest")
clearing = Room("a clearing")
forest.exits['S'] = clearing
clearing.exits['N'] = forest

```

However, this requires adding exits after defining the rooms (since otherwise you will need to refer to rooms before they are defined). Also you may want to eventually put the room data in a data file (like a database, CSV, or a JSON file) and having names or ids is important to link rooms together then.

# Answer
> 0 votes
Yes, your question is (a little) unclear. I thought about commenting to seek some clarity first, but maybe it's more useful to just explore the implications of a movement system? @Jimmy's already covered some of this; such is the nature of picking at an answer between other tasks :)

---

### A very simple system

The basic questions you need to be able to answer with a movement system are *where is the player?* and *where can the player move to?* Let's just try to write a movement command, and see what feels like a natural (well--IMO) way to express these questions in Python (I'm just freewriting pseudo-code and omitting things that aren't in focus; don't expect this to execute).

```
class Player(object):
    ...

    def parse_command(self, command, *args):
        """
        I wouldn't actually check commands in this order;
        it just makes for a better progression
        """

        # is this a global command (like "help")?
        if command in command_list:
            return commands[command](args)

        # is this something the user can do with an item they're holding?
        for item in self.bag:
            if command in item.actions:
                return item.actions[command](args)

        # Is this something the user can do in the room they occupy?
        if command in self.location.actions:
            return self.location.actions[command](args)

        # Is this a valid exit?
        if command in self.location.exits:
            return self.move(self.location, self.location.exits[command], direction)

    def move(self, start, end, direction):

        # maybe ask the present room if we can go, in case there's a guard, or a booby-trap
        if start.can_exit(self, end, direction):

            # maybe we won't ask the destination, but we might want to give everyone a chance to react to our move
            start.exit(self, end, direction)
            self.location = end
            end.enter(self, start, direction)
            return True

```

This fairly simple expression works if `player.location` is literally a reference to the room object, and not just an identifier (string, number) we can use to look it up. Instead of starting with `player.location = 0`, you can start with `player.location = introd`. It also answers your next question (*How can I make it so the player only has access to their current room's attributes and not the attributes of the other Room instances?*), because you can just do something like `print(player.location.description)`.

You've probably already realized that this really simple model gets tricky when it's time to define exits, because all of the room objects have to be loaded before they can link to each other. One way around this is to create all of your room objects at once, and *then* configure them:

```
introd = Room()
clearing = Room()
forest_path = Room()

introd.setup("You are in a forest, you can hear wildlife all around you. Your sword lies at your feet. There seems to be a clearing in the distance.", {'N': clearing}, {"Search the ground", "Go North"}, [sword], 0)

clearing.setup("You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating a bright white flower in the center of the clearing. To the South is the way you entered the forest. A well worn path goes to the East. In the distance a harp can be heard.", {'S': introd, 'E': forest_path}, {"Take flower", "Go south", "Go East"}, [flower], 1)

...

```

### Increasing complexity

This isn't to say that using a position number is *wrong*--just that there's a simpler way to write it if you don't need something more complex. If your text game was so large that you couldn't load all of the rooms at once, you'd need a stable string or number that you could use to look up rooms as-needed. Likewise, if you want to have a "save game" file, you'll probably need to save a string or number indicating where the user was.

Unless your game is very small, I would recommend using a string (perhaps even a path) to identify the rooms; by the time you've got 20 rooms, it's going to get hard to remember which exit/id points where, and you'll have to do lots of cross-referencing to untangle them if you mess up. You'd need to change up some code:

```
# you could make a rooms dict keyed by room ID, AND pass the ID to each room
rooms = {key: Room(key) for key in ["introd", "clearing", "forest_path"]} # this a "dict comprehension"
rooms["introd"].setup(... {'N': "clearing"}...)

# without further changes, moving would look a little tedious...
self.move(rooms[self.location], rooms[rooms[self.location].exits[command]], command)

# You could have your cake and eat it too by using a *property decorator* on the player object (property decorators enable a method to behave like a regular object property):
class Player(object):
    ...
    @property
    def location(self):
        return rooms[self._location_id]

    @location.setter
    def location(self, value):
        self._location_id = value.room_id

# then moving would simplify to:
self.move(self.location, rooms[self.location.exits[command]], command)

```

### More complex or special-purpose options

One of the nice things about the simple system is that you can make non-traditional exits (like "ladder" or "swim"), but it does have *some* downsides when compared to, for example, a coordinate-based system:

* It's harder to draw maps (where do you draw an exit to "swim"?)
* Locational messages are harder to do cleanly ("You hear a loud scream to the east" vs. "You hear a loud scream from... swim?")
* It's harder (but not impossible) to craft certain kinds of free-form/unbounded/random exploration experiences, such as wandering off into a wild forest where you can walk any direction, but have a random chance of stumbling on the entrance to a cave system.
* Certain kinds of directional commands or abilities can be awkward (that darn swim exit would once again break a command like "throw torch east" that in a coordinate system might just yield "You toss a torch east into the darkness and it lights up {description}.")

---
Tags: movement, python, text-based
---