# Question
Title: How does Physics2D.OverlapBoxAll work in Unity 3D?
I am using Unity to create 2D sidescroller game. In my game I have a person that does a melee attack. In order to implement this I am using Physics2D.OverlapBoxAll().

* The first parameter is the position of the box.
* The second parameter is the size.
* The third parameter is the angle.
* The fourth parameter is the layerMask.

I am having trouble understanding the second and third parameters. What does angle mean? Also I am having trouble understanding the size is relative to which units?

Relevant Code:

My Attack Function:

```
    void Attack() {
    Vector2 tempx = new Vector2 (AttackTransform.position.x, AttackTransform.position.y);
    Vector2 tempy = new Vector2 (AttackTransform.position.x + swordSwingRange.x, AttackTransform.position.y + swordSwingRange.y);

    Collider2D[] enemies = Physics2D.OverlapBoxAll (tempx,tempy,0,AttackLayerMask);
    Debug.DrawLine (AttackTransform.position, new Vector3(tempy.x,tempy.y, AttackTransform.position.z));
    print (enemies.Length);

}

```

Explanation: The AttackTransform is the starting position where I would like to instantiate my attack. tempx and tempy are the starting and ending positions respectively. 'enemies' is used to find the the number of colliding objects which i will later iterate to decrease health or something.

In my Debug.DrawLine function it draws a line from the start position to the endposition. Hence shouldn't it draw a line that represents the box that will be formed for Physics2D.OverlapBoxAll() ? However as I have experimented with that it does not so. So what scale of units do the aforementioned methods use?

Another side-question: Is this the best way to detect collision in front of me? Or is there a better way? Any links would be appreciated I can study up further!

Thank you so much for taking the patience to read my question! And I greatly appreciate the help!

# Answer
The `size` is measured in world units, measured from one side of the box to the other, with `point` specifying the center.

If I wanted a box running between (1, 2) at its bottom left to (3, 5) at its top-right, that would be `point = (2, 3.5)` (the center) and `size = (2, 3)` (total width & height in world units)

The `angle` is a z rotation applied to the box.

So if you create a new default cube primitive at the top level of your hierarchy, and set its scale equal to the size you want, and the z rotation to the angle, the result will match the area checked by OverlapBox.

We can also make a preview function to draw it:

```
void DebugDrawBox( Vector2 point, Vector2 size, float angle, Color color, float duration) {

    var orientation = Quaternion.Euler(0, 0, angle);

    // Basis vectors, half the size in each direction from the center.
    Vector2 right = orientation * Vector2.right * size.x/2f;
    Vector2 up = orientation * Vector2.up * size.y/2f;

    // Four box corners.
    var topLeft = point + up - right;
    var topRight = point + up + right;
    var bottomRight = point - up + right;
    var bottomLeft = point - up - right;

    // Now we've reduced the problem to drawing lines.
    Debug.DrawLine(topLeft, topRight, color, duration);
    Debug.DrawLine(topRight, bottomRight, color, duration);
    Debug.DrawLine(bottomRight, bottomLeft, color, duration);
    Debug.DrawLine(bottomLeft, topLeft, color, duration);
}

```

In your case, it looks like you want your first argument to be just `AttackTransform.position` if that's the center of your attack range (`Vector3`s can implicitly truncate to xy `Vector2`s, so you don't need to split out its components manually), and your second argument can be `swordSwingRange` on its own (assuming it's an end-to-end distance and not a half-extent)
> 1 votes

---
Tags: unity, c#, collision-detection
---


title: GODOT Change scene in node

text:
# Question
Title: GODOT Change scene in node
I will change a scene on button click. But not change the main scene with button.

Node structure:

```
main
- scene (with childs)
- button

```

button.gd:

```
func pressed():
    get_node("scene").change_scene("res://second_scene.tscn")

```

It doesn't works.

# Answer
> 2 votes
I would keep track of the current scene in a global variable called `current_scene` and try something like this:

```
func change_scene(scene_path):
    call_deferred("change_scene_deferred", scene_path) # waits until an idle period when nodes can be removed safely

func change_scene_deferred(scene_path):
    # remove current scene
    current_scene.free()
    print("FREED CURRENT SCENE")

    # instance new scene
    var s = load(scene_path)
    current_scene = s.instance()
    print("INSTANCED NEW SCENE")

    # add new scene to main node
    get_tree().get_root().get_node("Main").add_child(current_scene)
    print("ADDED SCENE TO Main")

```

# Answer
> 0 votes
Search and try.... I think this is a bad solution:

```
func pressed():
    var main= get_tree().get_root().get_node("main")
    var scene = get_tree().get_root().get_node("main/scene")
    main.remove_child(scene)

    var next_scene_resource = load("res://second_scene.tscn")
    var next_scene = next_scene_resource.instance()
    main.add_child(next_scene)

```

---
Tags: 2d, scene, godot
---


# Question
Title: How/whether to pool bullets for a shmup in Unity?
I'm working on my first Unity project, which (maybe naively) I decided to make a shmup.

I've been doing a lot of reading about Unity, and about object pools, and about using components to control behaviors of game objects.

Right now my idea for how a bullet works is that each bullet should be a game object, with a component that controls how it moves, and another component that controls what happens when it collides with something it can damage. Depending on the enemy or player shooting the bullet, however, the way it moves or how it deals with collisions may be entirely different, which means that a bullet from enemy A may need one component to control motion, but a bullet from enemy B may need a different type of component. (And the same for damage-dealing.)

If I want to pool bullets, since a shmup tends to need a lot of bullets all the time, I'm not sure how to handle "resetting" the bullets when I'm done with them and grab them out of the pool to use the next time.

So my question is, what is the ideal way to design a bullet system for a shmup in Unity, from the point of view of an expert in Unity instead of my beginner perspective? Am I going about using components wrong? Should I have a completely different pool for each possible type of bullet (which may not be feasible since I want a good amount of variety in the game)? Should I just have one monolithic motion control component that has a ton of code and can control every imaginable type of motion a bullet could ever need (I hope not)? Should I just forget about pooling and use Instantiate and Destroy? Is there a good way to reset what components are attached to a GameObject to the state of its prefab when I'm done with it?

I'm afraid my beginner-ness to this ecosystem makes it hard to even know what the right question is.

# Answer
> 3 votes
Your idea with various movement components and damage components isn't bad.

However, if you want to combine this with object pools, then removing and adding the appropriate movement components whenever you reuse a bullet makes object pools less useful. You still have expensive teardown and setup. I see two options to prevent this:

* Use a separate object pool for each kind of bullet
* Put all your movement-components on the bullet but only activate one at a time. Your bullets will now consume more memory, but we are talking about a few **byte** per bullet.

# Answer
> 0 votes
So if we were talking old school smhups I really wouldn't bother with trying to optimize much as you'd only have a few bullets on screen at a time. But with bullet hell it gets a bit more trickier as the engine would be dealing with a lot of objects that need to be enabled and disabled and unitys build in 2d physics.

A while ago I found a post on shmups.system11 that showed a neat implementation ( not unity tho ), unfortunately my google search can't find the thread but Ill update this answer once I do.

I don't know the exact implementation but the idea is to have your own custom particle system that updates each point ( in this case points represent bullets ). The elaborate part on this particle system is that you need a way to draw the visuals at each point and you need to handle collision yourself.

Unity offers an API to make custom draw calls and simple rectangle/circle collision isn't complex. I'm pretty sure you can also make use of the physics engine Unity provides but this is something you'd have to discover yourself ( I don't have the proper knowledge )

I can not say how much performance you win by this but I'm sure that if done correctly:

* There is potentially less overhead ( instantiating game objects, registering events, firing events, etc vs adding a much simpler data object to represent a bullet).
* Could be more cache friendly, making use of flat data ( a continuous array representing your particles ), meaning you can let the cpu do more in one cycle.

Now it should go without saying that depending on your needs and implementation your code affects performance as well. All this should be measured. If you work with just instantiating and pooling game objects and it runs well on your lowest target you could consider just going that route.

# Answer
> -2 votes
**I suspect you are wasting your time.**

Unity is garbage collected. This means:

* Allocation is fast.
* Deallocation is, on average, fast.

The downside of garbage collection is that the collector must examine every object in memory, which means:

* Potentially long pauses.
* Speed is proportional to the amount of memory you are wasting.

However, a collection cycle that examines a few thousand objects is likely to be very quick, and you will probably never have more than a few thousand live objects in a bullet hell game. Long pauses occur when you have an application that stores millions of objects.

Similarly, the memory footprint of a few thousand bullets is likely to be rather trivial, probably less than 1MB.

I suggest quickly making an enemy that spams say 5000 bullets a second and seeing what effect this has on performance.

---
Tags: unity, shoot-em-up, object-pools
---


# Question
Title: Feasible to do all game logic on PHP server?
For the turn-based browser Flash RPG I'm working on, I'm keeping all player stats in a MySQL database, with PHP as the go-between, for the sake of persistence and to prevent cheating by memory editing. But then it occurred to me that someone could cheat by hacking the client as well by, for example, repeatedly calling the function which adds gold to the database by posting arguments to a PHP page. That means I have to do all logic on the PHP server to prevent that.

Is that a feasible thing to do? My end goal is to have a commercial game that could have a large number of people playing at the same time, and I assume I need to be mindful of the number of operations being performed on the PHP server as well as the number of queries being made to the MySQL database. Although when I look at various web hosting providers that provide PHP and MySQL, none of them seem to mention any limitations on those two things. I'm hoping speed won't be an issue as well. On the free test server I'm using, it takes a couple seconds to get a result back from the database, but you get what you pay for.

# Answer
It depends on your skill at programming, but it should be feasible. Remember, Facebook was built in PHP and it serves a pretty big crowd. A better question might be if PHP is the *best* choice for what you are trying to do. (And the answer is probably "no", unless it's the only language you know and you're not interested in learning a new one).

You will need a better hosting provider, though.
> 3 votes

---
Tags: flash, actionscript-3, php, anti-cheat, mysql
---


# Question
Title: Can I use inheritance to inherit properties from the editor?
The title might not be very clear, so I'll give an example.

Let's say I have two types of buttons in my game's UI : buttons of the category A and buttons of the category B.

