title: RPG Item Design

text:
# Question
Title: RPG Item Design
I'm currently fiddling around with some RPG mechanics and I'm trying to implement a solid way to handle items that have different on use effects.

Currently, I have a base class called "Item" that consists of things that all items have such as ID, name, description, quality etc. Then I have some subtype classes that extend "Item" such as "Weapon", "Armour", "Consumable", "Material" and "Quest". "Item" also implements an interface called "Usable" that has a Use function.

These subclasses share the exact same qualities. Such as all armour has an armour value, all weapons have an attack value etc so that I don't need a different class for each item but I want the use effects to differ. An example is that I have an item of type "Consumable" which when the use function is called, restores player health, a different consumable may do this again, but heal a greater amount. Another consumable may teleport the player to a specific location. These items are being stored in a JSon file and there may be a thousand or more different items and effects.

So, firstly, What would be an effective way to implement this behaviour? Secondly, if the vast majority of items have a use effect in each category but a few don't, should it still be structured like this?

Thanks.

# Answer
> 2 votes
Similar to the answer to the question referenced by Philipp, you might consider using a general system of events and flags for every item:

* CanEquip, OnEquip/OnDeEquip
* CanConsume, OnConsume
* IsQuestItem, OnCompleteQuest
* etc.

This is a much more flexible approach as it allows items to serve multiple purposes as would be the case in, for example, the dry baguette which is both a blunt weapon and a food.

You can then use the OnEquip/OnDeequip to add and remove user actions, status effects, and so on. Imagine a cyborg character who needs to equip limbs. We might consider adding or removing the "Fight" option depending on whether they have their limbs equipped. The DeEquip event also supports having a thief-type character steal equipped items.

To make reusable records for each item, you can use composition. So you might use the Item class for everything, and include a list of components for each, ala:

```
Item: { Name: "Baguette", Aspects: [ Weapon: { ... }, Food: { ... }, ... ] ... }

```

Note that the Aspects member is an array. You would implement a base class for that like ItemAspect, and extend that for particulars to each idea, while every Item object could pass through events (OnConsume) and properties (CanConsume) to check in with its aspect members.

---
Tags: rpg, inheritance, effect, polymorphism
---


# Question
Title: problem using OnStartServer() for unity multiplayer networked game
***UPDATE: i am still scratching my head over this. The way i see it, the Awake() function is only invoked when I load it in the Editor, but if I put the prefab Loading line into OnStartServer() it just doesnt load anything, presumably because it hasnt managed to load the prefab yet ... i think it is something to do with when it switches Scenes from the offline to online in NetworkManager, i think this script and others are being dropped because the DontDestroyOnLoad command wasnt called due to Awake not being called.***

Hello everyone I am making a football game which you control one player from the team. It will connect 11v11 players per server (using a "Host" acting as server and client, and other clients connecting to them)

I believe I have followed the examples and information provided by Unity to the letter, but I can't seem to get it working properly.

The problem: My code seems to work fine, provided I open the 'Host' instance from the Unity Editor, but if I make the full build version the Host it doesnt work.

Strangely all my player-objects will all spawn and act exactly as I intended, but the ball will not spawn unless the 'Host' instance is the one opened inside Unity Editor. I've made the Ball a Network Identity, NetworkTransform etc and Registered Prefab in the NetworkManager in inspector.

Here's the code I am using to spawn the ball on the server, what could be the problem as I really have no ideas, thanks:

```
using UnityEngine;
using UnityEngine.Networking;

public class MatchdayManager : NetworkBehaviour {
GameObject ballPrefab;

private void Awake()
{
    DontDestroyOnLoad(this);

    ballPrefab = Resources.Load<GameObject>("Prefabs/Ball");
}

public override void OnStartServer()
{
    Debug.Log("on server start called");
    GameObject go = Instantiate(ballPrefab);
    NetworkServer.Spawn(go);
}

}

```

# Answer
OK well I found a workaround style solution. I also came across some info here https://forum.unity.com/threads/when-awake-will-be-call-for-game-object-with-networkidentity.441678/ , which states that it is actually a known bug (for many months/years/iterations of unity!) where Awake is not called on NetworkBehaviour scripts, unless its in the Editor.

My solution is really annoying for me as it means calling gameobject.SetActive on the gameobject for my 'MatchdayManager : NetworkBehaviour' class constantly in Update() in my GameManager class (which is derives from MonoBehaviour). So I had to create an Update loop in the GameManager class and make a public variables and drag the MatchdayManager object into it, in the update loop first line is constantly setting the matchdaymanager to Active every frame (otherwise Unity is automatically setting it to inactive whilst I am in the 'offline scene' of my game).

```
using UnityEngine;

public class Game : MonoBehaviour {
public static Game instance;
public MatchdayManager matchdayManager;

// Use this for initialization
void Awake() {
    if (instance == null)
    {
        instance = this;
    }
    else
    {
        return;
    }

    DontDestroyOnLoad(this);
}

void Update () {
    if (!matchdayManager.gameObject.activeInHierarchy)
    {
        matchdayManager.gameObject.SetActive(true);
    }
}
}

```

and...

```
using UnityEngine;
using UnityEngine.Networking;

public class MatchdayManager : NetworkBehaviour {
public static MatchdayManager instance;

public GameObject ballPrefab;

public void Awake()
{
    instance = this;

    DontDestroyOnLoad(this);
}

public override void OnStartServer()
{

    Debug.Log(Time.time + " OnStartServer invoked");

    GameObject go = Instantiate(ballPrefab);
    NetworkServer.Spawn(go);

}

}

```

With this workaround my ball is now loading on all clients and the host client , whichever I use (ie. Build version or Editor version), so i was clearly right that the Awake call wasnt getting called, but now that I set it to active every frame, it is getting called from any type of Build of the game.

If anyone understands why this is happening and can tell me a better way to handle it I would be very grateful.

thanks
> 1 votes

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


# Question
Title: How can I trigger to start timeline using distance and not OnTriggerEnter/Exit?
```
using UnityEngine;
using UnityEngine.Playables;

public class GenericTrigger : MonoBehaviour
{
    public PlayableDirector timeline;

    // Use this for initialization
    void Start()
    {
        timeline = GetComponent<PlayableDirector>();
    }

    void OnTriggerExit(Collider c)
    {
        if (c.gameObject.tag == "Player")
        {
            timeline.Stop();
        }
    }

    void OnTriggerEnter(Collider c)
    {
        if (c.gameObject.tag == "Player")
        {
            timeline.Play();
        }
    }
}

```