They are both very similar, and have the same "Normal Color", "Highlighted Color", etc. The only difference is that they have a different "Pressed Color". For example, A buttons are red when pressed and B buttons are blue.

Now I could create two different prefabs as models for A buttons and B buttons, and call it a day, but I might end up adding some more categories of buttons later (C, D, etc.). And each one has a different "Pressed Color". And if I decide to change the "Normal Color" for each button, I would have to change it in each prefab.

So is there a way to do some kind of... prefab inheritance I guess? For example, each category prefab would inherit from a more high level prefab that would define the "Normal Color", "Highlighted Color", etc.

If yes, how?

# Answer
Not really, no.

The best solution I can think of is a script that will modify the values to the desired ones, and then that script can be subclassed to have different values.

This could *probably* be done as an editor script and update the prefabs, but I'm not sure.
> 1 votes

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


title: Lighting in 2d isometric games

text:
# Question
Title: Lighting in 2d isometric games
I want to add lighting to an isometric game that I'm working on.

The closest I've come so far is to do a pass over the blocks on the floor and build up a light intensity matrix (based on how far each one is from the nearest light source). Then I've been rendering that with overlay compositing enabled.

This sort of works as a rough prototype, but there are some problems and I don't know whether they're inherent limitations of the way I'm storing the scene.

The floor blocks are stored in a 2d array and the world entities are stored in a list with their own 2d coordinates and height.

That means that if I overlay a light map like I did in the example earlier, the shadow only covers the tile. Entities on the tile are only partially effected by that tile's light value.

Here's an example where the blue tile is the overlaying light tile without blending turned on.

If that character was at the edge of the map, the top half of their body would be unaffected by the lighting.

I could trace rays out through the scene and mark the colliding faces with lightness values, but at that point, I'm not sure how I'd actually render that lightmap onto the screen.

How can I construct a light map that can be rendered over this scene?

# Answer
> 2 votes
A better, yet very similar approach, would be applying the light matrix during the sprite rendering, tinting it with overlay blending using the sampled position of the tile it belongs to. That way, not only will you prevent the issue at the edge of the map, but also, tall sprites will correctly be affected by the tile they belong to, instead of having their tall parts use the light from whatever tile is behind them.

---
Tags: lighting, html-canvas, isometric
---


# Question
Title: How do multiple render targets get rendered onto the back buffer(s) then screen?
I'm using DX11. I understand how render targets are created, set, and why they are used, but I am really unsure how this all plays together with presenting it to the screen.

Does the GPU automatically flatten all render targets onto the back buffer, and how does this work with multiple back buffers?

If I were to have multiple render-targets for deferred rendering, or some customized post processing shader (using a ping-pong model) how do multiple render targets get presented accordingly? I assume I have to set the final render-target used to be presented to the screen. But I am not sure.

# Answer
> 2 votes
The render targets become sampling textures for a final compositing pass shader rendering to the back buffer.

The GPU doesn't do any automatic flattening. It all has to be done in a shader.

Ping-pong is less often necessary now that GPUs can handle large number of texture sampling operations in a single pass.

Support for older GPUs may still require ping-pong for those effects such as ambient occlusion, ambient lighting, depth blur, bloom, etc.

Or for simplicity's sake it's easier to have each post effect be a separate process/module and this requires ping-pong between temporary buffers.

With recent GPUs combining the compositing passes inside a single shader can improve performance by reducing memory bandwidth as long as it doesn't hit the GPU's internal shader code size cache limit. This limit varies between GPU models.

The memory bandwidth penalty of ping-pong becomes more significant as the resolution increases (4K, 8K, ...) and GPUs become faster relative to their memory. This tends to even more significant for mobile and integrated GPUs as their memory bandwidth is very limited relative to GPU core speed.

Ping-ponging also introduces stalls in the pipeline: The GPU's tile dispatcher has to wait for the previous render to finish before using the render target as a texture in the next step. Doing this multiple times can quickly cause post-effects to become the largest consumer (\>50%) of your GPU render time. This is when it's time to consider combining post-processing passes if possible.

This is not DX11 specific. All of this applies to just about any GPU rendering APIs.

# Answer
> 0 votes
To answer your question about how multiple render targets are presented, it's not that simple but you can imagine at the end of your frame for rendering you have one output presented on screen (although you have rendered to multiple targets in that time).

Whether forward rendering or deferred rendering, you will end up sending a frame to the swap chain. In earlier versions of the swap chain, you grabbed a pointer to the backbuffer frame and rendered everything into it. Later, the addition of `SWAP_DISCARD` and `SWAP_SEQUENTIAL` were developed. These are the only compatible modes for UWP based applications. These require you to use the resolve resource call for MSAA render targets into the backbuffer, which ever one you choose you must resolve. This is usually your final frame composition as the backbuffer will not be multisampled.

Basically, you can create multiple render targets in memory, and render to each individually OR, you can set multiple render targets and tell your pixel shader to render to each one at the same time (with different data obviously). These render targets are usually have a shader resource view attached also, so they then can be used on the next render pass as source textures.

For example - very simple cascaded set

Pass 1 - Multiple targets

Render Diffuse Render Normals

Pass 2 - SSAO

Read Z Buffer Read Normals from Texture Render Ambient Lighting Frame

pass 3 - combine - Some use screen space quad

Combine Diffuse and Ambient Render to FinalBuffer

resolve resource to backbuffer

That was a simple example, but you can leverage that pattern to be able to use for on forward and deferred.

---
Tags: directx, gpu, deferred-rendering, frame-buffer
---


title: How to sort poker hands? c++

text:
# Question
Title: How to sort poker hands? c++
The examples below come from the answer by Steven Stadnicki in Determining Poker Hands

Suppose a player get a hand like A9772. I would like to store the hand as either 77A92 or, better yet, 7A927. A hand of two pair would be stored with the higher of the two pairs first, then the lower, then the 'kicker' (so, e.g., A9977 would store as 97A97). Three of a kind would be stored with one card of the three first, then the kickers, then the other cards (e.g., A7772 would be 7A277); a full house would be stored with one of its three and then one of its two (e.g., 99777 would be stored as 79779);

How can I do that? Suppose I have a vector of cards :

```
std::vector<Card> m_cards;

```

Or simpler a vector of int

```
std::vector<int> v = {3, 9, 7, 7, 2};

```

The goal is to sort the above vector as follows: 77932.

# Answer
You need to determine the **class** of your hand first. I.e. if the hand is "two pair", "full house" etc.

The answer you linked is only meant to compare hands with identical class. It does this by comparing their lexicographical orders (using the poker "alphabet") after the hands are sorted according to their class.

That means you should already know what class and which cards form part of that class. For example, given the hand

> 7, A, 9, 7, 9

You need to know that it's a two pair, of 9 and 7, already. So based on that, you sort based on the cards that form the two pair (7, 7, 9, 9), using the higher pair first:

> 9, 9, 7, 7, A

The "even better" part of the answer is not strictly necessary. It is a questionable micro-optimisation.

The idea is you can easily compare the hand against another two pair hand, like

> 9, 9, 8, 8, 10

By comparing the two, you will notice that the 9's are equal but the second hand's 8 is higher, so the second hand wins.
> 1 votes

---
Tags: c++, card-game, poker
---


# Question
Title: Why when getting random index from a List the index is higher then the List count?
What I'm trying to do is to get a random index not a number but index from the randomPatrol List and use it in the patrolPoints.

```
private void Update()
{
 if (mode == PatrolMode.Random)
        {
            var rn = randomPatrol[Random.Range(0, randomPatrol.Count)];
            randomPatrol.RemoveAt(rn);
            patrol = patrolPoints[rn];

            if (randomPatrol.Count == 0)
            {
                randomPatrol = new List<int>();
                for (int i = 0; i < patrolPoints.Length; i++)
                {
                    randomPatrol.Add(i);
                }
            }
        }
        else
        {
            patrol = patrolPoints[index];
        }
}

```

randomPatrol is List randomPatrol contain for example 100 int numbers. Also patrolPoints is a List contain 100 items.

I used a break point at the first few times it was getting some indexs. rn value was 13 then 27 then 41 and 44 and then after few more times I'm getting out of range exception on the line:

```
randomPatrol.RemoveAt(rn);

```

And I see that randomPatrol count is 93 but the index number in rn is 96. Not sure how the random chosen number can be 96 if the List count is 93.

The complete script:

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

[System.Serializable]
public class PatrolData
{
    public Transform target = null;
    public float minDistance = 5f;
    public float lingerDuration = 5f;
    public float desiredHeight = 10f;
    public float flightSmoothTime = 10f;
    public float maxFlightspeed = 10f;
    public float flightAcceleration = 1f;
    public float levelingSmoothTime = 0.5f;
    public float maxLevelingSpeed = 10000f;
    public float levelingAcceleration = 2f;
}

public class PatrolOverTerrain : MonoBehaviour
{
    public FlyToOverTerrain flyOverTerrain;
    public LookAtCamera lookAtCamera;
    public UserInformation userinformation;
    public enum PatrolMode { Clamp, Wrap, PingPong, Random };
    public PatrolData[] patrolPoints;
    public PatrolMode mode = PatrolMode.Wrap;

    private int iterator = 0;
    private int index = 0;
    private float lingerDuration = 0f;
    private int overallLength = 0;
    private List<int> randomPatrol = new List<int>();
    private PatrolData patrol;

    public bool autoFreedomPatrol = false;
    public List<GameObject> Targets = new List<GameObject>();
    public string tagName;
    public Vector3 distanceFromTarget;

    public void Start()
    {
        if (tagName != "")
        {
            GameObject[] tempObj = GameObject.FindGameObjectsWithTag(tagName);

            for (int i = 0; i < tempObj.Length; i++)
            {
                //Add to list only if it does not exist
                if (!Targets.Contains(tempObj[i]))
                {
                    Targets.Add(tempObj[i]);
                }
            }

            //Get the current Size
            if (tempObj != null)
            {
                overallLength = Targets.Count;
            }

            GeneratePatrolPoints();

            for (int i = 0; i < patrolPoints.Length; i++)
            {
                randomPatrol.Add(i);
            }
        }
    }

    private void OnEnable()
    {
        if (patrolPoints.Length > 0)
        {
            lingerDuration = patrolPoints[index].lingerDuration;
        }
    }

    private void Update()
    {
        int length = patrolPoints.Length;
        if (!flyOverTerrain) return;
        if (patrolPoints.Length < 1) return;
        if (index < 0) return;

        if (mode == PatrolMode.Random)
        {
            var rn = randomPatrol[Random.Range(0, randomPatrol.Count)];
            randomPatrol.RemoveAt(rn);
            patrol = patrolPoints[rn];

            if (randomPatrol.Count == 0)
            {
                randomPatrol = new List<int>();
                for (int i = 0; i < patrolPoints.Length; i++)
                {
                    randomPatrol.Add(i);
                }
            }
        }
        else
        {
            patrol = patrolPoints[index];
        }
        if (lingerDuration <= 0)
        {
            iterator++;
            switch (mode)
            {
                case PatrolMode.Clamp:
                    index = (iterator >= length) ? -1 : iterator;
                    break;
                case PatrolMode.Wrap:
                    iterator = Modulus(iterator, length);
                    index = iterator;
                    break;
                case PatrolMode.PingPong:
                    index = PingPong(iterator, length);
                    break;
                case PatrolMode.Random:

                    break;
            }
            if (index < 0) return;

            patrol = patrolPoints[index];

            flyOverTerrain.target = patrol.target;
            flyOverTerrain.desiredHeight = patrol.desiredHeight;
            flyOverTerrain.flightSmoothTime = patrol.flightSmoothTime;
            flyOverTerrain.maxFlightspeed = patrol.maxFlightspeed;
            flyOverTerrain.flightAcceleration = patrol.flightAcceleration;
            flyOverTerrain.levelingSmoothTime = patrol.levelingSmoothTime;
            flyOverTerrain.maxLevelingSpeed = patrol.maxLevelingSpeed;
            flyOverTerrain.levelingAcceleration = patrol.levelingAcceleration;

            if (lookAtCamera != null)
            {
                lookAtCamera.target = patrol.target;
                lookAtCamera.RotationSpeed = 3;
            }
            //userinformation.target = patrol.target;

            lingerDuration = patrolPoints[index].lingerDuration;
        }

        Vector3 targetOffset = Vector3.zero;
        if ((bool)patrol.target)
        {
            targetOffset = transform.position - patrol.target.position;
        }

        float sqrDistance = patrol.minDistance * patrol.minDistance;
        if (targetOffset.sqrMagnitude <= sqrDistance)
        {
            flyOverTerrain.target = null;
            if (lookAtCamera != null)
                lookAtCamera.target = null;
            lingerDuration -= Time.deltaTime;
        }
        else
        {
            flyOverTerrain.target = patrol.target;
            if (lookAtCamera != null)
                lookAtCamera.target = patrol.target;
        }
        distanceFromTarget = transform.position - patrol.target.position;
    }

    private int PingPong(int baseNumber, int limit)
    {
        if (limit < 2) return 0;
        return limit - Mathf.Abs(limit - Modulus(baseNumber, limit + (limit - 2)) - 1) - 1;
    }

    private int Modulus(int baseNumber, int modulus)
    {
        return (modulus == 0) ? baseNumber : baseNumber - modulus * (int)Mathf.Floor(baseNumber / (float)modulus);
    }

    public void GeneratePatrolPoints()
    {
        patrolPoints = new PatrolData[Targets.Count];
        for (int i = 0; i < patrolPoints.Length; i++)
        {
            patrolPoints[i] = new PatrolData();
            patrolPoints[i].target = Targets[i].transform;
            patrolPoints[i].minDistance = 30f;
            patrolPoints[i].lingerDuration = 3f;
            patrolPoints[i].desiredHeight = 20f;
            patrolPoints[i].flightSmoothTime = 10f;
            patrolPoints[i].maxFlightspeed = 10f;
            patrolPoints[i].flightAcceleration = 3f;
            patrolPoints[i].levelingSmoothTime = 0.5f;
            patrolPoints[i].maxLevelingSpeed = 10000f;
            patrolPoints[i].levelingAcceleration = 2f;
        }
    }
}

```

# Answer
> 2 votes
It's because you get the index from inside the list, instead of just getting a random int.

To illustrate this, let's say you create `randomPatrol` with only 6 elements, so the values go from 0 to 5.

The first time `Random.Range` gives you back 3, so since `randomPatrol[3]` is 3, then `rn` is 3.

Afterwards you make `randomPatrol.RemoveAt(rn)`, removing the value at index 3.

Now `randomPatrol` contains `0, 1, 2, 4, 5` at indexes `0, 1, 2, 3, 4`.

Now, if the next time `Random.Range` returns you 4, `rn = randomPatrol[4] = 5`. And when you try to `randomPatrol.RemoveAt(5)` you get the exception, since there's no more `randomPatrol[5]`.

To fix, you should change your code to this:

```
var index = Random.Range(0, randomPatrol.Count);
var rn = randomPatrol[index];
randomPatrol.RemoveAt(index);
patrol = patrolPoints[rn];

```

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


# Question
Title: developing a uci compatible chess engine
I have understanding of how chess engines work in theory. I know the algorithms like minimax and alpha beta pruning. I want to develop a UCI compatible chess engine.I know that UCI protocols are these: http://wbec-ridderkerk.nl/html/UCIProtocol.html but I don't quite get how the program is supposed to get those commands and how it is supposed to give result.

As minimal as it maybe, but a working model in a short time to test first is preferred. I'll add features on the go. Any tips are welcome. please guide me, thankyou.

If this is not the right place for this question, please guide me where to ask this.

# Answer
> 3 votes
My approach to this was launching the UCI engine process from within my chess engine and opening a read pipe and a write pipe to the process. You can then send and receive text commands to the chess engine using the pipes.

Assuming you are using C or C++ on Windows, you can see an example of this by looking at my project from several years ago: https://sourceforge.net/projects/etherealchess/

It's not the best code and it's probably not even threadsafe, but the AI header and source files demonstrate how to do what I just described (also I'm not sure why someone left a one star review with a positive note, and Sourceforge removed all of the five star reviews that had no comments).

---
Tags: game-design, chess
---


# Question
Title: When should I use GL_TRUE or GL_FALSE values?
When using `GLboolean`, should I just use `true` and `false` or should I use `GL_TRUE` and `GL_FALSE`? When should I prefer using `GL_TRUE` and `GL_FALSE`? or maybe I shouldn't care at all (Because both works)?

Here It is said that both are actually a different type.

But in some tutorial websites I've read, they use `GL_TRUE` or `GL_FALSE` on functions that requires `GLboolean`. Example:

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

```

Well, it works too if we substitute `GL_FALSE` with `false` in the code above.

# Answer
> 8 votes
It's only a matter of opinion and code style. You can use:

* `GL_TRUE` and `GL_FALSE`
* `true` and `false`
* `1` and `0`
* Or anything that can be converted to 1 and 0.

They all may have different types, but usually it does not matter because they all will be implicitly converted to `GLboolean` upon use.

Use whatever you want, any of them will work.

My only advice would be to choose *one* style and maintain the consistent usage of it across your code.

# Answer
> 2 votes
Those macros were created because C didn't have a true/false keyword like C++ does.

In C using `GL_TRUE` and `GL_FALSE` made the code easier to read compared to using just 0 and 1 so it was provided by the OpenGL headers.

In C++ you may as well use the builtin keywords `true` and `false` and enjoy your favorite IDE's highlighting feature. Or you may use OpenGL's macro to be consistent with OpenGL code.

* `GL_TRUE` is 1 and `GL_FALSE` is 0.
* C++'s `true` is also 1 and `false` is also 0.

It's guaranteed to work.

For portability however you must still use `GLboolean` and not `bool` for any GL functions demanding a **pointer** to `GLboolean` (such as `glGetBooleanv`) even if they happen to be the same size on current platforms. That may not be the case in the future.

But assigning `GLboolean b = true;` is perfectly safe.

---

To answer the comment on explicitly comparing to `GL_TRUE`/`GL_FALSE`:

It's generally a bad idea to compare to `GL_TRUE` or `true` (eg: `if(x == true)`) as this may introduce hard to find bugs (eg: where x is 2). You should use simply `if(x)` as anything other than zero is considered true but may not be equal to `GL_TRUE` or `true` and this may create an inconsistency between what your code thinks is true and OpenGL's interpretation.

`GLboolean` are not `bool` and may (accidentally) contain a value other than 1 or 0. This can cause some confusion and the comparison failing can result in a red herring and many hours of debugging down the wrong path when tracing code.

Comparing to `GL_FALSE` or `false` is safe (both `==` and `!=`) as only 0 can be `false`.

So if you wish to use an explicit comparison use `if(x != GL_FALSE)` to consistently compare x to "true".

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


# Question
Title: Prioritizing prefabs in array for procedural generation
I am trying to create procedural space background with a bunch of sprites of nebulas and stars. I have made few prefabs with different types of sprites attached to them. I have created an array through which game will loop and randomly place different stars on a background.

The question is. I want for example 90% of white stars in the background and 10% of others. I know I can create few loops for each prefab with a different maximum number, but it doesn't look very efficient. Is there any way to prioritize some array items while looping through an array?

# Answer
Decide your total star count. Divide it into segments. For example, out of 100 total stars:

* 10 Blue Star Hard
* 30 White Star Medium
* 60 Red Star Soft

Code:

```
//can make enum StarColour
int BLUE = 0;
int WHITE = 1;
int RED = 2;

//can make enum StarFocus
int HARD = 0;
int MEDIUM = 1;
int SOFT = 2;

int i = 0;
for (i = 0; i < blueHardTotal; i++)
{
    PlaceStar(BLUE, HARD);
}

for (i = blueHardTotal; i < blueHardTotal + whiteMediumTotal; i++)
{
    PlaceStar(WHITE, MEDIUM);
}

for (i = whiteMediumTotal; i < whiteMediumTotal + redSoftTotal; i++)
{
    PlaceStar(RED, SOFT);
}

```

This takes you through index `[0]` to `[99]` in segments. P.S. There is nothing inefficient about this; and if you make the `Total`s compile-time constants, then the compiler should unroll the loops, thereby avoiding all conditionals.