The idea is to create some kind of cut scene. Once the player (First person, in the screenshot i'm just showing the door on the left where the player will come from and the soldiers ) exit the door on the left and is in a specific distance from the soldier the first soldier the closet one will start moving to the player. Later I will make that it will change to close up view on the soldier with some text conversion. That's the main goal.

But the script the original script by the unity tutorial is using triggers. I'm not sure if I should using this way or using somehow by calculating the distance between the player and the soldier to start the timeline ? And how to do it.

After the soldier is moving/walking to the player at some point I will make it to change to a close up view on the soldier with blurry background something like this:

But first how should I approach to the triggering part ?

# Answer
> 1 votes
You could use a SphereCollider component for your trigger. Put it on your player's GameObject and set the radius property to the distance at which the cutscene should start. Because it is a sphere, it will always fire at the closest distance to the soldier.

---

Another option would be to do it via script:

```
using UnityEngine;
using UnityEngine.Playables;
using System.Collections;

public class GenericTrigger : MonoBehaviour
{
    public PlayableDirector timeline;
    public GameObject[] soldiers;
    public GameObject player;
    public float cutsceneDistance = 5f;

    // Use this for initialization
    void Start()
    {
        timeline = GetComponent<PlayableDirector>();
        StartCoroutine(CheckDistanceCoroutine());
    }

    IEnumerator CheckDistanceCoroutine()
    {
        // Check distance forever in each frame
        for(;;)
        {
            // Check distance for each soldier
            for(int i = 0; i < soldiers.Length; i++)
            {
                float distance = Vector3.Distance(soldiers[i].transform.position. player.transform.position);
                if(distance <= cutsceneDistance)
                {
                    timeline.Play();
                    // Maybe also destroy the helper behaviour here if it is not needed anymore
                    break; // Leaves the distance check coroutine
                }
            }

            // Wait for next frame
            yield return null;
        }
    }
}

```

If you need further info to coroutines, see the documentation:

https://docs.unity3d.com/Manual/Coroutines.html

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


# Question
Title: What graph Search algorithm (s) that can simulate the behaviour of a human searching in a forest
We are building a game , where a group of humans(AI agents) have to wander seperatly throughout the forest looking for a collectable item. The forest is represented as a 2d graph with the item randomly placed at an (x,y) coordonate. Having a random search, while the easiest, doesn't guarantee that in a such big map I will reach the item and doesn't take into account that humans have memory and are able to tell, to a certain degree, weather the have traveled that path before.

A more systematic approach such as DFS, while guarantees that eventually the item will be reached, doesn't feel like a human wandering throughout the forest, it lacks the element of randomness and loss.

What I have in mind so far, is to run DFS to randomly selected batch of the forest. So the forest would be subdivided into randomly placed chunks for each human to wander, overlap and revisit is possible, and it would run DFS in that chunk traversing the subgraph eventually if item not found randomly select another chunk.

What do you guys think of the approach? How would you simulate human like search in a graph?

# Answer
If your humans are trained search and rescue people they would use one of the established search patterns.

This usually means going to the point most likely to contain the target and systemetically spiraling outwards. Or splitting up the search area into sectors and searching each one in turn.

This is not random but that is by design to avoid gaps and overlap.
> 1 votes

# Answer
Let's start with a simplified case and work up from there: Just one AI agent exploring the graph.

Calculating the *perfect* route to explore the whole graph in an acceptable time is an unsolved problem. So we shouldn't even try to find a perfect solution and instead aim for a simple solution which provides "good enough" results.

One such algorithm is the "greedy" algorithm: Always walk to the closest unexplored node.

This algorithm is very easy to implement and will cover a good amount of area in the short-term. But it has an unfortunate side-effect. It might lead the AI actor on a journey far away from the starting location before it fully explored its vicinity. You would usually expect them to look close to their starting location and then expand further when they don't find anything nearby.

A good way to account for that is to integrate this into the rating function for picking the next node. When you rate the nodes by priority, don't just take the distance to the current location of the agent into account, but also the distance to the starting location. How you weight these two criteria in relation to each other is more of an art than a science. Just experiment with this until you get a result you like.

Now how do we extend this to multiple cooperating agents? When they all perform the same algorithm, they will all walk to the same tile. They will likely stick close together and not make any use of their superior number.

In order to get them to divide and split, add a 3rd criteria to your rating function: proximity between the node and the next other agent. But assign a *negative* weight to this criteria. That means agents will avoid those tiles which are close to other agents and will instead focus on those areas of the graph no other agent currently attends to yet.

So final node rating formula:

`node_rating = distance_agent * a + distance_origin * b - distance_closest_other_agent * c`

Adjust the values of the constants `a`, `b` and `c` to taste. Lowest rating wins.

Now this algorithm might seem a bit too perfect. You said you wanted an "element of randomness and loss". To make the AI agents more fallible, you could screw with their list of visited nodes. While the AI agent wanders the forest, randomly mark previously visited nodes as unvisited, so the agents explore them again. Give each AI agent a separate list of forgotten nodes, so they wont all simultaneously run towards the same node. That way you will also observe the behaviour that they will occasionally not trust each other and check a node another agent checked previously.

How often to do this is another thing you might have to experiment with. Things I would experiment with is how frequently to forget nodes in which phase of the search and whether to prefer to forget nodes closer or further away from the agent.
> 0 votes

---
Tags: collision-detection, navmesh, graph, search
---


# Question
Title: How to know the size of object in Unity in world units?
Suppose I have some external package with objects. Suppose I place some of these object to the scene. Now how to know actual size of object in world units?

I found no any rulers or something in Unity.

The I thought I can place primitive cube and compare it, but then I realized that I don't know the size of cube too.

Is is possible to "measure" arbitrary object in Unity somehow?

# Answer
> 1 votes
Use the `Mesh.bounds` variable. From Unity's docs:

> The bounding volume of the mesh.
>
> This is the axis-aligned bounding box of the mesh in its local space (that is, not affected by the transform). Note that the Renderer.bounds property is similar but returns the bounds in world space.

Then use the `Bounds.size`. From Unity's docs:

> The total size of the box.
>
> size.x is the width, size.y is the height and size.z is the depth of the box.

This should give you the exact size of the mesh. Unfortunately this means you have to create a script to get the size, which may be impractical, but you can for example make it print in the Inspector the size of the mesh while you are editing.

# Answer
> 0 votes
The default cube is one unit in each direction. To some extent, the units themselves are arbitrary (that is, you can assign whatever meaning you want to that size). In places where Unity uses distance (for instance, certain physics formulas), it assumes each unit is a meter.

As to measuring objects, you can make some quick estimate by using the unit cube as a reference, scale it & make comparisons.

There are also one or more distance tools in the asset store that can be used to GameObjects in your scene.

---
Tags: unity
---


# Question
Title: How do I spawn an enemy at one of many spawn points in Unity?
I have a spawn script that so far only creates one Enemy spawn point and enemy trigger while only spawning one enemy.

Instead, I want it to create multiple spawns and triggers, but keep it such that only one enemy spawns at a time, at a random on of the spawn points.

How can I do this?

---

Here's the relevant code at the moment:

```
public class SpawnManager : MonoBehaviour {

    public GameObject Enemy; // the enemy prefab
    public float mytimer; // the time to wait before spawn

    private GameObject _spawndEnemy; // the enemy that was spawnd

    void SpawnEnemy()
    {
        var enemySpawnPoint =  GameObject.Find("FFEnemySpawn1").transform;
        _spawndEnemy = Instantiate(Enemy, enemySpawnPoint.position, enemySpawnPoint.rotation) as GameObject;
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.name == "FFMirror1") {
            mytimer = Random.Range(0,15);
            Destroy(_spawndEnemy);
            Invoke("SpawnEnemy", mytimer);
            Debug.Log("Spawn Normal");
        }

    }
}

```

# Answer
This falls under the Single Responsibility Principle (see SOLID).

Specifically:

* the spawn point should handle entity creation, rather than a manager
* you would want to either have a field on the spawn point or a parameter on the spawn method that would tell it what to spawn
* you would then use an ordinary trigger behavior (maybe called TriggerSpawn, with a target array field) to trigger the spawn point
* tag the spawned entity so that you can locate it later, rather than referencing it within the entity that created it
* once the entity is spawned, you can disable the trigger until some condition is met (the entity could enable the trigger if it's destroyed), or you could disable the spawn points, etc.
> 3 votes

# Answer
I got this random spawning code I made if it helps. I'm sure its not hard to have it spawning one person at a time.

```
    public class SpawnScript : MonoBehaviour
{
    public GameObject player;

    void Start()
    {
        GameObject theSpawn;

        do  // checks an error
        {
            getSpawn(gameObject); // grabs random spawn
            theSpawn = getSpawn(gameObject);
        } while (theSpawn == gameObject);

        player.transform.position = theSpawn.transform.position; // changes players position
    }

    private GameObject getSpawn(GameObject spawn)
    {
        Transform[] childs; // spawn list childs transform
        GameObject randomSpawn; // random spawn game object

        childs = (Transform[])spawn.GetComponentsInChildren<Transform>(); // gets transform of spawnPositions children
        randomSpawn = (GameObject)((Transform)childs[Random.Range(0, childs.Length)]).gameObject; // randomly picks a childs transform

        return randomSpawn;
    }
}

```
> 0 votes

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


title: Get ring of tiles in hexagon grid

text:
# Question
Title: Get ring of tiles in hexagon grid
Thanks to this post: Hexagonal tiles and finding their adjacent neighbours, I'm able to collect adjacent tiles to a given tile. But I'm pretty much stuck on an algorithm that gives me only a "ring" of tiles specified by an offset. The algorithm given in that Stack Overflow post doesn't exactly care about the order in which it collects the tiles.

I know that with every offset 6 tiles are added.

* Offset 1 gives you 6 tiles (the first adjacent tiles).
* Offset 2 gives you 12.
* Offset 3 gives you 18, etc.

There is a constant growth of 6 with each offset. So I assume there should be a rule which adapts to these offsets. I can't exactly figure this one out. Anyone?

# Answer
> 24 votes
A hexagonal ring with the radius of N consists of 6 straight lines, each with length N - see my extremely crude example below :) For N=2:

The arrows cover 2 hexes each.

I assume you have some functions which give you the neighbouring tile in a specific direction, like north(), southeast() etc. So your algorithm, in pseudocode, should be something like this:

```
var point = startingPoint.north(N)
for i = 0..N-1:
    result.add(point)
    point = point.southeast(1);
for i = 0..N-1:
    result.add(point)
    point = point.south(1);
for i = 0..N-1:
    result.add(point)
    point = point.southwest(1);
for i = 0..N-1:
    result.add(point)
    point = point.northwest(1);
for i = 0..N-1:
    result.add(point)
    point = point.north(1);
for i = 0..N-1:
    result.add(point)
    point = point.northeast(1);

```

Note that this should work also for edge cases N=1, returning 6 tiles, and N=0 returning an empty set.

I know the code isn't perfect :) There is some redundancy here. In my projects using regularly tiled maps (hexagonal or otherwise) I usually have an enum "Direction", which allows me to do this more smoothly:

```
var point = startingPoint.inDir(N, Direction.North)
var dir = Direction.SouthEast.
for d = 0..Direction.count():
    for i = 0..N-1:
        result.add(point)
        point = point.inDir(1, dir);
    dir = nextDirection(dir);

```

# Answer
> 2 votes
I have found this article to be a very good reference for hexagonal grid algorithms, and its section on "Distances" provides a method for determining the number of steps between two tiles. If you convert your **axial coordinates** (x-y) into **cube coordinates** (x-y-z), the distance is always equal to the largest of the coordinate offsets between the two tiles, or max(|dx|, |dy|, |dz|).

An exhaustive search of the whole grid for tiles at the desired distance is \\$O(n^2)\\$ with the grid dimensions, but it is a simple implementation that works well for small grids.

---
Tags: algorithm, grid, hexagonal-grid
---


# Question
Title: Best Practice for Validating Components in Unity/C#?
In my game there's a Unit class, which all soldiers use. Not all soldiers have special abilities which require unique class components (like Stealth class). Special abilities either exist on a unit from the start, or never.

Special classes like Stealth are monobehaviour classes which provide specific functionality, and the fact a unit is or is not Stealth will need referenced by other classes. For example, the classes which handle unit shooting and detection must check whether a unit in proximity is stealth. I'm wondering what is the best way to handle this case with Unity, given components?

Right now the Unit class' Start function checks if the special class exists, and assigns a private boolean to true. This boolean can only get accessed by a get function. Does this make sense for more easily readable and secure code? Or is it overengineering?

```
private bool isStealth;

if (GetComponent<Stealth>())
{
    isStealth = true;
}

public bool IsStealth()
{
    return isStealth;
}

```

# Answer
Your solution is fine. Although “secure coding” is not what you’re doing so much as “decoupled coding” which is a laudable goal.

An even more decoupled alternative is to have the solution be more generic, so that the Unit class need not know about the Stealth class at all, for example by using an enum. It can then be extended if the Unit has other properties set up via Components without needing to modify the Unit class (more than trivially) for each property.

For example (warning: untested):

```
[Flags]
public enum UnitProperty {
    Stealth = 1,
    Boss = 2,
    Slow = 4,
    MadeOfJelly = 8,
    //etc.
}

public interface UnitPropertySource {
    UnitProperty GetProperty();
}

public class Stealth : MonoBehaviour, UnitPropertySource {
    public UnitProperty GetProperty() {
        return UnitProperty.Stealth;
    }
    //other stealthy stuff
}

public class Unit : MonoBehaviour {
    private UnitProperty properties;
    private void Start() {
        foreach (var propertySource in GetComponents<UnitPropertySource>()) {
           properties |= propertySource.GetProperty();
        }
    }
    public bool HasProperty(UnitProperty p) {
        return properties & p == p;
    }
    public bool IsStealth {
        get {
            return HasProperty(UnitProperty.Stealth);
        }
    }
    public bool IsMadeOfJelly {
        get {
            return HasProperty(UnitProperty.MadeOfJelly);
        }
    }
}

```
> 1 votes

# Answer
Your approach seems fine as long as a Stealth component cannot be added during runtime. Otherwise you should get rid of the `bool` field and just write your IsStealth method like so:

```
public bool IsStealth()
{
    return GetComponent<Stealth>();
}

```

Because a `bool` is returned, `GetComponent<Stealth>()` will be casted automatically.

Unity also provides a special method for validating values in `MonoBehaviour` called OnValidate. This is useful if you have public fields (or in Unity docs sometimes called properties) that require validation. But in your case it makes more sense to validate during runtime, because the isStealth field should not be public if its value depends on some other component.
> -1 votes

---
Tags: unity, c#, component-based
---


# Question
Title: how to place object relative to parent at x distance specified
**My application:**

Place furnitures or construction objects (doors/windows) in scene.

Everything is fine until I touch the construction objects. Since the application is mobile, it will be hard for a user to place the door at the exact place, so I decided to help and put a little menu where they can specify where to put it:

The scene (room in this case) looks like this:

**Some implementation details:**

The walls are a prefab instantiated 4 times:

```
 GameObject wall_N = Instantiate(wallPrefab);
 wall_N.gameObject.name = "Wall_N";
 wall_N.GetComponent<Transform>().position = new Vector3(center_W, 50, center_H + z / 2);
 wall_N.transform.SetParent(room.transform, false);
 wall_N.GetComponent<Renderer>().material.color = myColor;
 wall_N.gameObject.transform.localScale = new Vector3(x, y, 0);

```

and so on for each wall. `x, y, z` are the values introduced by user and transformed into int

`int x = Int32.Parse(xInput); // width int z = Int32.Parse(zInput); // length int y = Int32.Parse(yInput); // height`

and `Center_W` and `Center_H` are screen points:

`private int center_W = Screen.width / 2; // 960 private int center_H = Screen.height / 2; // 540`

In the above image i've introduced `x, y, z` as `200, 200, 200`

**Question:**

In what coordinates must I work in order to place the door at a dimension specified? I'm not even sure if this approach is correct, the main idea is to put the door at the correct position in the room.

**What I've tried**

The first idea that came in my mind was to find the `bottom-left` coordinates from `Wall_N` and place the door at `point + A` but then I realised that the `bottom-left` is represented in different coordination sistem then `A`. I've search about it and I tried to see the values from `screenPoint` in different coordinates:

```
var screenPoint = new Vector3(center_W, 50, center_H + z / 2);

 var worldPos = Camera.main.ScreenToWorldPoint(screenPoint);
 var screenToViewport = Camera.main.ScreenToViewportPoint(screenPoint);
 var viewpointToWold = Camera.main.ViewportToWorldPoint(screenPoint);
 var worldToViewport = Camera.main.WorldToViewportPoint(screenPoint);

 Debug.Log("wallN - screen point " + screenPoint + " to worldPos " + worldPos);
 Debug.Log("wallN - screen point " + screenPoint + " to viewPortPos " + screenToViewport);
 Debug.Log("wallN - viewPort " + screenPoint + " to worldPoint " + viewpointToWold);
 Debug.Log("wallN - world " + screenPoint + " to viewport " + worldToViewport);

```

Unfortunately, they didn't tell me anything, I just don't know how to solve this.

# Answer
> -1 votes
After many tries I found that the dimensions introduced are calculated in pixels

`int x = Int32.Parse(xInput); // width
 int z = Int32.Parse(zInput); // length
 int y = Int32.Parse(yInput); // height`

`wall_N.gameObject.transform.localScale = new Vector3(x, y, 0);` -\> if I introduce 200, x will be 200 pixels, y introduced will be in pixels etc relative to this position `wall_N.GetComponent<Transform>().position = new Vector3(center_W, 50, center_H + z / 2);`

So, after a bit of thinking I've come to this formula:

`var xDistance = center_W - DimensionIntroduced/2 + dimDesiredFromWall_V + xDoorDimension/2;
// or var xDistance = center_W + DimensionIntroduced/2 + dimDesiredFromWall_V + xDoorDimension/2; if i want to move at right`

`var yDistance = center_W + DimensionIntroduced.height/2`

`var clone = Instantiate(newGameObject, new Vector3(xDistance, 0, yDistance), Quaternion.identity);`

So I guess that `transform.localScale` is measured in pixels, but i'm not very sure, as long as it works as expected in my app, it's ok xD I don't know how much it helps tho, but if somone has questions, feel free to ask.

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


# Question
Title: Calculate quaternion rotations between two values
I have a quaternion Q1:
X: -0.023995593190193176 Y: -0.4076451063156128 Z: 0.04357096180319786 W: 0.9117847681045532

and I have a keyframe value Q2 which is based on Q1: X: 0.176469 Y: -0.368251 Z: 0.479782 W: 0.776569

Now my question is how can I get the correct keyframe values if there would be no extra start values ? I mean if Q1 is 1,0,0,0 (w,x,y,z). (no extra start values) So basically I need to rotate my object to the same pose but from the default values (1,0,0,0) start not from Q1.

# Answer
> 0 votes
Let's see if I understand correctly...

* Q1 is our absolute starting rotation
* Q2 is our absolute ending rotation - ie. it includes both Q1 and some additional rotation

...and you want to get let's call it Q\_delta, the change in rotation from Q1 to Q2? (Or, equivalently, the corresponding Q2 if Q1 were the identity quaternion (w=1, xyz = 0)), is that right?

If so, it's fairly straightforward:

Q\_delta = Q2 * Inverse\*(Q1)

To see why, we can derive it from the fact that Q2 is Q1 with an extra rotation of Q\_delta applied on top (here using the convention that rotations stack from right to left):

$$\begin{align} Q\_\Delta \cdot Q\_1 &= Q\_2\\ (Q\_\Delta \cdot Q\_1) \cdot Q\_1^{-1} &= (Q\_2) \cdot Q\_1^{-1}\\ Q\_\Delta &= Q\_2 \cdot Q\_1^{-1}\ \end{align}$$

---
Tags: rotation, quaternion
---


# Question
Title: Terrain Rendering/Update Failure Python 3.x
I have begun to create a procedurally generated RPG using Python, and I am having trouble with rendering the terrain.

### What is happening:

I generate some terrain from some files, or create/save new terrain, and display it on the screen as a 2D B&W heightmap; black = low elevation, white = high elevation. The data are stored in .txt files, formatted as a series of arrays populated with floats.

When the game loads, the terrain is displayed properly, however, once you begin to move around, the terrain begins to act funky.

1. If you move far from where you start, the terrain becomes gridlike.
2. If you move horizontally, the terrain becomes somewhat vertically offset.
3. If you move vertically, the terrain does not update.
4. Even if you DO move horizontally before/after moving vertically, the terrain will not update vertically, only horizontally.

What I just said, but with images/video.

EDIT: I *think* the problem occurs in this block of code, but I can't be sure. This is taken from `grid_generator.py`. It returns a merged grid from the 3x3 area around a given point, where `merge`, `loadGrid`, and `findAdjFnames` are custom functions within `grid_generator.py`.

```
def threeBYthree(x,y):
    g = []
    for gy in range(-1,2):
        g.append([])
        for gx in range(-1,2):
            adj = findAdjFnames(x + gx,y + gy)
            print(adj)
            shouldSave = not os.path.isfile('./assets/grids/' + str(x + gx) + '_' + str(y + gy) + '.txt')
            print(shouldSave)
            g[gy + 1].append(loadGrid(str(x + gx) + '_' + str(x + gy) + '.txt', adjF = adj, andSave = shouldSave))

    #merge upper four
    g3a = merge(g[0][0],g[0][1],g[1][0],g[1][1])

    #merge bottom-left two
    g3b = []
    for y in range(len(g[2][0])):
        g3b.append(g[2][0][y] + g[2][1][y][1:])

    #merge top-right two
    g3c = []
    for y in range(len(g[0][2])+len(g[1][2])):
        if y < len(g[0][2]):
            g3c.append(g[0][2][y])
        elif y == len(g[0][2]):
            pass
        else:
            g3c.append(g[1][2][y-len(g[0][2])])

    #merge all
    g3d = merge(g3a,g3c,g3b,g[2][2])

    return g3d

```

The problem may occur somewhere else, but this bit is what I most recently worked on before the code stopped working.

### Pastebin files:

Terrain functions: grid\_generator.py

Main game loop: main\_test.py

Terrain file for coordinate (0,0): 0\_0.txt

*NOTE: irrelevant, and some necessary, functions have been removed for privacy and security reasons. If you feel that this includes information required for a fix, please comment.*

# Answer
# The solution has been found!

Within the `threeByThree` function, on a line I would have never guessed was incorrect:

`g[gy + 1].append(loadGrid(str(x + gx) + '_' + str(x + gy) + '.txt', adjF = adj, andSave = shouldSave))`

should have been:

`g[gy + 1].append(loadGrid(str(x + gx) + '_' + str(y + gy) + '.txt', adjF = adj, andSave = shouldSave))`

### The problem with my function was that I was using an `x` variable where a `y` should have been.
> 0 votes

---
Tags: python, pygame, terrain-rendering
---


title: Avoiding Out-Of-Ram Crashes in unity

text:
# Question
Title: Avoiding Out-Of-Ram Crashes in unity
My Players experience crashes on older computers when they enter a scene with a lots of 3d models.

Is there anything I can do to avoid this, except deleting those models from the scene?

# Answer
I can add more; but the big things you can do are:

* Have lower res models. This is how games ran a dozen years ago (or two dozen!), so have lower poly-count models. Often 3dsMax and other programs can even *generate* a lower poly model for you
* Have 2d versions of the model when it's far enough. This is extremely common for Trees and things, but interestingly you can do this with models. The Total War series does this noticeably.
* Add "fog" closer to you (or don't load things outside of a radius.) This is also made famous games when they overused this and only loaded things right in front of you (N64 superman if I recall)
* Lower-res textures. Textures are often a culprit for very high Ram usage.
> 1 votes

---
Tags: unity, memory-efficiency
---


# Question
Title: Gunfire Sound Gets Cut Off When I Release the Aim Button. Help?
So for my game you have to hold down right mouse click to aim and then simultaneously click the left mouse click to shoot. When the gun is fired, I'd like the gunfire sound to play. Currently, I have this working, but I have a problem. When I let go of the aim button, the gunfire sound immediately stops playing (if it hasn't already played through).

I understand this is happening because of the placement of my PlayShootSound method call, but what I can't figure out is where to put it so that I don't have this problem.

Any pointers/ideas?

```
public class Weapon : MonoBehaviour {

 public float fireRate = 0;
 public float damage = 10;
 public LayerMask whatToHit;

 public Transform BulletTrailPrefab;
 public Transform MuzzleFlashPrefab;

 float timeToFire = 0;
 float timeToSpawnEffect = 0;
 public float effectSpawnRate = 10;
 Transform firePoint;

 public AudioClip shootSound;
 private AudioSource gunFire;

 bool isShooting = false;

 // Use this for initialization
 void Awake () {
     gunFire = GetComponent<AudioSource>();

     firePoint = transform.Find("FirePoint");
     if (firePoint == null)
     {
         Debug.LogError("No fire point...Please make an empty object named FirePoint and attach to end of gun. :)");
     }
 }
 void Update () {
     CheckIfShooting();
 }

 void CheckIfShooting()
 {
     if (Input.GetButton("Fire2")) // Holding right click
     {
         if (fireRate == 0)
         {
             print("fire rate is 0");
             if (Input.GetButtonDown("Fire1")) // Left click while holding right click
             {
                 Shoot();
                 PlayShootSound();
             }
         }
         else
         {
             if (Input.GetButton("Fire1") && Time.time > timeToFire) // For automatic guns
             {
                 timeToFire = Time.time + 1 / fireRate;
                 Shoot();
                 PlayShootSound();
             }
         }
     }
 }

 void Shoot()
 {
     Vector2 mousePosition = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
     Vector2 firePointPosition = new Vector2(firePoint.position.x, firePoint.position.y);
     RaycastHit2D hit = Physics2D.Raycast(firePointPosition, mousePosition - firePointPosition, 100f, whatToHit);

     if (Time.time >= timeToSpawnEffect)
     {
         Effect();
         timeToSpawnEffect = Time.time + 1 / effectSpawnRate;
     }
     // Debug.DrawLine(firePointPosition, (mousePosition - firePointPosition) * 100, Color.cyan);

     if (hit.collider != null)
     {
         // Debug.DrawLine(firePointPosition, hit.point, Color.red);
         Debug.Log("We hit " + hit.collider.name + " and did " + damage + " damage.");
     }
 }

 void PlayShootSound()
 {
     gunFire.PlayOneShot(shootSound, 1f);
 }

 void Effect()
 {
     Instantiate(BulletTrailPrefab, firePoint.position, firePoint.rotation); // Fire Bullet

     Transform muzzleFlashClone = Instantiate(MuzzleFlashPrefab, firePoint.position, firePoint.rotation) as Transform;
     muzzleFlashClone.parent = firePoint;
     float size = UnityEngine.Random.Range(6f, 9f); // Randomize size of muzzle flash
     muzzleFlashClone.localScale = new Vector3(size, size, size);
     Destroy(muzzleFlashClone.gameObject, 0.05f);
 }

```

# Answer
Thank you everyone for helping, but I found the answer finally!!!

I followed this tutorial on how to create an audio manager and call sounds through it...and now my problem is fixed. :)