If you want a more elegant way:

```
int[,] totals; //index in here by colour and focus, e.g. totals[RED, SOFT]

int i = 0;
for (int c = 0; c < COLOUR_COUNT; c++)
{
    for (int f = 0; f < FOCUS_COUNT; f++)
    {
        int max = i + totals[c, f];
        while (i < max)
        {
            PlaceStar(c, f);
            i++;
        }
    }
}

```
> 1 votes

---
Tags: unity, mathematics, procedural-generation, random, procedural
---


# Question
Title: how to sync clients and local avoidance in mobile RTS game?
I have been making mobile RTS game in Unity look like Clash Royale similarly.

Unfortunately, I faced to two big problems.

First is two phones(clients) to be synchronized each other in game state. And second is "path finding" or "local avoidance"(collision check).

To solve the path finding issue, I have searched about "Flow Field".

1. Should I do consider on 3 layer map(cost field, integration field, flow field) to apply "Flow field"?
2. If I do apply "flow field" to my game, can I have a liberty from the problem of Sync two clients?

Thank you in advance.

# Answer
(1) You should consider *at least* a 2-field map since you otherwise will be reading from the same map you are writing to, at the same time, which breaks spectacularly. I see no reason not to use the 3 fields you mentioned, if that keeps the data clearer and easier to debug.

(2) But no, I see no reason why flow fields in particular (which are just another pathfinding algorithm) should particularly solve any sync problems, since if the map is out-of-date by the time it arrives at another client, you will face exactly the same issues you would with any other solution.

What you need to look into is ways to deal with *latency*. Pathfinding algorithms themselves are not for that purpose, and flow fields are a pathfinding approach.
> 0 votes

---
Tags: unity, path-finding, rts, collision-avoidance
---


title: Agents going to the same position

text:
# Question
Title: Agents going to the same position
So more often than not I have a case where two agents get the same destination vector3.

This causes some hiccups because they won't be able to get to their target because they block for one another.

I was thinking that I am not the only one who has faced this issue and was wondering what you guys do to fix such an issue?

An example of this could be if I want my agents to go to the nearest tree and chop it down. Since both agents have the destination which is the trees transform they will go to the same position.

# Answer
If the tree example is representative, where the destinations the AI tend to bunch up at are "job sites," then you can solve this by using a claim system.

When an AI goes looking for a job to do, it searches for the nearest *unclaimed* job site. Then it places a claim on that job site before proceeding.

The next AI to search for unclaimed job sites of the same type won't be assigned the same one, because it's already been claimed.

When an AI needs to stop work (has a full load of wood to bring back, changes jobs, gets interrupted, dies) it releases its claim so that it doesn't gum up the works with claims that aren't currently in use.

One issue with this system is that if it acts globally, it can give the AI a kind of clairvoyance. Each one knows what every other is doing and which job sites *will* be in use, even if nobody's nearby yet. This can lead to strange behaviour like an AI who's been ordered to chop wood walking away from the tree right next to them (because it's been claimed by another AI who's still pathing over from the far side of the map).

To solve this you can introduce some hierarchy & local awareness to it. Say, have a resource patch entity that encompasses many trees. It knows how much harvesting capacity it has, and AI pathing from a long distance away can register their claim with the patch itself. Only once they get close do they bother claiming an individual tree. That way the coordination looks more like what can be accomplished with regular senses & shouted updates, rather than ESP or a central traffic control system. ;)
> 1 votes

---
Tags: unity, 3d, navmesh
---


title: How do you implement AABB?

text:
# Question
Title: How do you implement AABB?
I am having some trouble peforming an overlap test on a axis aligned bounding box.

Here is my code

```
public boolean overlapps(AABB other) {
    return false;
   }

}

```

I don't know how to implement this method.

---

Here is what I tried

```
public boolean overlapps(AABB other) {
    if(min.x <= other.max.x && max.x >= other.min.x) {
        if(min.y <= other.max.y && max.y >= other.min.y) {
            if(min.z <= other.max.z && max.z >= other.min.z) {
                return true;
            }
        }
    }
    return false;
}

```

# Answer
The easiest, and in some cases most efficient, way to test for this is to try to find an axis on which the AABBs do not overlap, since this avoid dealing with all the possible partial overlaps:

`return !(this.xmax < other.xmin || this.xmin > other.xmax ||
 this.ymax < other.ymin || this.ymin > other.ymax ||
 this.zmax < other.zmin || this.zmin > other.zmax)`

You'll find that this approach also translates to other related algorithms such as the separating axis test (this pretty much is a special case of it).

The actual sweep and prune algorithm has many variations (arrays or linked lists, single- or multiple axis, persistent etc.) and can be a lot harder to implement depending on which variation you choose.
> 0 votes

---
Tags: java, collision-detection, aabb
---


title: balancing a building game

text:
# Question
Title: balancing a building game
I'm working on a building game (the usual, build house X to produce resource A, which then lets you build house Y...) and I am now in the stage of balancing the various resource needs and productions.

Since I'm by far not the first person doing this, but couldn't find much practical advise on how to actually do it, I'm asking around: How to do the balancing math?

I thought about using a spreadsheet, but the main issue is not in the pure numbers but in the dependencies - if A then B. How many X are needed for Y to become available and does that fit to the stage of the game I want it to happen?

Which better ways than just playing for hours and tweaking the numbers exist? What approaches do you use to balance your economics games?

---

Additional details:

The game is a static build-your-village game. "static" means that time is not a factor - buildings provide a fixed amount of resources, not "x per minute". So a house provides housing for some peasants and a farm needs some peasants to work it, providing food.

So the things to balance against each other are resources. One trivial example: Farms need to provide more food than the peasants working on the farm plus the lumberjacks required to provide the wood for building the farm eat.

The goal of the game is resource-optimization. Doing the most with the resources available on the map. It is closer to a puzzle than to a clicker game.

Trivial early-game elements (see farm example) are easy to balance. But once you get into dependency trees (e.g. a 3rd level house needs A and B which are provided by X and Y, who need resources created at X2 and Y2, etc.) my intuition fails. Is X2 and Y2 balanced correctly or should they produce less? more?

I am not looking for specific answers, but for **methods** to approach this problem in general.

# Answer
EDIT: Since you added to your question that the resources are static, I’ll talk a bit about that specifically. I’ll leave the previous answer below the line as it might be useful to other people.

If your resources are static, there is going to be some limiting factor on them. This may be your starting resources or worker count that determine how many generators you can maintain. Those have to be distributed in such a way as to multiply them and invest them in other resources efficiently enough to get to your goal. In such a game there isn’t really “growth” per se, just different configurations and combinations. Like you said it resembles a puzzle more than a management game.

The method of balancing is similar though. First, you determine the win condition (what I called production goal before). This might be a certain amount of resources and/or buildings (e.g. have X free workers and X swords to arm them to overthrow the king). Next, calculate the ideal configuration to reach this goal with your current numbers (e.g. X swords need Y smithies which need Z workers, Q charcoal and V iron, which means you need W mines and R charcoal burners, which require resources and workers again and so on down to the most basic resources). You can partially automate this by using a script or spreadsheet that automatically adds the minimum amount of supporting generators for everything you add manually. Beware of loops (workers come from houses, houses need food, food comes from workers) as they complicate the math quite a bit.

Next, and this step is a bit more difficult, see if that configuration can actually be reached in forward play, i.e. can you get there from your starting resources. It’s possible to have a theoretical end configuration that can’t be attained in practice, because at some point several things require each other and you can’t build either of them first without already having the other. You can pretty much only find out about this through test playthroughs. In other words, since the order you buy things in is relevant, you can’t perfectly infer the solution from the result. Still, as you’ll likely understand your own methods of resource management you should be able to use the optimal strategies (e.g. build level 1 houses, use those workers to unlock level 2 houses which are more efficient, then replace all level 1 houses (or leave just as many as you have resources for them left over that you can’t use anywhere else)). Wherever necessary, add or remove buildings. You now have a new writeup of a solution that you know to work.

Once you have found an optimal or near optimal solution, you can begin to think about tweaking the numbers. Examine your spreadsheets and look for the following things:

* Numbers that stand out or don’t make sense, because those make the solutions unintuitive and harder to find (e.g. you need 200 mines but only one charcoal burner to support a furnace).
* Numbers that are directly proportional but at weird ratios (e.g. one mill supports exactly 3,791002 bakeries which produce enough for 2,1452 houses each), because those will irritate players who like to line up everything to work out exactly. Such ratios can be unavoidable if either multiple resources require the same resource or vice versa or because you want a little overhang, since exact numbers make it too easy to see how many you need.
* Opposite direction: numbers that are too simple. If you can just buy 1 or 2 of everything and the numbers line up, it’s too easy. Introduce small overhangs with simple numbers (one building gives 5, next needs 4 or vice versa) and make multiple things require the same resource in different amounts.
* Numbers that are needlessly large. You should only have big numbers, if it’s one of the basic resources that’s used by so many other buildings that high level production requires that much. If you can divide an entire production line by a natural number, probably do that.

Then consider how strictly you want your players to follow your solution. It’s probably advisable to include a little flexibility here, which means your starting resources (the limiting factors) should be a bit more generous than they have to be for a perfect solution. Also consider what exactly the challenge of your game should be. If it’s about finding the right combinations it might be too easy, as they might only have to build their way up the tech tree and slightly balance the numbers. If it’s about little tricks (like replacing lower tier buildings with more efficient higher tier ones) then this could be completely nonobvious and on the other hand is trivial once you’ve found out you can do it – you’d need several of such tricks to discover. If the challenge comes from different maps providing different starting conditions or supporting different generators, you need to balance these starting conditions against the solution every time.

---

My general approach is to try and find a single unit to balance for, as this greatly simplifies the mathematics involved. In your case this could be time spent.

Your variables will be something like amount of each resource, number of resource generators, resource gain per time per generator, resource use per time per generator (these two can be combined by using negative numbers), resource cost per generator and time spent. If your game includes something like generator efficiency (e.g. farms produce more/less depending on irrigation/space) assume an average value and wherever it makes sense also assume an average value of generators. The latter can be achieved by calculating the minimum number of generators to generate a stable output of the highest order resource (e.g. if you're calculating swords which need iron which needs ore and coal which needs lumber you can calculate the minimum number of mines, charcoal burners and lumberyards to support one smithy without going into negative production for any resource) and scaling up from there.

Whether you'll stay on the minimum depends on the amortisation rate of the generators, but I'd avoid going down that rabbit hole. Maybe do a second calculation afterwards with twice as many and see how the timing scales. If your game has something like research unlocks you can figure in the one-time cost of these as well, but only do so if the cost is high enough to make a perceivable difference in playtime. Don't try and factor in upgrades that increase production rates for now - if your game has them, just factor them in as a higher average production rate. Only upgrades that make a massive difference should have a place in your equations. You want to balance a game, not write a thesis in mathematics. Replace all variables with constants wherever you can.

Now set a production goal that represents player success and solve the equations for how long it takes to get there. If you don't actually have numbers for all of these things yet, reverse engineer from time by working your way up. How long should the player have to work to get stable tier 1 production lines, how long for tier 2 all the way up to a complete tech tree. By working your way up you already have the numbers for the prerequisites of the higher levels.

Once you've done you can try and experiment with external factors, such as space and terrain. These are usually mission specific, so they're as much a part of level design as systems design.

Now, how long a player should need to achieve something in order for the game to be engaging, that's something you'll need to playtest for and it heavily depends on how much the player has to do during playtime and how interesting the decisions they make will feel. That's where you might consider changing your numbers, for example by reducing the production of some generators in order to increase player actions per time (because they have to build more now) or by making the numbers line up imperfectly so it's not as clear how many buildings are ideal.

You won't ever get around playtesting a lot and with different people, but doing the spreadsheets first can give you a head start on what might make sense.
> 7 votes

---
Tags: game-design, balance, economy
---


# Question
Title: How can I prepare the different difficulty levels for my game?
I've though about creating the game for the easiest difficulty level, and from there scale up and create the other, more difficult difficulty levels, but I'm not sure it's the fastest way to go.

How should I create the different difficulty levels for my game?

# Answer
> 8 votes
There is never just one way to do things in game development.

But the usual unspoken consensus between developer and player is that "medium" represents the way the game is meant to be played. So you usually develop the game to be balanced on medium difficulty.

However, there is a general problem with difficulties: Players don't know how good they are at your game before they played it. So when they pick a difficulty at the beginning they don't yet know what's the ideal difficulty for them. Also, players rarely change the difficulty while they are playing, because it is quite an immersion breaker to be able to change the fairness of the whole world at a whim. That means if the player chooses poorly, they will have a bad time full of frustration or boredom.

A better solution than having preset difficulty levels can be to have an adaptive difficulty ingrained in your game design.

* Make the game harder for good players. No, I don't mean to make them weaker. Players expect to be rewarded for good play, not punished. Give them more or less of a challenge. For example, in a 4X strategy game, make the opponents band together against the player when the player expands too fast and ignore the player when they are weak.
* Make the basic goals relatively easy to achieve, but provide stretch-goals for completionist players which represent a far greater challenge. "So, you can beat the first level. But can you beat it in under 1 minute? Without getting hit? While killing every single enemy? And while collecting every single star in the level?". You can do that in form of achievements or with a medal system. Tell the player about these stretch-goals before they play the level for the first time, so skilled players can try to achieve all this on their first try.
* Provide ways to complete challenges faster and more rewardingly, but which require more skill to pull off. For example, when you have an RPG game, make sure that a player who uses advanced combat tactics can win a battle faster than when they just spam the basic attacks. That means players who have a good grasp of the game mechanics can advance through the story faster because they spend less time level-grinding. With "faster" I mean real-time, not game-time. This is where good UI design plays an important role.

# Answer
> 3 votes
Basically to define a base difficulty to scale (whether down or up), you must considerate a playable difficulty, one that engages the player on your game, with challenges (peak points) and points on the game where the player can feel relaxed, which are interest curves, basically every good entertainment content follows one.

On the programming side of things, you could play with normalized values, or have an explicit mapping. The example above is with normalized values as if they represented difficulty percentage, but all should be considered from base difficulty values (e.g., spawn quantities, drop rates, damage taken, etc.).

```
namespace Game
{
//For the sake of example, the values assigned are lineal to each other. It is up to the
//Game Designer to tweak the values.
public enum Difficulty
{
    Easy = 1,
    Medium = 2,
    Hard = 3
}

public class GameController
{
    public static float difficultyMultiplier;

    public void ChangeDifficulty(Difficulty _difficulty)
    {
        difficultyMultiplier (1f * (int)(_difficulty)) / ((1f) * (int)(Difficulty.Hard));
        // Cases examples:
        // Easy = 1/3 = 33.3% hard.
        // Easy = 2/3 = 66.6% hard.
        // Easy = 3/3 = 100% hard.
    }
}

public class Enemy
{
    float strength;

    public void HitPlayer(Player _player)
    {
        _player.HP -= (strength * GameController.difficultyMultiplier);
    }
}
}

```

I suggest you to read Jesse Schell's "The Art of Game Design: A book of lenses", which explains in more detail the Game Flows.

# Answer
> 2 votes
In general, as a matter of practicality, you might want to find a difficulty level that suits your and your testers' skills and balance around that to begin with. What name you end up assigning to that difficulty in the end is secondary and may very well change as designs evolve and emergent gameplay becomes more apparent.

However, where to start and whether it's easier to scale up or down also depends on the **kind of game** and **how you implement difficulty** levels.

Many shooters and RPGs simply assign modifiers to certain numbers (e.g. health points, damage). This is easy to implement, and easy to change later on, but often affects the volatility/randomness of challenges (e.g. random critical hits insta-killing the player on "hard") as well as their duration. With this method, I'd advise to find a good middle ground first (smooth, interesting gameplay) and go from there, in both directions. Start on "medium".

Another approach would be to keep the numbers the same, but add or remove obstacles and assistance depending on difficulty. For example, levels for a puzzle game might be easier to design around a fairly simple premise, with complications added in harder difficulties. Start on "easy".

A game focused around timing (e.g. racing game) or resource conservation (e.g. "get from A to B without running out of fuel") might be calculated around the worst case (highest difficulty) scenario where a player playing perfectly might just about make it, with additional pickups or more lenient parameters added in easier difficulties. Designing around the maximum possible score is especially useful in "score attack" games. Start on "hard".

---
Tags: game-design, difficulty
---


# Question
Title: How can I rotate the camera around the player on the Y axis on this code in Unity?
I have a problem, I want my camera to rotate along the Y axis while he is looking at the player with an offset. I want to rotate with Q and E key to right and left around the player but on my Camera Follow Player Script I used Vector3.SmoothDamp to follow the player on the other side when I try to rotate with Keys with transform.RotateAround() it seems like its locked on the Y axis I dont know how to get around this.

Code:

---

```
void CameraFollowPlayer()
{
    transform.position = Vector3.SmoothDamp(transform.position, player.position + offset,
                                             ref velocity, smoothSpeed * Time.deltaTime);
    transform.LookAt(player.position);
}

void RotateRightLeft ()
{
    if(Input.GetKey (KeyCode.E))
    {
        transform.RotateAround(player.position, transform.up, rotateSpeed * Time.deltaTime);
    }

    if(Input.GetKey (KeyCode.Q))
    {
        transform.RotateAround(player.position, -transform.up, rotateSpeed * Time.deltaTime);
    }
}

```

# Answer
Maybe it is because the axis you are passing on **RotateAround** is your local up (**transform.up**). You should use **Vector3.Up** instead if you want to do it on world coordinates, or **target's transform.up** if you want to rotate around the target's local up normal.

About the offset, you should consider getting a direction vector pointing towards the target, the basic formula is:

> **d = target - observer**

Having that vector, you'll have to normalize it (convert it to a Vector with magnitude of 1) to then multiply it by the desired offset, and finally is just up to assign the camera's position to the target's plus the offset.

A quick example code would be like this:

```
public class CameraExample : MonoBehaviour
{
    public Transform target;
    public float offset;
    public float rotationSpeed;

    void Update()
    {
        // Follow target at offset:
        transform.position = ((target.position - transform.position).normalized * offset + target.position);

        if(Input.GetKey(KeyCode.E)) transform.RotateAround(target.position, Vector3.up, (rotationSpeed * Time.deltaTime)); // Or transform.up, as I've suggested
        if(Input.GetKey(KeyCode.E)) transform.RotateAround(target.position, Vector3.up, -(rotationSpeed * Time.deltaTime));
    }
}

```

Hope it helps.
> 2 votes

# Answer
You could make a target position (a separate transform or Vector3) that rotates at a fixed distance around the player as controlled by key input, then use the SmoothDamp to make the camera gravitate towards that point.
> 1 votes

---
Tags: unity, c#, movement, rotate
---


# Question
Title: OpenGL GLSL using projection,view and transformation
I have been trying to get a simple triangle to render on the screen. I am using Projection, View and Transformation matrices but am unable to get anything to the screen.

Main loop

```
...
shader->start();

Matrix4f transformation = Math::createTransformationMatrix(Vec3<float>(0,0,-25),0,0,0, 1);
shader->loadTransformationMatrix(transformation);

Matrix4f camera = Math::createViewMatrix(Vec3<float>(0, 0, 0), 1, 0, 0);
shader->loadViewMatrix(camera);

Matrix4f projection = Math::getProjectionMatrix(1080,720);
shader->loadProjectionMatrix(projection);

glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(
    0,
    3,
    GL_FLOAT,
    GL_FALSE,
    0,
    (void*)0
);
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableVertexAttribArray(0);

shader->stop();
...

```

Math.h

```
static Matrix4f createTransformationMatrix(Vec3<float> translation, float rx, float ry, float rz, float scale) {
    Matrix4f matrix;
    Matrix4f::translate(translation, matrix,matrix);
    Matrix4f::rotate(toRadians(rx), Vec3<float>(1, 0, 0), matrix, matrix);
    Matrix4f::rotate(toRadians(ry), Vec3<float>(0, 1, 0), matrix, matrix);
    Matrix4f::rotate(toRadians(rz), Vec3<float>(0, 0, 1), matrix, matrix);
    Matrix4f::scale(Vec3<float>(scale, scale, scale), matrix, matrix);
    return matrix;
}
static Matrix4f createViewMatrix(Vec3<float> pos, float pitch, float yaw, float roll) {
    Matrix4f matrix;
    Matrix4f::rotate(toRadians(pitch), Vec3<float>(1, 0, 0), matrix, matrix);
    Matrix4f::rotate(toRadians(yaw), Vec3<float>(0, 1, 0), matrix, matrix);
    Matrix4f::rotate(toRadians(roll), Vec3<float>(0, 0, 1), matrix, matrix);

    Vec3<float> negativeCam(-pos.x, -pos.y, -pos.z);
    Matrix4f::translate(negativeCam, matrix, matrix);

    return matrix;
}
static Matrix4f getProjectionMatrix(int width, int height) {
    float aspectRatio = (float)width / (float)height;
    float y_scale = (float)((1 / tan(toRadians(FOV / 2)))*aspectRatio);
    float x_scale = y_scale / aspectRatio;
    float frustum_length = FAR_PLANE - NEAR_PLANE;

    Matrix4f projectionMatrix;
    projectionMatrix[0] = x_scale;
    projectionMatrix[5] = y_scale;
    projectionMatrix[10] = -((FAR_PLANE + NEAR_PLANE) / frustum_length);
    projectionMatrix[11] = -1;
    projectionMatrix[14] = -((2 * NEAR_PLANE * FAR_PLANE) / frustum_length);
    projectionMatrix[15] = 0;
    return projectionMatrix;
}

```

Vertex Shader

```
    #version 330 core

    layout(location = 0) in vec3 position;

    uniform mat4 transformationMatrix;
    uniform mat4 projectionMatrix;
    uniform mat4 viewMatrix;

    void main() {
        //Works but renders without any camera or projection applied
        //gl_Position.xyz = position;
        //gl_Position.w = 1.0;

        vec4 worldPosition = transformationMatrix * vec4(position, 1.0);
        vec4 positionRelitiveToCam = viewMatrix * worldPosition;
        gl_Position = projectionMatrix * positionRelitiveToCam;
    }

```

# Answer
> 1 votes
Some sanity checks could help you debug this:

1. Disable culling with `glDisable( GL_CULL_FACE );`
2. Disable depth test with `glDisable( GL_DEPTH_TEST );`
3. Use super simple fragment shader that just sets frag colour to `(1.0, 0.0, 0.0, 1.0)` e.g.

If after that, you still only see a black screen, double check your view matrix.

Something that not everybody may know: the view matrix is nothing else than the inverse of your camera transform.

So instead of building up your viewmat as in your code, it is easier to just transform (position/orient) your camera in the world. Then take its matrix, and invert it.

That inverted matrix, is your view matrix.

# Answer
> 0 votes
There are many things that can be wrong, check the follows:

* Use quaternions, because then you can normalize them and be sure that all is correct.
* `gl_position` should look like this: `ViewProjection * cameraRotation * cameraTranslation * Object transformation * vec4(Position,1.0);`

Where object transformation is: Object Translation * Object Rotation * Object Scale

* Stop using `glUseProgram(0)` Opengl is sequential, it wont do anything good for you.
* Make a buffer at the init to initializate the vertex buffer and save it for later use it. It should look something like this:

glGenVertexArrays(1, &m\_VAO); glBindVertexArray(m\_VAO); glBindBuffer(GL\_ARRAY\_BUFFER, m\_Buffers\[POS\_VB\]); glBufferData(GL\_ARRAY\_BUFFER, sizeof(Positions\[0\]) * Positions.size(), &Positions\[0\], GL\_STATIC\_DRAW); glEnableVertexAttribArray(POSITION\_LOCATION); glVertexAttribPointer(POSITION\_LOCATION, 3, GL\_FLOAT, GL\_FALSE, 0, 0);

---
Tags: opengl, c++, shaders, glsl
---


# Question
Title: Can't access object parent type if some parent object along the way was in array
I use this method to get type of the object the field was declared via reflection. (f.e.) this time it's field at index `[5]` \- `activePlaybackAudioArchive`.

If along the way the object/objects in hierarchy was placed in array it produces - `[1] Array` and `[2] data[0]`. Strangely the `[SerializeField] private AudioPlayerData[] _audioPlayerData` is the array, why it shows in hierarchy below this variable is unusual to me.

Is there a good way to deal with this problem, or omit the indices like `[1] and [2]`? Or maybe there is a proper way to get `fieldNames` that wouldn't include `Array` like types into path?

# Answer
```
public static readonly string[] PATH_FIELD_NAMES_EXCEPTIONS_SUBSRTINGS = { "Array", "data[" };

private static bool IsException(string fieldName)
{
    for (int j = 0; j < TypeExtensions.PATH_FIELD_NAMES_EXCEPTIONS_SUBSRTINGS.Length; j++)
        if (fieldName.Substring(0, TypeExtensions.PATH_FIELD_NAMES_EXCEPTIONS_SUBSRTINGS[j].Length) == TypeExtensions.PATH_FIELD_NAMES_EXCEPTIONS_SUBSRTINGS[j])
            return true;

    return false;
}

/// <summary>
/// Search to top of the hierarchy via fieldNames
/// </summary>
/// <param name="type"></param>
/// <param name="fieldNames"></param>
/// <returns>Parent object FieldInfo || null if has no parent</returns>
public static FieldInfo GetParentObjectFieldInfoViaPath(this Type type, string[] fieldNames)
{
    FieldInfo fieldInfo = null;

    for (int i = 0; i < fieldNames.Length - 1; i++)
    {
        //if (TypeExtensions.IsException(fieldNames[i]))
        //  continue;
        if (type.IsArray)
        {
            type = type.GetElementType();

            i += 2;
        }

        fieldInfo = type.GetField(fieldNames[i], BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

        if (fieldInfo.FieldType.IsArray && i + 3 >= fieldNames.Length)
            break;

        type = fieldInfo.FieldType;
    }

    return fieldInfo;
}

```

Here is a quick workaround, cheat :) Check if it's an array, if it is, then skip 2 steps `(Array, data[n])`. Then the magic method - `GetElementType()` and everything is fine.
> 0 votes