https://www.youtube.com/watch?v=HhFKtiRd0qI
> 0 votes

# Answer
In my own game I've put all Gun oriented logic inside of a Gun class (with derived classes representing different guns.)

I'd probably refactor this so you do a "gun.Shoot()" and then inside of gun.Shoot() you'd have something like:

```
public Shoot()
{
     // logic for firerate
     // logic for creating/firing a bullet

     this.PlayShootSound()
}

```

Depending if that's still buggy; you may go crazy and wrap it in a Task. Tasks are managed Threads from a Thread pool that are automatically assigned when needed so then you might do:

```
var task = new Task(() =>
    {
        this.PlayShootSound();
    }
task.Start();

```

Hopefully that's overkill and not necessary.

EDIT: I think you should try the above. It should be nigh guaranteed to work if you use a task;
> 0 votes

---
Tags: unity, sound
---


# Question
Title: How do you handle large triangles with frustum?
I am rendering the Sponza scene ato test my frustum implementation.

My current approach is simply, test if the vertices of the triangle are within the frustum (angle between the camera looking direction and the position od the vertex relative to the camera).

If any of the vertices are visible then the trianlge is considered to be visible.

The issue is that the sponza scene has some really large triangles, thus with my approach it is possible to be looking directly at a triangle and see nothing if all 3 vertices are outside the camera frustum.