---
Tags: unity, c#, code-reflection
---


# Question
Title: In Unity, is there a difference between Vector3.down and -Vector3.up?
I've noticed numerous tutorials and examples using something like "transform.up * -1" or "-Vector3.up" instead of simply saying "transform.down" and "Vector3.down".

Is there a good reason for this, or is it simply a style difference?

I'm specifically thinking about downward raycasts, if that matters at all.

# Answer
> 2 votes
They're equivalent. You can verify via the documentation for `down` and `up` respectively.

The choice is thus down to style (or perhaps ignorance of the existence of `down`) and relatively minor, nitpicky sorts of details (like how one could make that case that, for iteration purposes, it may be easier to add or remove the leading `-` to switch between two options).

# Answer
> 1 votes
`Vector3.up` equals to `new Vector3(0, 1, 0)`

`Vector3.down` equals to `new Vector3(0, -1, 0)`

When you do `-Vector3.up` it sets every value to negative value:

```
public static Vector3 operator -(Vector3 vector)
{
    vector.x = -vector.x;
    vector.y = -vector.y;
    vector.z = -vector.z;

    return vector;
}

```

Or Unity could also implement it as immutable type and it will do:

```
public static Vector3 operator -(Vector3 vector)
{
    return new Vector3(-vector.x, -vector.y, -vector.z);
}

```

Though, you can do `someVector.y = 10f;`, thus they are not immutable.

---
Tags: unity, vector, raycasting
---


# Question
Title: Raycast in Unity for ground detection returns false while touching ground
I'm using a raycast to detect the player's distance to the ground for a hovercraft game.

The raycast works correctly (returns true and also returns the distance to the first impact) until the moment the craft actually touches the ground. When the player hits the ground, the raycast should theoretically return true and return the distance as near 0f. Instead, it returns false, meaning the raycast isn't colliding with anything over the length of the ray. As a result, it can't find the distance.

I'm having a hard time troubleshooting this, and I wonder if anyone can lend a fresh pair of eyes.

```
Ray ray = new Ray (transform.position, Vector3.down);
RaycastHit ray_result;
bool hit_ground = Physics.Raycast (ray, out ray_result, optimal_vertical_distance * 2);
if (ray_result.distance < optimal_vertical_distance && vertical_force < max_vertical_force)
  {
  vertical_force += vertical_acceleration;
  }
if ((!hit_ground || ray_result.distance > optimal_vertical_distance) && vertical_force > min_vertical_force)
    {
    vertical_force -= vertical_acceleration;
    }
  }
body.AddForce (Vector3.up * vertical_force, ForceMode.Acceleration);

```

The only time hit\_ground worked correctly was when I increased the thickness of the floor from 2 units to 4 units and set the ray to start from 2 units above the craft instead of from the craft itself. I don't understand why it works, though. However, in that example, ray\_result.distance seems to be locked at -1.10999, regardless of how far away the craft is.

# Answer
> 1 votes
**My collider was in the wrong position.**

It *appeared* that my collider mesh was perfectly lined up with my model. When I zoomed in very close in 2D mode, I was able to see that the bottom of the player's model was extending about .1 units past the bottom edge of the collider. Thus, when the collider would hit the ground, the bottom of the model would be intersecting the ground, and, consequently, the origin point of the raycast would be in the ground as well (since I was setting the origin near the bottom of the model). Since raycast ignores any mesh inside its origin point, it thought the ground was part of the player.

# Answer
> -1 votes
You should check all **Physics.Raycast** overloads on the Documentation. You are using the default one, which checks a ray at a given distance, modifies a **RaycastHit**, this method returns true if it hits anything, even the origin's object, and since you are casting it from **transform.position** which will:

* Always return true.
* The **RaycastHit** passed as reference will have the ray origin's transform.

What you could do, is to have a **LayerMask** attribute on that class (or anywhere, depending your code architecture) and use the **Physics.Raycast** overload that takes also a **LayerMask**, that parameter is used to selectively ignore layers, and just consider the layer(s) given. Example:

```
public class LameExample : MonoBehaviour
    {
        public LayerMask layers;
        public float rayDistance;
        private bool grounded;

        void Update()
        {
            RaycastHit hit;
            Ray ray = new Ray(transform.position, Vector3.down);

            grounded = Physics.Raycast(ray, out hit, rayDistance, layers);
        }
    }

```

You could also consider cast the ray from the bottom border of your object, plus a padding, to give a more precise raycast length, see Bounds' API for more reference. Example:

```
public class LameExample : MonoBehaviour
{
    public LayerMask layers;
    public float rayDistance;
    public float padding; // Use a tiny number, like 0.1f
    private bool grounded;
    private Renderer renderer;

    void Awake()
    {
        renderer = GetComponent<Renderer>();
    }

    void Update()
    {
        RaycastHit hit;
        Vector3 boundExtent = new Vector3(0f, -renderer.bounds.extents.y + padding, 0f);
        Ray ray = new Ray(transform.position + boundExtent, Vector3.down);

        grounded = Physics.Raycast(ray, out hit, rayDistance, layers);
    }
}

```

Hope it helps.

---
Tags: unity, collision-detection, raycasting
---


title: Player tag does not respond to AddForce

text:
# Question
Title: Player tag does not respond to AddForce
I have a player with rigidbody and it has a tag as *Player* .

I have set a sphere collider as *trigger* with script

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

public class Addforce : MonoBehaviour {

```
public int speed;

void OnCollisionEnter(Collision other)
{
    if (other.gameObject.CompareTag("Player"))
    {
        other.gameObject.GetComponent<Rigidbody>().AddForce(Vector3.up*speed);
    }
}

```

}

I have set speed force to 100.

But when player enters the collider, nothing happens. It doesn't tag it.

# Answer
Since the sphere is a trigger, you need to use `OnTriggerEnter(Collider other)` instead of `OnCollisionEnter`.

`OnCollisionEnter`, `OnCollisionExit` and `OnCollisionStay` are called when both objects' colliders are not triggers.

Moreover, you should specify that the force added is an impulse. You should do this:

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

public class Addforce : MonoBehaviour {

    public int speed;

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Player"))
        {
            other.gameObject.GetComponent<Rigidbody>().AddForce(Vector3.up*speed, ForceMode.Impulse);
        }
    }
}

```
> 1 votes

---
Tags: unity, collision-detection, physics
---


title: Designing a fluent API for card effects

text:
# Question
Title: Designing a fluent API for card effects
I'm currently trying a develop a small game similar to http://www.estiah.com/.

Basically, there are 2 teams of 1 or more actors each, everyone with their same deck. Turn order is fixed and each card is automatically played when drawn, so games play out automatically. I already got the basic game loop, game state and history and turn order and currently try to create a fluent API, that makes it easier to add cards later on.

Each card consists of multiple effects, that can either target the current user, a random ally/enemy, a specific ally/enemy based on some criteria (like, enemy with lowest hp) or all allies/enemies/everyone. On top of this, effects may also have some kind of setup/cleanup, that should only be executed once before/after all targets have been processed.

Below are the use cases i can currently think of:

* apply 1 effect to self
* apply 1 effect to a random ally/enemy
* apply 1 effect to a ally/enemy matching criteria
* apply 1 effect to all allies/enemies
* apply 1 effect to everyone
* apply multiple effects to either of the above (targets should not change between effects, even if, for example, the "enemy with lowest hp" is different after the first effect)
* execute effects based on a condition on the user
* execute effects based on a condition for each target

Conditions/targets should be resolved during effect execution, since previous effects might influence them (unless multiple effects are joined and assigned to the same target, in which case it should not change between effects, as stated above).

Since the theory probably isn't very expressive, i already developed a basic system, which can be found over here: https://codereview.stackexchange.com/questions/189732/designing-a-system-to-apply-multiple-effects-to-one-or-multiple-targets.

The current system allows me to do things like:

```
public class MyCard implements Card {
    public Effect getEffect() {
        dealPhysicalDamage(10).to(randomEnemy());
    }
}

```

Where `dealPhysicalDamage(...)` returns an instance of `TargetedEffect`, `randomEnemy()` returns an instance of `TargetSingle` and the `to(...)` method binds the target to the effect, converting it into a plan `Effect`, which in turn can get executed by the game engine. This modifies the current game state, which gets deep cloned into a history for later usage as a battle log.

I've been trying for days to come up with a better system that gives me the freedom to apply 1-n effects to 1-n targets (single target effects will be the majority), while keeping the API as compact as possible. I'm probably too deep in the code to get a clear view, so maybe someone else can come up with an idea.

# Answer
You probably *are* too deep in the code. This is not a particularly complex system when you consider the ordering, or the processing, from what I can see.

> I've been trying for days to come up with a better system that gives me the freedom to apply 1-n effects to 1-n targets

OK, assuming that's your main concern...

```
public class Game
{
    public ArrayList<Card> cardsInPlay;

    public ArrayList<Card> GetCardsAffectedBy(Effect effect)
    {
        ArrayList<Card> results = new ArrayList<Card>();
        //run some sort of a filter here to know what is affected by what
        //this will be based on your cards'/effects' varying logic
        //and what else is in play, and by whom i.e. which player
        for (Card card : cardsInPlay)
        {
            if (card is pertinent to this effect) //your logic here!
                results.Add(card);
        }
        return results;
    }
}

public class Card
{
    public Game game; //set from Game itself on Card creation

    public void applyEffects
    {
        for (Effect effect : played.effects)
        {
            ArrayList<Card> cardsAffected = game.GetCardsAffectedBy(effect);
            for (Card card : cardsAffected)
            {
                effect.applyTo(card)
            }
            //or apply to players, enemies, allies, whatever.
        }
    }
}
Game.playCard(card); //or whatever, but call card.applyEffects();

```

Pass in whatever extra paramaters to whichever functions you like, e.g. `GetCardsAffectedBy` might need ID of player who just played that effect. We might need to keep data in `Game` itself till the turn resolves, e.g. a list of the effects played so far so we can evaluate order... and so on.

As for...

> (single target effects will be the majority)

...Don't concern yourself with that. Loops accommodate one *or* many, that's all you need to know. Act as though there are always more than one, and the one-card case will be handled by-the-by.

**Reporting**

While it's important to build a game with logging / reporting in mind, I think you need to stop allowing that aspect from limiting your thinking in regards to *making the game work* relatively efficiently. Remember, it's not a game if you can't play it, and it's not an efficient, maintainable codebase if you can't tweak it to make things elegant. Really, logging comes as a secondary concern to these aspects, in my opinion at least. In my case I tend to do data driven design with a hierarchical data model and control hierarchy, and I expose all members as public so that any reporting tools can access these down the line (not a fan of shadowing every member with a get/set pair).

**Adding cards**

Having certain supported gameplay effects, there is plenty you can add by just changing names and numbers in accordance with whatever that component can represent. However, when it comes to new logic, obviously you have to write the code that supports that. How flexible you make things is entirely up to you. You may choose to keep the cards / effects minimally parameterised.

More specifically though, it's difficult to help you with *API design* while we have no idea *how* you envision creating new cards. Will you be using an editor or do this in text files by hand? Will you allow card proposals by players, is there an acceptance/rejection process? Will there be a facility for image, sound effect upload? etc. etc. Once again, it is better to focus on getting the the game playable first, and worry about these petty details a bit later.
> 1 votes

---
Tags: java, architecture
---


# Question
Title: C# (Unity) Use a method common to multiple classes with the same base class
**The Problem:**

I'm building one of those empire/kingdom building games and so I am trying to create an efficient way of making a "ResourceManager" class handle the games resources (wood, food, iron, stone). I currently repeat a function 4 times to do the same thing.

**Attempt 1:**

I created a "Resource" class (abstract) and derived the four resources from it. In each resource there are multiple methods which are similar:

*Example Food.CS:*

```
    new public static void AddResources(int amount) {

    Player.currentFoodSupply += amount;
    foodText.text = Player.currentFoodSupply.ToString();
}

```

*Compare to Iron.CS:*

```
new public static void AddResources(int amount)
{
    Player.currentIronSupply += amount;
    ironText.text = Player.currentIronSupply.ToString();
}

```

The AddResource() function is static because I have other scripts (like buildings, when they get upgraded) needing to communicate with each resource. The base building class currently has a method like this:

```
public void DeductResources()
{
    Food.DeductResources(FoodCost);
    Wood.DeductResources(WoodCost);
    Iron.DeductResources(IronCost);
    Stone.DeductResources(StoneCost);
}

```

This seems like it's so repetitive that there needs to be a more efficient way to do this.

**Attempt 2:**

A "ResourceManager" class that anything to do with the 4 resources can go through this one script. I can update that one script instead of numerous scripts that does something with the resources.

Where I am undecided is this one:

```
public static void DeductResources(Resource resource, int amount)
{
    if(resource.GetType() == typeof(Food))
    {
        Player.currentFoodSupply -= amount;
        resource.resourceText.text = Player.currentFoodSupply.ToString();
    }
    else if (resource.GetType() == typeof(Wood))
    {
        Player.currentWoodSupply -= amount;
        resource.resourceText.text = Player.currentWoodSupply.ToString();
    }
    else if (resource.GetType() == typeof(Iron))
    {
        Player.currentIronSupply -= amount;
        resource.resourceText.text = Player.currentIronSupply.ToString();
    }
    else if (resource.GetType() == typeof(Stone))
    {
        Player.currentStoneSupply -= amount;
        resource.resourceText.text = Player.currentStoneSupply.ToString();
    }
}

```

It looks like it works and I can't see a way around calling the above method 4 times as I need to know how much food or wood to add or deduct.

Does anyone have any suggestions please on how to improve this code/call the method once?

I'm always willing to learn! Thank you

# Answer
> 4 votes
Here's a slightly different version of my previous answer about this kind of system.

The big idea is to move away from using differently-named variables for each resource, because then we need to write different code to access each one. Instead, we can treat them uniformly as members of a collection, indexed/keyed by a resource type.

First we define our types (we could do this in data too via a Type Object, if you want to be able to add new resources dynamically without re-compiling, eg. for mods & expansions)

```
public enum ResourceType : int {
    Food,
    Wood,
    Iron,
    Stone,