# Answer
Elimination of large triangles isn't as simple as the vertices aren't on screen then the triangle can't be seen.

For an accurate frustum cull, the only valid elimination scenario for your data (there are more deeper versions) is that the all vertices are on one side of a frustum plane. The reason for this is that your triangle may straddle the frustum (ala cross the plane of your screen).

Testing the angle between the vertices and the camera position is also inaccurate, as your frustum isn't a point, its a projection of a box. Therefore you need to test your vertices against 6 planes that make up your frustum.

Finally, testing every vertex against the frustum will become expensive. This is where abstracting your data becomes more important. Usually abstraction comes in the form of using bounding boxes to group up sets of triangles (also known as a mesh) to quickly eliminate them from your potential visible set.

I've attached my frustum generation (create at start of every frame) code and the bounding box test:

```
  void GenerateFrustumPlanes()
        {
            if (m_disableFrustumUpdates)
                return;

            Matrix matrix;

            // Create the frustum matrix from the view matrix and updated projection matrix.
            matrix = m_wvp;

            m_planes[0] = new Vector4(matrix.M13,
                 matrix.M23,
                 matrix.M33,
                matrix.M43); // near
            m_planes[1] = new Vector4(matrix.M14 - matrix.M13,
                matrix.M24 - matrix.M23,
                matrix.M34 - matrix.M33,
                matrix.M44 - matrix.M43);

            m_planes[2] = new Vector4(matrix.M14 + matrix.M11,
                matrix.M24 + matrix.M21,
                matrix.M34 + matrix.M31,
                matrix.M44 + matrix.M41); // left
            m_planes[3] = new Vector4(matrix.M14 - matrix.M11,
                matrix.M24 - matrix.M21,
                matrix.M34 - matrix.M31,
                matrix.M44 - matrix.M41);//right

            m_planes[4] = new Vector4(matrix.M14 - matrix.M12,
                matrix.M24 - matrix.M22,
                matrix.M34 - matrix.M32,
                matrix.M44 - matrix.M42); // top
            m_planes[5]  = new Vector4(matrix.M14 + matrix.M12, matrix.M24 + matrix.M22, matrix.M34 + matrix.M32, matrix.M44 + matrix.M42); // bottom

            for (int i = 0; i < s_frustumPlanes; i++)
            {
                m_planes[i].Normalize();
            }
        }

```

Testing code:

```
public bool IsInViewableArea(List<Vector3> a_cornerLIst)
        {
            // this is a simpler occlusion test where we basically don't even need to test frustum as the the extents are outside the camera view distance.  But you need to test extents + width because we only hold 2 corners and squares are 4

            int iTotalIn = 0;

            Vector4[] pList = GetFrustumPlanes();  // this should only be called once.

            // test all 8 corners against the 6 sides
            // if all points are behind 1 specific plane, we are out
            // if we are in with all points, then we are fully in
            Vector4 temp;
            float dotvector;
            for (int p = 0; p < Camera3d.s_frustumPlanes; ++p)
            {

                int iInCount = 8;
                int iPtIn = 1;

                for (int i = 0; i < a_cornerLIst.Count; ++i)
                {
                    //Vector3 a = pList[i].
                    // test this point against the planes
                    //   if (pList[p].SideOfPlane(vList[i]) == BEHIND)
                    //Vector4.Dot()
                    temp = (Vector4)(a_cornerLIst[i] );
                    temp.W = 1;

                    dotvector = Vector4.Dot(pList[p], temp);

                    if (dotvector < 0.0f)
                    {
                        iPtIn = 0;
                        --iInCount;
                    }
                }

                // were all the points outside of plane p?
                if (iInCount == 0)
                {
                    return false;
                }
                // check if they were all on the right side of the plane
                iTotalIn += iPtIn;
            }

            // so if iTotalIn is 6, then all are inside the view
            //    if (iTotalIn == 6)
            //       return true;

            // we must be partly in then otherwise
            return true;
        }

```
> 2 votes

---
Tags: graphics, glsl, frustum, frustum-culling
---


# Question
Title: Can't scale properly to android device in Game Maker Studio 1.4
My phone is using a resolution of `360 x 640` with a `9:16` aspect ratio. I set my room in game maker to `360 x 640` and game maker thinks it's in landscape mode. I disabled landscape mode in the android settings and set to portrait only, like it should be. How do I get it to scale properly?

This is the code I have in my Scale Manager Object.

Create Event:

```
///Display Properties
ideal_width = 0;
ideal_height = 640;

aspect_ratio = display_get_width()/display_get_height();
ideal_width = round(ideal_height/aspect_ratio);

//check for odd numbers
if(ideal_width & 1) {
    ideal_width++;
}

for (var i = 1; i <= room_last; i++) {
    if(room_exists(i)) {
        room_set_view(i,0,true,0,0,ideal_width,ideal_height,0,0,ideal_width,ideal_height,0,0,0,0,-1);
        room_set_view_enabled(i,true);
    }
}

surface_resize(application_surface,ideal_width , ideal_height);
window_set_size(ideal_width,ideal_height);
room_goto(room_next(room));

```

# Answer
I switched the variables locations in this line

```
ideal_width = round(ideal_height/aspect_ratio);

```

Now it's

```
ideal_height = round(ideal_width/aspect_ratio);

```
> 1 votes

---
Tags: android, game-maker, resolution
---


# Question
Title: How to prevent attackers from compromising multiplayer game servers?
Consider a relatively small multiplayer game server, written by an individual or a small company. Some malicious user wants to boost their character stats by a factor of 100.

What paths of attack might they have and what are the most important safeguards to prevent these attacks?

# Answer
**Attack vector 1: The netcode**

As already pointed out by Mario, one important factor when designing the network protocol of a client/server application is to not blindly trust the client. You can't control the software which runs on the client machine. You can't even tell that it's your software and not something the user programmed themself. The same limitations apply to anti cheat software. They can't do anything you can't do yourself to prevent hacking your client software. So make sure that the server doesn't allow the player to do anything they aren't supposed to do, like setting their stats to any number they want.

Treat the network input of the client like you would treat the user input on a GUI. Would you make the number fields on the character status screen editable, allow the user to put in anything they want and then go with it? Certainly not. So why would you do that on the server?

**Attack vector 2: The database**

Most games use SQL databases as backends. Whenever you use an SQL database and deal with data provided from an untrusted source, you have to be weary of SQL injections. This is a common mistake many people make when using an SQL databases and which allows users to do anything to the database they want, including deleting and altering records. Fortunately it's easy to avoid by following some well-known coding practices like prepared statements, ORM wrappers or stored procedures.

**Attack vector 3: The infrastructure**

The gameserver might run on an operating system which might not be configured for high security, not be behind a properly set-up firewall and might not have the latest patches. This can make it vulnerable for os-level exploits allowing remote code execution or unauthorized logins. How to properly secure a server on the OS level is a topic for http://security.stackexchange.com and/or http://serverfault.com.

**Attack vector 4: The human factor**

But the biggest security hole of all is always the user.

All other security measures are worthless when an attacker acquires the password to a GM or admin account.

An attacker could use social engineering techniques to impersonate staff members and claim that they forgot their password. They could use spear phishing to trick staff into revealing their passwords or they could trick staff members into installing keyloggers.

The only countermeasure against this is to educate all staff members about proper security practices.

Some of your staff members could also be susceptible to bribery or blackmail (or just be idiots), especially when they are unpaid volunteers from your community. This problem can be partially mitigated by 1. having a rigid code of conduct explaining what a staff member can and can't do in a certain situation and 2. properly log all admin actions making it impossible to abuse privileges without you finding out.
> 14 votes

# Answer
Another interesting question where I can cite that awesome quote I've found on the internet a few years ago regarding the creation of multiplayer games:

> The client is in the hands of the enemy.

Whereas the enemy is the player trying to cheat or "hack".

Overall, there's no 100% perfect way to avoid hacking, cheating or botting.

One of the easiest way to avoid such issues is - as said in the quote - to never trust the client.

**Neverwinter Nights 2** offers a perfect example for this. It had horrible net code. I helped running a roleplay server a few years ago and it was really, really hard to do so right after the first expansion has been released. What happened?