    // Ensure this entry is last and it will automatically keep track
    // if how many resources we have. (If we don't explicitly assign
    // values anywhere to confuse the auto-numbering)
    TOTAL_COUNT
}

```

Then we define a resource holder that can process transactions on each of these resource types as needed:

```
public class ResourcePool {
    uint[] _resources = new uint[(int)ResourceType.TOTAL_COUNT];

    public int GetQuantity(ResourceType type) {
        return _resources[(int)type];
    }

    public void Add(ResourceType type, uint quantity) {
        _resources[(int)type] += quantity;
    }

    public bool TryDeduct(ResourceType type, uint quantity) {
        if(GetQuantity(type) < quantity)
            return false;

        _resources[(int)type] -= quantity;
        return true;
    }
}

```

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


title: Unity Redraw canvas graphic on Update()

text:
# Question
Title: Unity Redraw canvas graphic on Update()
```
using UnityEngine;
using UnityEngine.UI;

public class DrawLoad : Graphic
{
    protected override void OnPopulateMesh(VertexHelper vh)
    {
        //==========================
        float r = rectTransform.rect.height / 2.0f;
        //float widthFactor = (rectTransform.rect.width / 2.0f) - r;
        float y = r;
        float x = 0.0f;
        int t = 20;                     // t = total vertices
        float a = 360.0f / (t-1);       // angle delta/differences between each vertex
        float aC = 0.0f;                // incrementing angles  from 0 --> 360
        int maxi = t - 1;
        Vector2[] vtR = new Vector2[t];
        UIVertex[] uivR = new UIVertex[t];

        vh.Clear();

        for (int i = 0; i <= maxi; i++)
        {
            y = r * Mathf.Cos(Mathf.Deg2Rad * aC);
            x = r * Mathf.Sin(Mathf.Deg2Rad * aC);
            vtR[i] = new Vector2(x, y);
            aC += a;

            uivR[i] = UIVertex.simpleVert;
            uivR[i].position = vtR[i];//0,0
            uivR[i].color = Color.green;
            vh.AddVert(uivR[i]);
        }

        // ======== add center point ========
        Vector2 center = new Vector2(0.0f, 0.0f);
        UIVertex c = UIVertex.simpleVert;
        c.position = center;//0,0
        c.color = Color.green;
        vh.AddVert(c);

        for (int i = 0; i <= maxi; i++)
        {
            vh.AddTriangle(t, i, i + 1);// use indexes, don't use count, start from 0
        }

        for (int i = 0; i < uivR.Length; i++)
        {
            uivR[i].color = Color.green;
            vh.SetUIVertex(uivR[i],i);
        }

    }
}

```

Hi, I wish to change the color dynamically of each assigned triangles. I have these code modified from Unity documentation and I tried the SetUIVertex method but it doesn't seems to work. What is the proper way to redraw the vertices. I want to make it in MonoBehavior.Update(). Any helps would be greatly appreciated. Thanks.

# Answer
> 0 votes
Found the solution:
**The shorst answer** is using `SetAllDirty()` will do.
**A better alternative:**
is using others' source code/utility to draw shape and update circle (unfortunately).
\> Go to bitbucket.org/UnityUIExtensions and download the .unitypackage
\> Go to your Unity project and Import the package
\> Don't need to import everything but import only
1. unity-ui-extensions \> Scripts \> Primitives \> UICircle.cs
2. unity-ui-extensions \> Scripts \> Primitives \> UIPrimitiveBase.cs
3. unity-ui-extensions \> Scripts \> Utility \> SetPropertyUtility.cs
\> Create an UI image under canvas
\> Remove the Image Component
\> Assign "UICircle.cs" into Image object
\> In you game `Update()` script, assign values like `GameObject.Find("Image").GetComponent<UICircle>().FIllPercent -= 1`
\> will dynamically change the circle draw percentage.

---
Tags: unity, graphics, gui
---


# Question
Title: Should I be concerned that my microtransaction based game will often be hacked?
I used to play Diablo II, both online and offline. The game was so easily “hackable” offline that one could download a program called Hero Editor and, using a nice, comfortable interface, change their character in many ways. However, it was harder to hack the online portion of the game, and many that did were caught. Thus some of the game’s content was restricted to online play, doubling up as a way to promote people playing together.

Now I’m making a mobile TD using Unity, targeting the iOS, Android, and perhaps PC/Mac/Linux platforms initially. Players would slowly earn some rare currency during play that can be used for permanently unlocking exciting (but non-essential) extras, or they can just pay for them.

I’m concerned that if I allow this gradual unlocking to happen offline (without a server to confirm the accrual of said currency), then it’ll be as easily hacked as Diablo II’s offline mode and that many people would simply resort to doing that instead of either playing it through or paying for it. However, I’m also reluctant to force online play, as the mobile environment has significantly lower network stability and this is a relatively long game to be playing in such conditions, so drop-out is very likely.

So my question is: how concerned should I be about the mobile game getting hacked for the purpose of acquiring these unlocks without going through the correct methods? Is it so easy that your average user could do it, like they could for Diablo II, having the potential to significantly damage the game’s bottom-line? Or is it difficult such that only a small percentage of people who are interested enough would bother to try, so I can focus on providing the best UX for all players without worrying about these hackers?

Brownies for anybody who can summarise how it may actually be hacked!

# Answer
> 1 votes
It all depends how you implement the server-side code. If, for example, when the user logs in, they send the number of currency they collected while offline, and the server accepts that currency without any check, there's a huge potential for people to abuse that (assuming they have some programming skills, and they care enough).

One thing you can do, is something like "if you want to collect this item, log in online" which kinda forces players to be connected, which is not nice (and as you said you'd rather avoid that).

One other way would be, when the player sends the data, the server checks if the data make sense. Can a player collect a million of your currency in a day? If not, that player probably did something malicious (or found a bug), in which case the server can reject the currency.

I like the logic of "if you play offline, you are free to do whatever you want with a game, including hacking it, but if you want to play online, this changes". Following this, the best course of action would perhaps be "connect online to collect this" and the server can then check if things are valid.

On the bright side, most games do not become as big hits as Diablo II, which means not a lot of people will care about hacking you. Considering that huge companies are getting hacked, you can never be 100% safe, so as long as you have at least some minor protection, you should be alright.

---
Tags: unity, mobile, security, pc, microtransactions
---


title: help making a grid based game in java

text:
# Question
Title: help making a grid based game in java
i'm trying to achieve a grid that you can move an character a set number of spaces on per turn, similarly to fire emblem or advance wars. instead of going for a tileset approach however, i want to have an invisible grid that contains all of the properties of each tile (such as movement penalty, combat bonuses while standing on the tile, etc) then just put a gui behind containing an image that lines up with all of the tiles. i'm not exactly sure how to approach this however so any help would be appreciated

# Answer
> 3 votes
Um... an invisible grid is one you represent in memory, but don't display. Nothing stops you from representing whatever you like in memory and never displaying it! It's pretty easy to do nothing!

In memory you set up a 2D array of tiles, e.g.

```
Tile[][] tiles= Tile[ROW_COUNT][COL_COUNT];

```

I would suggest setting up some drawing logic to show the boundaries of the tiles while you are developing, that you can turn off with e.g. F1 key, so you can see how it will look in the final game.

Just render an image before/beneath everything else, each frame, and you should be good to go?

---
Tags: java, 2d, gui
---


# Question
Title: Can I use Paragon assets store assets in other Engines besides Unreal?
Epic Games recently released a lot of assets from their game Paragon for free. I like some of them but am not particularly fond of the Unreal Engine.

Can I use those assets in another engine like Unity or something custom?

# Answer
> 4 votes
I should have read the description on the assets

> Licensed for use only with UE4 based products. Includes the character model, animations and skins

Other assets that Unreal didn't make themselves are fine to use in other engines as far I have found. If you want to be sure read the description and the license that comes with the asset.

---
Tags: assets, unreal, copyright
---


title: Game is darker on build

text:
# Question
Title: Game is darker on build
I've been recently doing test builds of my game. In Unity, I worked on baking the lighting to ensure everything looked fine. However, upon building, the game level becomes far darker and much of the lighting and baking is ineffective.

Here is how the scene looks in the editor:

And here is how it looks in the built game:

It's much darker than intended.

Here are my lighting settings which I've baked in Unity's Editor. These settings and lightmap parameters were designed to, at least in the editor, provide decent quality while making light bake times relatively quick. However, I've noticed that newer Unity's Lighting settings are way different now, so perhaps something is amiss here?

I've been at my wits end trying to figure this out for the past while, but I can't figure out why this is happening or how to fix it. Any ideas?

# Answer
Unity will only take lighting from the active scene. So it's worth checking that:

1. The scene is the "Active Scene" (bold highlight in hierarchy) when building lighting in the Edit Mode
2. The scene is either the only loaded scene in Play Mode or you call SceneManager.SetActiveScene( scene ) for whichever scene you wish to take the lighting data from.

see: https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.SetActiveScene.html
> 3 votes

---
Tags: unity, lighting, build-process
---


title: HLSL Buffer<> Data Type

text:
# Question
Title: HLSL Buffer<> Data Type
I'm working on converting a dx11 shader from a .fx file for use in Unity3D and I'm a little puzzled by the HLSL Buffer\<\> type declared in the shader. More specifically, what are these and how can I implement them in Unity? I'm aware of the Structured, Append, and Consume Buffers but those appear to be different then this and the Microsoft documentation wasn't to helpful. Is it just like an array that is populated and sized from code before getting assigned to the shader? Are they read only or writable as well? So far I'm thinking the closest approximation I can use is a StructuredBuffer but the .fx file has its own declaration for that as well so I'm not entirely sure I should go that route.

Example:

```
Buffer<float4> g_someData : register(t18);

```

# Answer
> -1 votes
I've had similar buffer interop issues with HLSL Compute under Unity. HLSL itself is poorly documented; it doesn't get any better when it comes to interop with Unity specifically.

I *have* had consistent success with `RWStructuredBuffer`, though there you must set the C# struct size and offsets explicitly, and pad the entire struct according to 16-byte boundaries used by HLSL. The HLSL struct needs to be *exactly* the same order and types / sizes, including pad members.

---
Tags: directx11, hlsl, unity, directx10
---