Account creation in Neverwinter Nights 2 has been (not sure it's been changed) the perfect example of how not to do it. Just to note, the game offers two different modes of multiplayer gameplay: Either characters saved on the local player's machine or characters saved on the server. The first approach allows easy cheating, so we didn't use it. However, the second approach hasn't been a lot better:

At account creation, the game created the character and uploaded it to the server. That doesn't sound very secure and it isn't. In fact, this caused quite some unintentional issues. If an expansion player created some character with expansion features and logged into a non-expansion server, the server couldn't handle that suddenly "invalid" character data and simply crashed.

What should have been done instead is something a bit different: The client should tell the server what to create. But in the end the server determines how/what he creates and whether it accepts the parameters given. This is how pretty much any modern MMORPG handles its character creation process and other mechanics. If you still happen to pass some invalid value, you'll just receive an error message rather than see your character being created with invalid stats.

As you specifically asked to magically gain 100 points of some attribute or anything like that: If done right, there's nothing you can do without having access to the actual server. If all calculations (like damage) happen on the server, you simply can't influence or modify them.

Something like the **injection** you mentioned can have some - but at most minimal - effect based on how the game is written:

Let's assume upon login, the server sends the client some data package "permissions". This will tell the client what the player is allowed to see, for example spawn points or transitions usually not visible to the player. Using traffic manipulation, you could use a program to modify that package so the client thinks you're actually allowed to see that stuff (for example), yet this won't change how you appear to other players or the server (because that data should be verified by the server before being accepted and/or passed on).
> 4 votes

# Answer
Ok, I can tell you that I had access to the opensource wow server code, and the worst thing for me was fixing the loop holes which gave some not "noon programmers" the ability to manipulate packets, the unofficial opensource servers have thousands backloops and they do not check the packets. On contrary I am sure that you wont do any harm to anyone, because an advanced skill in programming to do such stuff. And in the question you haven't mentioned networking which is all about handling packets. That is how wall hacks work, speed hacks if the server allows something and it will not have a bottlecap of some sort, there is no reason why the hacked client shouldn't send 10x more packets that are responsible for player forward movement. So in this case the player would be able to move 10x faster.

Keep in mind, that tinkering with somebody's server will get you into trouble. In the civilised world you are not allowed to do harm or manipulate data without the owners permission. (Applies to DDOS attacks too). All the incomming packet data, that exceeds the norm is logged in 95% of sittuations. And the player who does that gets a permanent ip-ban.

Search google for "packet manipulation methods".

**Still, if somebody wants to go work as an "anti hacking programmer" this is the perfect way to learn about it. And never do it on somebody's server because I can tell you that it is extremely hard to avoid getting your actions logged. If you do it on somebody's server you will most likely be banned from the server and you might even get a real life "ban"...**
> 2 votes

# Answer
There are a few attack vectors to consider here, not just those with the intended effect (some malicious player wants to boost their stats) but also other effects as well.

As the other answers have eloquently put, **never unquestioningly trust the client**. Because there is no way to tell on the Internet what has happened to your client (if there is a bug in the client or the network, if the client has been modded, or even if it is your client at all), a server must always sanitize a client's inputs, making sure they are plausible and correct, before using them. There are several aspects to this:

**Keep the network out of it:** As much as possible, encrypt all of your network communications using SSL certificates and individual symmetric keys for each client. That way, when you receive messages from a client, you can at least know that they are unequivocally that client and that their messages have not been compromised by the network. (You still can't usually trust the client, though, but it is easier if they can trust you.)

**Make sure that the API you provide to clients is exactly and only what they need:** For instance, do not provide a call on the data server that updates a character's stats directly. Instead, provide simple, normal game actions to the client, and allow the server to calculate when stat changes should happen.

**Make sure that the calls to your server/receiving client APIs make sense:** You should first make sure that a message received from a packet corresponds to a client API call at all (and thus have a data format that allows you to verify this), then make sure that the arguments provided make sense and that it makes sense for the client to make this call at this time. For instance, a player who doesn't have a shotgun should not be sending calls to fire one. (NOTE: Many higher level netcode APIs in consumer game engines like Unity and Unreal will check if incoming messages match one of your expected message types, but will not check the contents for you.)

**Enforce all prerequisites:** In general, if any part of your code ever makes any assumption about the arguments, you should already be enforcing those assumptions with assertions, which will safely terminate your program if they are not met. Whenever you receive any network messages, you are guaranteed very little about their contents, so at that point you should ensure that the network message meets all of the assertions in all of the code in which it will be used (which is probably your entire code base).

**Beware of DoS attacks:** If a rogue client can't get their way, they can just take the server down with them and ruin it for everybody else by simply overwhelming the server with faulty packets. You can never perfectly safeguard against this, but you can increase your tolerance for it by simply refusing to honor requests that are sent from the same client too frequently.

**Secure your server in other ways, too:** Keep in mind that there are other ways to access your game server for administrative purposes - for instance, you might use SSH or Remote Desktop to log into it and fix things, or it may contact a data service. Be sure that those channels are secure, too, because an attacker may attempt to compromise your server by going through one of these backdoors.

**If all else fails, keep good backups and logs and allow user reporting:** If you cannot prevent a rogue action, a good backup will allow you to roll it back with little to no collateral damage. Also allow players to report the condition, and you can read the server's logs to investigate what happened, find the cheater, and act accordingly. (Be sure to keep your reporting system secure, too!)
> 0 votes

---
Tags: server, security, hacks
---


# Question
Title: Algorithm to generate random shapes that fill up a rectangle?
The final result can be like this

I've thought up several approaches:

1. Generate random curved lines to "cut" the rectangle (or generate random dots and form the line from the dots)
2. Break the rectangle with Fracture Voronoi algorithm and shrink the broken parts to make the curved lines thicker.
3. Generate random shapes and let it fall into the rectangle like the game Tetris

But before implement the ideas, I want to know if there is an algorithm (with pseudo code) to generate random shapes that fill up a rectangle?

# Answer
> 1 votes
Did you check Fortune's algorithm?

Here is the Pseudocode from Wikipedia (sorry, in the Pseudocode has images, so I can't copy it as text but I can only capture the image)

You can find some people share their implementation on GitHub (for example: C++ implementation of Fortune's Algorithm)

---
Tags: algorithm, procedural-generation
---


# Question
Title: How to transform only part of an array in OpenGL ES?
I have one texture atlas of which I select the "non-animated textures", I put all vertex and UV coordinates in two array:

```
vertices = new float[] {
            // background
            0.0f, 1920f, 0.0f,
            0.0f, 0.0f, 0.0f,
            1080f, 0.0f, 0.0f,
            1080f, 1920f, 0.0f,
            // character
            240f, 760.0f, 0.0f,
            240f, 14.0f, 0.0f,
            770f, 14.0f, 0.0f,
            770f, 760.0f, 0.0f,
            // object (Will be transformed)
            360f, 800f, 0.0f,
            360f, 600.0f, 0.0f,
            500f, 600.0f, 0.0f,
            500f, 800f, 0.0f,
    };

uv = new float[] {
            // background
            0.50f, 0.25f,
            0.50f, 0.75f,
            1.0f, 0.75f,
            1.0f, 0.25f,
            // character
            0.0f, 0.25f,
            0.0f, 0.75f,
            0.25f, 0.75f,
            0.25f, 0.25f,
            // object
            0.0f, 0.75f,
            0.0f, 1.0f,
            0.25f, 1.0f,
            0.25f, 0.75f
    };

```

My vertex shader:

```
uniform mat4 matrix;
attribute vec4 vPosition;
attribute vec2 a_texCoord;
varying vec2 v_texCoord;

void main() {
    gl_Position = matrix * vPosition;
    v_texCoord = a_texCoord;
}

```

And my fragment shader:

```
precision mediump float;

varying vec2 v_texCoord;
uniform sampler2D a_texture;

void main() {
    gl_FragColor = texture2D(a_texture, v_texCoord);
}

```

I don't know how to animate just a part of the arrangements, also I try to create one more texture but when I run the app I only see the last texture.

# Answer
> 2 votes
So the first thing I notice is that you only have 3 rectangles that you are drawing. This is a very small number and unlikely to tax the GPU. Your best bet may be to simply make 3 separate draw calls. Setting things up to do this in a more complicated way seems needlessly complex.

Second, if you want to use more than 1 texture, you need to sample from more than 1 texture. You are only ever sampling from a single texture in your fragment shader, so that's all you'll see. Again, you could put drawing of all 3 objects into a single shader, but that just makes things more complicated without any benefit. If it were me, I would use the shader you have. I would set the texture unit used to a different texture unit before each draw call. So before each draw call, make a call to `glUniform1i(a_texture_location, x)` where `a_texture_location` is the result of `glGetUniformLocation("a_texture");` and `x` is the texture unit where the texture for that object lives (i.e. `GL_TEXTURE0`, `GL_TEXTURE1`, etc.).

---
Tags: opengl-es
---


# Question
Title: How can I improve the visibility of an object transform gizmo?
I'm developing a 3DSMax like move gizmo, and I'm struggling with how difficult it is to see, especially on modern high resolution displays. Is there a good way to make the RGB axis lines more visible when overlaid on top of a bright object?

# Answer
To try to answer your question I've Googled for examples, to see what other applications are doing differently, always a good thing to do!

Currently your gizmo lines are only 1 pixel wide. This is okay when rendering something in 3D, but makes the lines hard to see. Consider rendering a cylinder instead of the lines to create the gizmo. This will probably make it a lot more visible.

There are also many examples of gizmo's that have a cone/arrow on the end of each axis line. This also increases visibility.

Combine this with giving the user the option to how long the axis in the gizmo are, and how thick they are and it should become a very good to use gizmo.
> 2 votes

---
Tags: tools
---


# Question
Title: MMORPG Design Question: Best idea for adding PvP(PlayerVsPlayer) in open world MMO?
**Brief Explanation of game:** Time Travel, one map, open world MMO called ChronoCraft. If you'd like to know more about the game, you're welcome to check out our twitter where we post some of our development: https://twitter.com/Chrono\_Craft

Here are the ideas so far:

**1- Safe Zones**

*Pros:* People in major towns are safe and can fight when they leave the safety of the town *Cons:* When dealing with NPC's and Quests(Non-instance ones) outside of town, someone can kill you as you are talking to them

**2-PvP Zones**

*Pros:* Instead, areas of the map where PvP is possible is limited to the "wilderness" or dangerous areas(Anything that doesnt have Quest-able NPCs) *Cons:* Significantly reduces the area of allowable PvP areas

**3-PvP Toggle**

*Pros:* This allows players to turn on PvP mode in settings where only other PvP enabled players can fight eachother outside of Safe Zones (We would make it so if you are hit, you cant turn off PvP mode until a certain time to prevent people escaping death) *Cons:* Ambushing is limited, because only the people who are ready to fight will have it enabled

**4-Separate servers**

*Pros:* Having a PvE server and a PvP server. Which makes it so the player decides what gameplay he wants. *Cons:* Players cant bring items or money between servers so they may have to start from scratch if they change their mind on what type of server they like playing.(This is to protect the player economy from taking all the resources from one server and bringing them to another server)

**5-Time Specific**

*Pros:* When night falls, then PvP is enabled for everywhere outside a Safe Zone *Cons:* For players wanting to avoid PvP they will be forced to stay in towns half the time which might get boring unless they do fun stuff like running a shop or restaurant.

**6-Special Days**

*Pros:* When there is lighting and rain, PvP is enabled which will happen every few minecraft days in the game. Allowing PvPers to fight outside of safe zones. And a HUD display will make this clear. *Cons:* Players wanting to avoid PvP will have to stay in town during the inclement weather, which they might not enjoy.

**7-Level Specific**

*Pros:* Only players with a similar skill level will be able to fight eachother. So new players dont have to worry about pros slaughtering them early on. *Cons:* It would be hard to fight along friends unless you're the same skill level. "John help me kill this guy"-"Sorry cant, he is too low skill for me"

**8-Arenas**

*Pros:* Confines the fight to specific spot like a colosseum *Cons:* Nearly impossible to wage huge fights like 100v100 (Colosseum will make it into the game at some point, but should it be the only PvP option)

**9-PvP Everywhere** *Pros:* Either (A)Players can figure out their own police/protection system or (B) NPC guards in major towns spawn and nearly guarantee the death of a killer in the town. *Cons:* Has alot of potential to be annoying if players dont want to get killed in the middle of business in towns. Might also turn away less PvP focused players.

**-What do you think is the best?**

**-Can I mitigate the cons for the one you choose?**

**-Is there a better idea entirely?**

# Answer
> 3 votes
All the solutions you proposed have appeal, but their appeal is for different player demographics.

According to Richard Bartle's taxonomy of player types, there are 4 types of players playing MMORPGs:

* **Socialisers** who want to build a community and cooperate with other players.
* **Explorers** who want to figure out the game. They come in the flavor of metagame explorers who want to know every single detail about your game mechanics and environmental explorers who want to see every detail of your game world and find out its lore.
* **Achievers** who want to grow their character and solve challenges.
* **Killers** who want to dominate other players.

Nobody fits any of these categories 100%, but the majority of players identify very much with one or two of these categories. When you develop the PvP system of an MMO, you need to decide which player-archetype you want to cater to.

**Killers** do of course want a kill-or-be-killed world with open PvP everywhere. Not much more to write about that.

**Achievers** usually prefer PvE gameplay to train their character and achieve measureable and comparable goals (like beating a specific boss or acquiring an ultra-rare item). But they also enjoy some optional PvP from time to time, because it allows them to show off how strong their character is. Achievers will only be interested in PvP as a main game mechanic if it provides them with tangible rewards which let them advance faster than they could through PvE gameplay.

**Explorers** might find some enjoyment in discovering the PvP metagame, but when they want to explore the world or run a series of experiments, then some other player trying to kill them is just a nuisance. They usually hate it when you hide interesting world details in PvP zones, because they can't explore them at their own pace.

You would expect that **Socialisers** are peace-loving pacifists who are opposed to PvP on principle. But that's not completely true. Many socialisers enjoy to organize and coordinate teams for faction-based PvP. So while they often do not get much out of one-vs-one unorganized PvP, they can get a lot out of organized guild-vs-guild PvP systems.

If you want to create a game with the broadest appeal as possible, then you need to make sure that each of these player categories can indulge in the kind of PvP interaction they enjoy most and avoid the interaction they dislike. But that can be difficult to do in one single game. Especially considering that MMORPGs are already the most expensive type of game you can create.

So you might want to pick one of these archetypes as your primary demographic and design your PvP system around their needs.

# Answer
> 1 votes
I think this question is highly opinion based.

But i like it, so here are my thaughts:

**1-Safe Zones:**

good idea. To avoid your cons make players invulnerable while talking to npcs. This will also prevent Mobs interrupting the player reading the quest texts. Only allow talking while not in fight. While doing quests you can get killed. This is an PvP MMO.

**2-PvP Zones**

Totally different MMO. This depeds on what you want. If you want an PvP-MMO i wouldn't reccomend this. If you just want some PvP this would work great.

**3-PvP Toggle**

again something different. I think in Bless online you can buy buffs (ingame and relatively ceap) that disable PvP for a limited time. This depends really on the community. Maybe most people would disable or enable it.

**4-Seperate Servers**

This could happen automatically with Version 1 or 3. Maybe the players declare an server as inofficial PvP or non-PvP Server. Otherwise everything like you stated.

**5-Time Specific 6-Special Days**

Sounds like the same to me. I wouldn't recomend this. As you said, players will wait in the safezones and this gets boring. The other Versions at least always have the same danger, so you leave the zones, or you look for an other game.

**7-Level Specific**

This works great with 2. Just change it a little bit. You can attack everyone, but if you kill a lower level Player you get a debuff. Let's say it depends on the player Level. Die debuff decreases your health and damage for 30min (maybe up to 1/2). Make this debuff stackable, so if you kill 2 low level players you have 1/4. With this you can help friends, but at a cost. You can try some additional rules:

* this debuff only applies if you attack first.
* it is stronger the lower your oponent is.
* if you are already in a fight and you attack a new joined low level player before he attacks you, it still gets applied to avoid you with a friend staying infight to avoid the debuff.
* use **8-Arenas** to make big fights without debuff

**My choise**

I would choose a combinaton of 1 and 7. If you are invulnerable while talking to NPCs this can't get exploited. You are even able to go afk if you have to. Point 7 should keep players from slaughtering weaker ones because of the debuff, while allowing to attack others at the same level. Cons: Everyone that is not in a Safe Zone or talking to an NPC can get killed. (probably will not because of the debuff). But since you wanted an PvP MMO i think this should work.

For The Servers. Ask your community what they want. That means at least prepare a non-pvp Server to be possible.

---
Tags: game-design, mmo, combat, pvp
---


title: Tilemap shader confusion

text:
# Question
Title: Tilemap shader confusion
I am trying to setup a system for utilizing uvs to tile a texture and reduce draw calls. I'm using Unity. I create a texture which records the x index of the tile from a tileset into the red channel and try to use it in the shader. Here's the shader code:

```
        sampler2D _TilemapTex;
        sampler2D _MainTex;
        float _MaxIndex;
        vector _TilesetDim;
        vector _TilemapDim;

        struct vertexInput {
            float4 vertex : POSITION;
            float2 texcoord: TEXCOORD0;
        };

        struct vertexOutput {
            float4 pos : SV_POSITION;
            float2 texcoord: TEXCOORD0;
        };
        vertexOutput vert(vertexInput v)
        {
            vertexOutput output;

            output.pos = UnityObjectToClipPos(v.vertex);
            output.texcoord = v.texcoord;
            return output;
        }
        float4 SampleMap(float2 texcoord) {
            return tex2D(_TilemapTex, texcoord).r * 255;
        }
        float4 GetUv(int index, float2 texcoord) {

            int xpos = index;
            int ypos = _TilesetDim.y - 1;
            float2 uv = float2(xpos/_TilesetDim.x, ypos);
            float xoffset = frac(texcoord.x * _TilemapDim.x) / _TilesetDim.x;
            float yoffset = frac(texcoord.y * _TilemapDim.y) / _TilesetDim.y;
            uv += float2(xoffset, yoffset);
            float4 main = tex2D(_MainTex, uv);
            return main;
        }
        float4 frag(vertexOutput i) : SV_Target
        {
            int index = tex2D(_TilemapTex, i.texcoord).r * 255;

            return GetUv(index, i.texcoord);
        }`

```

I'm a beginner with shaders so maybe I'm missing something simple. Here's the result:

It looks interesting but I expected it to fill entire tiles.

# Answer
> 1 votes
I figured it out. The problem was that the texture I used for sampling wasn't point filtered so that's where the weirdness came from.

---
Tags: unity, shaders
---


# Question
Title: Why does a call to vkCreateInstance() take noticeable time to complete?
I decided to learn Vulkan and started writing a simple program. I then ran the program (which only called vkCreateInstance()) to see if the Vulkan instance was created successfully and was shocked to see that my computer's fan started spinning loudly (and kept doing so for 5 seconds) and I saw a spike of 8% of the computer's processes being used for a second(and the function call took **1.5 billion cycles** -- enough to make the program's loading time noticeable). Complaining about a one second CPU-usage spike would seem humorous if the spike were due to a loop doing hundreds of function calls, but I only called a single function once (vkCreateInstance()). Is there a way to reduce the overhead of some of Vulkan's functions and should I be using Vulkan for 2-D rendering?

Here is the code that took 1.5 billion cycles to run:

```
VkInstance instance;

VkApplicationInfo appInfo = { 0, 0, 0, 0, 0, 0, 0 };
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "Hello Triangle";
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.pEngineName = "No Engine";
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.apiVersion = VK_API_VERSION_1_0;

VkInstanceCreateInfo createInfo = { 0, 0, 0, 0, 0, 0, 0, 0 };
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.pApplicationInfo = &appInfo;
createInfo.enabledExtensionCount = 0;
createInfo.ppEnabledExtensionNames = NULL;

VkResult result = vkCreateInstance(&createInfo, NULL, &instance);

```

# Answer
> 4 votes
vkCreateInstance does a lot of things, one it looks for all the installed driver ICD dlls by looking through the registry (in linux it looks through pre-agreed folders) and parsing json files the registry refers to and loads those dlls. Then the loader negotiates an API version with each of them. Then it finally calls vkLoadInstance in each of the dlls.

Each ICD will then create and/or load the vkPhysicalDevice it is associated with so you can query its properties.

That's a lot of stuff to do, however it only needs to happen once in each application so it's not worth optimizing that much.

A similarly expensive function is vkCreateGraphicsPipeline which creates a vkPipeline object that encodes all information needed to render a triangle. Optimization is what will take most time there, spending a few milliseconds to save a nanosecond per fragment is worth it when you render to anything above 420p or even more than once.

The functions that are called often and in the critical path are the ones that are cheap. This can happen because a lot of processing is front loaded into specific function calls that you can call on a separate thread to keep the main thread running along.

---
Tags: vulkan
---


# Question
Title: Multiplayer netcode where all units, including server, are untrusted - possible, feasible, etc.?
Most professional video games use either a peer-to-peer architecture or a client-server architecture. In the former, clients often trust each other, and instead employ anti-cheat techniques to ensure that all clients are using the same version of the game. In a client-server architecture, the company-owned server manages the game, and each client only needs to trust the server without trusting any other client.

My question is: how might I write a game network architecture such that the *server* is not necessarily trusted either (e.g. it is another client, or is buggy, or has been compromised), and do so in a way that does not take too much processing power away from the game?

I know that the blockchain algorithm (as infamously used by Bitcoin and other cryptocurrencies) does provide this as long as at least half of the computing power is owned by trusted machines. While this may work for long-term actions (such as match verdicts), it doesn't work as well for the frame-by-frame actions of action games and can also be too slow for turn-based games, to say nothing of the computing power it requires of the clients or of any dedicated servers.

# Answer
**The client is in the hands of the enemy**

I forgot where i read this, but it's really useful while coding client-server architectures. Basically it means you can't trust the input from the clients and have to check if it's possible. In your case you also have to check the input you get from the server.

For Example:

* Strategy: keep also track of enemys resources and units. Is it possible to build them? How fast are they?
* Shooter: How much ammunation does the enemy have? How much did he use? Is his movement valid?

These checks should not take too much time in your gameloop and can at least verify if the actions are allowed.

The Problem with this solution is, that your client has to know everything. So it's easier for hackers to see where the enemy is, how much resurces he has, and so on.

In an standard client-server architecture the server decides which input is valid and which one is not. In your architecture each client decides this for himself. So maybe display a warning that the recieved data is inconsistent. The Players then can decide if they want to keep playing, or end the game. (Only show this once a match!)
> 1 votes

---
Tags: networking, client-server, anti-cheat
---


# Question
Title: Is there a way to run an Android Unity game in Windows?
I was wondering, given a generic Unity game built for Android (with no desktop version), if I could somehow run it on windows (not in an android emulator) by using the windows version of mono.

The theory is that the script assembly (if the scripting was done in c#) is separate from the game engine.

I tried replacing the Data folder of a windows game with the Managed folder from the Android apk but got this error:

> Failed to load PlayerSettings (internal index #0). Most likely data file is corrupted, or built with mismatching editor and platform support versions.

Is there some tool I can use to change the platform of a third party unity game in order to play it ?

I'm not an unity developer myself but my concern is that games could use features not supported on desktop...

# Answer
The simple answer is No.

When a game is compiled, it includes all assets for the platform it is compiled for only. This means the android version includes code of how to handle everything with Android's libraries. As a result, this is an android game, almost oblivious to the fact that it was made with Unity, as such, the only ways to run it are the same as if it was any other android app.
> 1 votes

---
Tags: unity, android, windows, cross-platform, mono
---


title: Randomly generated maps in Multiplayer

text:
# Question
Title: Randomly generated maps in Multiplayer
I am currently trying to get randomly generated maps work in multiplayer but I have so many difficulties trying to figure out how. How do other games implement this(Minecraft, Terraria, Don't starve)? My current solutions are as follows.

**Generate the map client side and verify(Hash?)**

This is the least bandwidth intense but the algorithm needs to be **EXACTLY** the same as the server side and it is the easiest to exploit.

**Generate Server side and transfer to client**

This method will ensure that the players all have the EXACT same map, but it it very resource intensive for the server and requires a lot of bandwidth and increased loading times.

# Answer
It slightly depends on what kind of game you are making.

**Generate Server side and transfer to client**

If the player can make their own maps, or the map can be generated when a player is playing offline (but can later be shared online), then the best methods would be for the player to transfer the map to other players directly. I remember Warcraft 3 used a similar method, where every player that didn't have the map, would download it as soon as they join the room. I'm not sure though if it was done user to user, or with the server in-between.

It can also work to generate the map server side, and then give the data to all joining players. If the game is too large, then give a part of it to each player, similar to minecraft.

**Generate the map client side and verify?**

I find this idea really bad. However, it could potentially work, if the maps that the player make are **very limited** and can be replicated with success. I can't think of an example that this has worked, maybe it has, maybe its just not worth it. At the end of the day, most of the resources have to be on the client's machine for this to work, so the more options they have when making a map, the bigger the final executable game will be (but the less resources you will have to send with your server).

At the end of the day, you are only sending a few data that describe the new map, you are (most likely) not sending new assets as the new map is using assets that already exist in the client's game, so the resources sent by your server aren't that big. An html website is far bigger than that, and you can navigate to them almost instantly.
> 6 votes

---
Tags: multiplayer, procedural-generation
---


# Question
Title: Screen Capture rendered on a RenderTexture in Unity
I have a pretty wild idea for a unity application that would work on a multi-display setup.

The app would be running in full screen mode on one of my displays, and the contents of the remaining two displays should be rendered in-game on a texture.

I've seen RTMP clients for unity and I've tried streaming my desktop with OBS to a local RTMP server but the delay was too big (more than 5 seconds). I would prefer an instant (or very low delay) solution for mirroring my displays on textures in Unity.

If anyone can help me solve this, i would appreciate it!

# Answer
I found one possible solution, but I haven't had time to try it. I will make a separate program that captures screenshots at around 30 FPS using DirectX (SharpDX) and these frames will be pumped into some sort of Socket (UDP or TCP) and a separate thread in Unity will receive and decode them and turn them into a Texture.
> 1 votes

---
Tags: unity, rendering, screen, rendertexture, streaming
---


title: Nuget in Unity with Mac OS

text:
# Question
Title: Nuget in Unity with Mac OS
I have moved over to Mac for Unity development, and am aware you can still use Windows .dll files in your project. I use NuGet as a secure method of getting specific dlls, and have usually done this on Windows by manually downloading the .nukpg and extracting the .dlls using WinRAR, then putting the dlls in Unity. So far, I have thought of two ways to do this on Mac:

1.) Doing the same thing, but with a WinRAR alternative that can open .nukpg

2.) Using Visual Studio for Mac that has a NuGet interface built in with Unity

Has anyone done this, or found a solution for getting package from NuGet in Unity for Mac?

# Answer
> 4 votes
While there's no built-in support for NuGet yet, this might change soon since a lot is happening in this regard. With Unity 2018.1, .NET Standard 2.0 finally got supported. This is a *huge* deal since it makes a lot of libraries accessible to Unity developers. Check out this Unity blog post for some information.

Until then, the process is pretty much as you described. Download the NuGet package, rename it from `nupkg` to `zip` which you then can unzip (in the finder, no 3rd party software needed) and use the `.dll` in your project. I've found this blog post on the topic (which might be a bit outdated by now but describes the whole process pretty well).

You might try NuGetForUnity. I didn't have a chance to check it out yet, but it looks really promising.

Visual Studio won't help too much (right now at least), since Unity handles project files a bit differently. Adding dependencies in Visual Studio will have no effect in your Unity solution.

---
Tags: unity, visual-studio, macos
---


title: Two Army Battle Simulator

text:
# Question
Title: Two Army Battle Simulator
I'm currently developing a small game project on unity (with purpose of learning C#) where each player controls a base and can build buildings, do research, build units, pretty much the basis.

I arrived where the each player may send their army of different sizes to attack the other player's base. Each army can be composed of three different unit types, being `Infantry`, `Archers` and `Cavalry`. They work as a kind of rock-paper-scissors, meaning `infantry` beats `cavalry` given equal resources (horses cost more than warriors, so 1 on 1, cavalry still wins), `cavalry` beats `archers` and finally, `archers` beats `infantry` given a long distance.

Every unit has different stats, `health`, `damage`, `armor` and `range` (mouvement speed exists but I do not want to consider it in battle).

I want the battle to be split in rounds and that it is not because you have less soldiers than the other player that you should loose. What would be an interesting way of solving the battle taking account of all those variables ?

Sort of solution I have is to give each player some decisions as to what would he do first (either archers attack first, cavalry waits for flanks, etc.) but nit seems too complicated and I still don't know how each parameter should be calculated. Should luck be included too ?

Thanks, luisarcher.

---

**EDIT**

After comments, here is my question more clearly. What would be the best way to simulate a battle of two armies composed of those units (with their weaknesses and strengths) where both armies would loose troops in X amount of rounds ?

I want the results to evolve with time so the players can react to it (either retreat, or maybe small commands). I'm not looking for a piece of code, but more of a guideline of how should I use every attribute of each unit (`health`, `damage`, `armor` and `range`).

---

**EDIT2**

By best, I mean an interesting resolution where each unit feels unique to be built and where players won't feel forced to build only 1 kind of units since it has the most cost effective hp/damage per amount of resource spent. I'm thinking of something like all those web-based strategy games like Grepolis, Tribal Wars, oGame, etc.

# Answer
> 2 votes
Keep in mind that this is a design question, and you can handle it in many ways. There will be no "best" or "correct" option; there may, however, be bad design decisions.

Your fundamental design error is that you seem to have started from the wrong end in your design process: you already have attributes for your units, but have no concept for how the fights will be handled. Now you're stuck trying to think of how to use all these attributes in an interesting way, without considering whether or not all of them are really necessary. A better way would be to first come up with an idea of how you want a fight to be handled, and add unit attributes as needed.

Keeping that in mind, let's completely ditch all your current attributes. Now let's think about how a fight can be fought between two armies so that:

1. archers hold advantage over infantry, infantry holds advantage over cavalry, and cavalry holds advantage over archers
2. the fight has to last a finite amount of turns, in between which the player can make strategic decisions to alter the fight flow

The first question you should ask yourself is how many rounds you expect the fight to last. Two more or less equal sized armies will need to have a victor determined in that specified amount of turns.

In order to fulfill the requirement #1, you need to make sure that certain unit type deals more damage (or receives less damage) to another.

This is how the aforementioned browser strategy games like Tribal Wars handle the "rock-paper-scissors" balancing: each unit type has a universal `Attack` attribute, and then three different attributes for defense: `General Defense` against infantry, `Cavalry Defense` and `Archer Defense`. During the fight, the system calculates the total offensive strength of each unit type in the attacking army, and then divides the defending troops into groups to fight against said groups.

So for example, let's say you have 1000 Infantry, 500 Cavalry and 500 Archers. The total offensive strength will look as follows:

1. 1000 * `Infantry Offense` = Total Infantry Offensive Strength
2. 500 * `Cavalry Offense` = Total Cavalry Offensive Strength
3. 500 * `Archer Offense` = Total Archer Offensive Strength

The defense troops are then divided into three groups proportional to each of the three offensive groups, and the system uses their `Defense` attributes against the specific group they're fighting against to calculate the losses on each side. For instance, if the offensive strength of the Infantry group is 5000, and the defensive strength of the first defending group is 5000, then each side loses 50% of their units; however, if the values are 10000 to 1000, then the attacking side loses only one unit per ten defenders killed.

Then the only thing you need to do is to repeat the process for each round of the fight. Now you need to come up with the attribute values and balance them out in a way that would allow your fights to last for certain amount of rounds on average. Come up with a few scenarios to test it with, and adjust the values according to how you want your game being played.

# Answer
> 0 votes
You could try using a "Command and Colours" technique, as used in "Memoir '44" and "Battlelore" boardgames. It give both players a few orders to play in a turn and changes which orders each turn. This would also have to have a turn-based gameplay game. One order could be "5 Cavalry" or "All Infantry". This would limit each turns complexity but overall increase strategies. Would orders they get is luck based though.

Unfortunately, I don't now how to code this though.

Hope this helps.

---
Tags: unity, game-design, architecture, algorithm, simulations
---


# Question
Title: How can I snap a game object's position to a grid?
I'm making a game that involves "falling block" gameplay elements. The problem is, I'm not quite sure how to make it so that the blocks will snap to some kind of grid, in other words, I'm not sure how it will pick the closest cell to its position.

The blocks are not continuously snapping to a grid (i.e. they are subject to gravity). Any tips?

# Answer
> 18 votes
You can do something like this

```
int gridCubeWidth = 16, gridCubeHeight = 16;

cube.Position.X = Math.round(cube.Position.X / gridCubeWidth) * gridCubeWidth;
cube.Position.Y = Math.round(cube.Position.Y / gridCubeHeight) * gridCubeHeight;

```

This basically rounds the X and Y positions to the nearest multiple of the cube dimensions. Then scales it by the cube dimensions to get the uniform position.

# Answer
> 0 votes
In my quick research, when you are snapping some geometry onto a grid:

* As long as all the vertices of your polygon (in its final position) coincide with vertices of the grid (in other words, if what you're trying to snap fits nicely in the grid), then
* You can snap any of the vertices of your polygon to its nearest grid vertex, and apply the same translation to all the others. You will always end up with the same resulting position.

This means you can simply pick a vertex and round its coordinates, or, if you're using a grid with side larger than one unit, use Austin's expression:

`cube.Position.XorYorZ = Math.round(cube.Position.XorYorZ / gridCubeWidth) * gridCubeWidth;`

# Answer
> -4 votes
Math.ceil gives the right feel to snap the blocks to right grids

---
Tags: mathematics, grid
---


# Question
Title: How to associate multiple arrays of vertex data and uv data with an attribute? OpenGL ES
I create the buffers to to put on them the vertex data and uv data:

```
    ByteBuffer bb = ByteBuffer.allocateDirect(coord.getVertices().length * 4);
    ...
    vertexBuffer.position(0);

    ByteBuffer dlb = ByteBuffer.allocateDirect(coord.getIndices().length * 2);
    ...
    drawListBuffer.position(0);

    ByteBuffer uv = ByteBuffer.allocateDirect(uv.getUv().length * 4);
    ...
    uvBuffer.position(0);

```

Then I pass this vertex data using these buffer to shader with:

```
glGetAttribLocation(Shader.program_Image, Shader.V_POSITION);
...
glVertexAttribPointer(v_Location, 3, GL_FLOAT, false, 0, vertexBuffer);

```

and the uv data with:

```
glVertexAttribPointer(a_Location, 2, GL_FLOAT, false, 0, uvBuffer);

```

This allows me to render multiple shapes using ONE array, and I also can use a texture atlas and load a special of "multiple-texture", and at this point my app run correctly without any error, but I want to do now is have different arrays and send them to shader, to be able to transform only some arrays, I don't know if this is possible, for the moment I have tried without success, and I was thinking if there is a way to add all the arrays to the same buffer and how to do it.

# Answer
> 1 votes
> I want to do now is have different arrays and send them to shader, to be able to transform only some arrays, I don't know if this is possible, for the moment I have tried without success, and I was thinking if there is a way to add all the arrays to the same buffer and how to do it.

What you can do is use the same VBO, but only a specified range for each drawing operation. You can use `glMapBufferRange` to map the VBO from range A to B, pass the data, then make a draw call (`glDrawArrays`) that only renders from the range A to B. After that, you can map from range B to C and make a draw call that only renders from B to C.

You still have only one VAO. But a VAOs are agnostic, and you can make some trickery with the offsets that will make it work as if it had two layouts:

```
// Layout 0 for the 3D world
// 3D Pos
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, layout0_stride,
                      0); // look at the offset
// UV
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, layout0_stride,
                      4 * sizeof(GLfloat)); // look at the offset

// Layout 1 for the 2D UI
// 2D Pos
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, layout1_stride,
                      0); // look at the overlapping offset
// UV
glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, layout1_stride,
                      2 * sizeof(GLfloat)); // look at the overlapping offset

```

This is, of course, an example. It doesn't make much sense to have two layouts just to have a specific layout for 2D drawing. You could use the layout for 3D drawing for that, by simply not using the `z` component.

After that, you can use an uniform variable in the shader to specify which layout to use. If `layout_to_use` is `0`, then you use the `in` variables in the layout position `0` and `1`. If `layout_to_use` is `1`, then you use the `in` variables in the layout position `2` and `3`:

```
layout (location = 0) in vec4 in_pos3d;
layout (location = 1) in vec2 in_uv3d;
layout (location = 2) in vec2 in_pos2d;
layout (location = 3) in vec2 in_uv2d;
uniform int layout_to_use;

void main()
{
  if (layout_to_use == 0) {
    // Do thing with in_pos3d and in_uv3d.
  } else if (layout_to_use == 1) {
    // Do thing with in_pos2d and in_uv2d.
  }
}

```

When you use the VBO from range A to B, you enable the attribute pointers `0` and `1`, and set `layout_to_use` to `0`. When you use the VBO from range B to C, you enable the attribute pointers `2` and `3`, and set `layout_to_use` to `1`.

Before doing all that, you should consider if it's worth to add this complexity to your code. Depending on what you are doing, making a single big layout (wasting some bytes) could be a better option.

The other option is using multiple VAOs and multiple VBOs, which has nothing special about but binding each VAO and VBO that you will be using. A costly operation that I don't recommend.

---
Tags: glsl, opengl-es
---