# Question
Title: Shortest path from BitmapSource to DX11 Texture2D
Does anyone know a way to get from (WPF) System.Windows.Media.Imaging.BitmapSource to a DX11 Texture2D without going to System.Drawing.Bitmap? I'm trying to strip out all System.Drawing references as this code it for WPF only.

# Answer
```
public Texture2D Bitmap2Texture(Device device, BitmapSource source) {
  var bitmap = new WriteableBitmap(source);
  bitmap.Lock();
  var texture = new Texture2D(device, new Texture2DDescription() {
    Width = source.PixelWidth,
    Height = source.PixelHeight,
    ArraySize = 1,
    MipLevels = 1,
    BindFlags = BindFlags.ShaderResource,
    Usage = ResourceUsage.Default,
    CpuAccessFlags = CpuAccessFlags.None,
    Format = Format.R8G8B8A8_UNorm,
    OptionFlags = ResourceOptionFlags.None,
    SampleDescription = new SampleDescription(1, 0),
  }, new DataRectangle(bitmap.BackBuffer, bitmap.BackBufferStride));
  bitmap.Unlock();
  return texture;
}

```

You might need to change the texture description flags depending on what you need the texture for.
> 0 votes

# Answer
I use this code to load a bitmap source in, I dont use the system windows media library at all but the directx (it may leverage the very same library underneath).

This works in UWP which is what I assume you are looking for.

Hope this helps.

```
   public static D3D11.Texture2D1 CreateTex2DFromBitmap(SharpDX.WIC.BitmapSource bsource, D3D11.Device3 a_device, D3D11.DeviceContext2 a_context, D3D11.Texture2DDescription1 a_desc, int a_mipLevels)
    {
        D3D11.Texture2D1 t2d = null;

        try
        {
            int stride = bsource.Size.Width * 4;
            var buffer = new DataStream(bsource.Size.Height * stride, true, true);

            if (a_mipLevels != 0)
            {
                // if we arent doing mip maps, then load the resource directly
                DataRectangle rect = new DataRectangle(buffer.DataPointer, stride);
                bsource.CopyPixels(stride, buffer);
                t2d = new D3D11.Texture2D1(a_device, a_desc, rect); /// this creates a texture and populates it, we need to create a blank one then populate it.
            }
            else
            {
                t2d = new D3D11.Texture2D1(a_device, a_desc); /// this creates a texture and populates it, we need to create a blank one then populate it.
                bsource.CopyPixels(stride, buffer);
                DataBox box = new DataBox(buffer.DataPointer, stride, 1);

                a_context.UpdateSubresource(box, t2d, D3D11.Resource.CalculateSubResourceIndex(0, 0, CountMips(bsource.Size.Width, bsource.Size.Height)));
            }
            buffer.Dispose();

        }
        catch (Exception ex)
        {
            ErrorHandler.DoErrorHandling(ex, ErrorHandler.GetCurrentMethod(ex), Environment.StackTrace);

        }
        return t2d;
    }

```
> 0 votes

---
Tags: c#, directx, sharpdx
---


# Question
Title: Algorithm to solve a battle in a card game
I am trying to write a solver for a sort of card game. I mainly do that for fun, and also to be able to learn a bit about the different types of algorithms I could use for this problem.

The rules of the card game is pretty simple:

* A card has a given amount of HP and Attack and potentially a skill that increases its stats
* Each card has an element. Each element has a weakness. E.g, if a fire card is attacked by a water card, the fire card will lose 2 times more HP
* All players have the same cards available to them (new random deck every day)
* Two players confront each other
* Each player can have up to 6 cards in his lineup
* Each turn, the front card of each lineup will attack each other, reducing the HP of the opponent by its Attack
* At the end of a turn, if one of the card has 0 HP, the next card enters the battle
* This goes on until one lineup is empty
* The players cannot interact with their cards during the battle: you set-up your lineup and then you watch the match

The game has 3 modes:

1. PvE: you know the enemy lineup and have to find a solution for the battle
2. PvP: you have a setup of 6 lineups. An enemy can attack you. The engine selects one random lineup for each player and the result of this battle determines the winner of the attack
3. Tournaments: You have a setup of 3/5/7 lineups. All players battle against each other. Each lineup will confront its opposite lineup (i.e. lineup 0 of the player A will battle against lineup 0 of player B, lineup 1 against lineup 1, etc.). The winner is selected based on the amount of wins.

I have made a battle simulator that gives you the amount of damage made by the winner (positive amount if left side wins, negative otherwise).

Currently, I use a genetic algorithm to solve the three cases.

1. PvE: my genome is my lineup, each chromosome being a card. My fitness is basically the result of the battle simulation, where I try to find the first solution that works.
2. PvP: my genome is my setup, each chromosome being a lineup. My fitness function makes every genome of my population battle against each other, and tries to maximize the lineup win ratio
3. Tournaments: Same as above, but instead of selecting the lineup win ratio, I select the setup win ratio. Basically, I don't want to win for every lineups, I just want to have more wins that my opponent

The issue I have with this is that it can be random at times. Also, for the PvP and tournaments mode, the crossover/mutation is hard because it is sometimes conflicting (e.g. if, after a cross over, you end up with 3 cards of type A, while you have only 2 in your deck).

Following this, I have some questions:

* Do you think that the genetic algorithm approach is good?
* What kind of problem is this? (Knapsack, Multi-Objective Optimization, or some other combinatoric problem). I have a hard time defining this.
* What kind of algorithm could give me good results, fast?

I'll take any suggestions for this :)

Thanks a lot!

---

Update:

A little bit more of context about how the game is played:

Your deck has 80 cards, and changes every day. In this deck, you can have multiple times the same card (there is no limit for this, so you can end up with 20 times the same card).

What I want to solve is mostly the tournament/PvP part.
PvE is easy because you know the lineup of the opponent.
But for the tournament/PvP mode, you just know that the opponents will have the same deck as you, you don't know the setup he will choose.
In these modes, all players have to set-up 3/5/7 lineups based on the deck of the day and, after a time, all players will fight all other players. At that point, you cannot interact with your lineups anymore, there are no user action during the fights, you can just see the replays.

A general strategy for this is usually to have half (rounded up) of your lineup as strong as possible, in order to win 3 of the 5 lineups so that it can be counted as a win against the player.

Pseudo-code for the tournaments would be something like:

```
numberOfLineups := rand(3|5|7)
tournamentWins := 0
for each otherPlayer in tournamentPlayers:
  matchWins := 0
  for each i in range(1 to 3):
    yourLineup := yourself.Lineups[i]
    otherLineup := otherPlayer.Lineups[i]
    winner := fight(yourLeftup, otherLineup)
    if winner == yourself:
      matchWins += 1
    else
      matchWins -= 1
  if matchWins > 0:
    tournamentWins += 1

```

The goal is to maximize `tournamentWins`.
In this context, I don't think there can be a globally optimal solution.

What's a good algorithm to find a solution that is somewhat good in this scenario?

I could potentially store the tournaments results if necessary, if I want to train a model that will predict the strategies used by other players.
But even in this case, what model could I use to do that?

---

Update 2:

As I said in the beginning, cards can have skills. Those skills can affect only the card itself, or other card as well. Some example of skills: \- give x2 damage to the card itself \- give +5 armor to all cards in front of the card in the lineup \- attacking damage the opponent first card for 100%, and the opponent second card for 50%

It means that we cannot always say that `Card A wins against Card B`: it depends on what combination of cards are present in the lineup, which is why I believe it would be something like (80 * 79 * ... * 75) possibilities, instead of (80 + 79 + ... 75). But maybe I'm wrong?

Following is an example of what I mean by 'combination can change the result of the battle'.

Let's take the following card:

* Card `A`: 10 Atk, 10 HP, no skill
* Card `B`: 6 Atk, 10 HP, no skill
* Card `C`: 3 Atk, 10 HP, skill: +6 armor to all cards

Fight:

```
Turn | Left    (HP) | (HP)    Right
   0 |        A(10) | (10)B
   1 |        A( 4) | ( 0)B
-----------------------------------
          Winner

Turn | Left    (HP) | (HP)    Right
   0 |        A(10) | (10)C
   1 |        A( 7) | ( 6)C
   2 |        A( 4) | ( 2)C
   3 |        A( 1) | ( 0)C
-----------------------------------
          Winner

Turn | Left    (HP) | (HP)    Right
   0 |      A-A(10) | (10)B-C
   1 |      A-A( 4) | ( 6)B-C
   2 |      A-A( 0) | ( 2)B-C
   3 |        A(10) | ( 2)B-C
   4 |        A( 4) | ( 0)B-C
   5 |        A( 4) | (10)C
   6 |        A( 1) | ( 6)C
   7 |        A( 0) | ( 2)C
-----------------------------------
                         Winner

```

As you can see, even if `A` wins against both `B` and `C` in a one-on-one match, a `A-A` lineup cannot win against a `B-C` lineup because of the bonus that `C` gives to `B`.

# Answer
Update 2: Your second update was very helpful/informative.

You have shown that this is a very large search space (roughly 2^38.) This is probably too big, but let's look at possible solutions from **the Search perspective** anyway:

* One could be breaking the problem up to approximate a good answer. Imagine finding the optimal pair for the deck; this is 80 * 79 for the first pair (which is only 2^13 or so), and similar for the other pairs.
* + Then one could imagine looking at optimal pairs of things, and performing a search on combinations of optimal pairs (the top 6 pairs or something) in order to find powerful combinations

If you were to go that route, you may be able to start your Learning AI search near very powerful (but likely not perfect) solutions. Intuitively, there should be some way to add heuristics for "This guy buffs the whole team, so pick him more often", but that'd be up to you to choose what makes sense.

**From the learning perspective**, I think Neural Nets make more sense for your problem than genetic algorithms. With such a giant search space, genetic algorithms will have to be lucky to start "nearby" a "global peak" and will only move slowly to "local peaks", where you may get "stuck" with a locally optimal but globally suboptimal solution.

Neural nets should be able to find trends of "what are powerful combinations" and it's fairly low effort to train 3 or 6 of them (starting with random weights) and just run it until it's win percentage is high. I would definitely run competing neural nets in a round robin tournament so that they don't just find solutions to the other neural net.

Hope this answer finds you well! Note: (if unfamiliar) look up Model Distillation and Model Calibration for combining neural nets.

---

Update:

If you were doing it such that it was like Pokemon (you use a guy until he dies) I could see it being an intractable search space without extreme pruning (80 * 79 * ... * 75); ~~however, you are actually only looking for the best guy in each slot.~~

~~I'd consider simply using a search space as singleton matches in a search algorithm. This means you only have 465 (80 + 79 + ... 75) checks to make because you don't care what your previous choices were since they don't influence your current choice (other than what you can't choose.) If you actually make a list of the rankings, it's down to only 80 checks, because the top 6 would be your choices.~~

~~Simply calculating the average best character based on it's ranking against the full list of opponents you'll get something close to optimal (***on average***.) Then you can randomize this list slightly by reordering the choices it makes so it's difficult to meta-game against it.<br>~~

~~If meta-gaming becomes an issue, now you can build more intelligent variations based on an even smaller search space, possibly starting your genetic algorithm with those who have high-average win rates.~~

Note: you should eventually use this AI with a group of interested players who *will* meta game and simply track statistics of average use of characters. Once you have an idea of this you can start deploying Ais that meta the meta and so forth.

---

*Disclaimer: I am an AI Professional who works with neural nets but have a standard CS degree (so take it with a grain of salt.)*

This is an optimization problem: Maximum Damage Dealt while Minimum Damage Taken

This is a deterministic problem, meaning you can math out the the entire solution space of a given problem simply by searching and ranking the results. ~~This would mean it's *definitely* in the realm of "Search based AIs" and not "Learning AIs" IMO.~~  EDIT: This is not quite true with a 2^38 search space and a low amount of time for "thinking." It may still be possible (for future readers) but I recommended a NN.

Similar to the above, deterministic solutions are easy to adjust for difficulty (make the search space smaller, choose suboptimal moves at times on purpose, introduce randomness); but will also give you *the best possible solution immediately, every time.*

---

Note: My university made a distinction that I realize a lot of people don't have, which is Search-based vs. Learning-based AIs; so I will explain.

Search Based AIs require no training to be effective and are done by searching all (or many) possible boardstates and weighing the results via heuristics (which could be trained if you desired.) They tend to require Perfect Information and will only choose a different move if you explicitly have randomization in part of your move-determination (usually picking between a set of equal moves within the search space.) A popular example of this is Chess. They also tend to be a deterministic approach to the problem.

Learning Based AIs require training and tend to be better at games that have random or a very high number of board states. A popular example of this is Backgammon. They also tend to be a statistical approach to the problem.

This is not to say the approaches can never be combined; just that this is the language/distinction used in my answer above that I have found is not universal among my peers.
> 1 votes

---
Tags: algorithm, ai, puzzle, card-game
---


# Question
Title: Why is my texture drawn in a different place when in fullscreen?
I'm trying to draw a texture (with a crescent moon) in the middle of the y-axis:

```
public void draw(SpriteBatch batch) {
    batch.draw(lune, 0, Gdx.graphics.getHeight() / 2);
}

```

It renders this when windowed:

And in full screen mode:

I don't understand why it doesn't work since I'm always drawing at the top of the middle in the y-axis.

---

I add a little update to what i do exactly :

```
        @Override
    public void resize(int width, int height) {
            this.levelDatas.screenWidth = width;
            this.levelDatas.screenHeight = height;
            this.levelDatas.lune.updateSize(width, height);
    }

```

My render method :

```
        @Override
    public void render(float delta) {
            Gdx.gl.glClearColor(0, 0, 0, 1);
            Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
            this.levelDatas.batch.begin();
            this.background.draw(this.levelDatas.batch);
            this.levelDatas.lune.draw(this.levelDatas.batch);
            this.levelDatas.batch.end();
            [...]

```

And this is the updateSize and draw method for the "Lune" object :

```
public void updateSize(int width, int height) {
    this.widthScreen = width;
    this.heightScreen = height;
}

public void draw(SpriteBatch batch) {
    batch.draw(new TextureRegion(lune), 0, this.heightScreen / 2, 0, 0, this.lune.getWidth(), this.lune.getHeight(), 1f, 1f, 0);
}

```

Still got the problem !

# Answer
> 0 votes
I finaly found the answer and it was pretty stupid. I don't understand how this work but let's admit that. Game is loaded in 1200x720. I keep this values inside of the Lune classes. And everytime i draw the Lune, i draw it at 720/2 and the scale does the work to place it at the correct place. Less talk, more code, here is my solution to my own problem :
This is the constructor :

```
this.widthScreen = Gdx.graphics.getWidth();
this.heightScreen = Gdx.graphics.getHeight();

```

And this is the render method :

```
batch.draw(new TextureRegion(lune), 0, (this.heightScreen / 2) - (this.lune.getHeight() / 2), 0, 0, this.lune.getWidth(), this.lune.getHeight(), 1f, 1f, 0);

```

I don't understand why, but the moon is placed correctly, see : Original size :

Full screen :

Lowered :

If anyone have any explanation, i'm here to listen !

# Answer
> 1 votes
I think your problem is , that

```
Gdx.graphics.getHeight()

```

doesn't get updated properly. (I tested this behavior and found out, that it's getting updated properly . I am sorry for this wrong information of mine.)

My solution:

create 2 variables

```
private int w,h;

```

Get the height and width of the window:

```
public void create() {
        w = Gdx.graphics.getWidth();
        h = Gdx.graphics.getHeight();
}

```

And then update the to every time, the resolution gets changed:

```
public void resize(int width, int height) {
    w = width;
    h = height;
}

```

Hope this helps.

# Answer
> 0 votes
Looking at the source code for SpriteBatch, it looks like vertices are generated like this:

```
final float fx2 = x + width;
final float fy2 = y + height;

```

This means even if you render at the "center" of the screen along the y-axis, it most likely will not do that. Had the SpriteBatch had something like:

```
final float fy2 = (y - height/2) + height;

```

I suspect it would be correct?

Imagine a screen height of 100, and a texture height of 50. The middle of the screen would be 50. So if you rendered the texture at 50, what would happen in the SpriteBatch is that y = 50, and fy2 = 100. That's not the middle of the screen. However, if you put y as 50 - (50/2) = 25, fy2 would be 75, and it should render in the middle.

So, (big disclaimer!!) unless libgdx does some translation somewhere else that I dont know about (and that's quite possible, since I don't know libgdx at all),

try:

```
public void draw(SpriteBatch batch) {
    batch.draw(lune, 0, Gdx.graphics.getHeight() / 2 - (lune.getHeight()/2));
}

```

# Answer
> 0 votes
Try calling this in your resize method and see if it works. It worked for me, but sincerely speaking, I don't know why.

```
batch.getProjectionMatrix().setToOrtho2D(0, 0, width, height);

```

---
Tags: libgdx, textures, rendering
---


title: Cutting a 3D mesh with a 2D shape

text:
# Question
Title: Cutting a 3D mesh with a 2D shape
I have a 2D image that i want to use to cut into a 3D mesh while leaving it closed (basically cut straight through it, and close it by generating vertices in both places it cut, front and back, to close the hole). The shape i'm cutting through is a manifold and i'm wondering if there's an easy & fast way to do it considering the shape is very high resolution (3K texture).

* The 2D Shape in the image is closed but complex (probably thouthand of points vectorized)
* The target mesh is a closed mesh, the odd case of intersecting with an edge of the mesh can be ignored in my case so the shape will either not intersect at all or intersect with 2 points (front and back of the mesh).

I guess i could simply vectorize the shape and then create a mesh from that and do a mesh-mesh intersection but i'm wondering if there's an easier / faster way to do it directly from the source texture.

# Answer
Does it need to truly "Cut out" the mesh", or just look cut out? You don't mention the scenario so I'm going to assume that simply "looking cut out" would be adequate, and I'll assume this is something that happens during Runtime and not something that is compiled in.

So, **going with the assumption that it only needs to look this way, not affect the mesh itself**:

I would use a special Alpha texture that is applied to the model in the shape that you desire, then apply it to the model in the same way you would apply a Blood Splotch. Treat this alpha the way you'd like (which may simply be to act "Clear".)

I do anticipate some odd work around looking at it from an angle, but I don't know what you're trying to accomplish yet. Hopefully this gives you a different approach to the problem and gets you into a helpful head-space.
> 1 votes

---
Tags: 3d, 3d-meshes, intersection
---


# Question
Title: Most effective way to perform dynamic list of actions?
I have a huge list of predefined game objects with different actions they do. What is the best (in terms of code simplicity and runtime performance) way to store, dynamically refresh and execute their actions after placement them in game in runtime?

Let's say GO1 every game turn creates copy of itself nearby. GO2 destroys all GO3's. GO3 adds resources. GO4 removes resources on its creation, etc. Each turn player instantiates one object from the list in the game world and after that they start to execute their actions. Player can build multiple objects of the same type, and there are hundreds of different gameobjects with hundreds of different types of actions. Objects can't change their actions in the runtime, for the sake of simplicity of this question. Each action can be very heavy on processor - for example, look through each other object. Having those be all executed at the same time is a problem itself.

Some ways I can think of (but having very little experience with the subject, I have no idea of their actual effectiveness):

> 1. Assign every object a method on its own. Object initialisation list becomes very complicated and you can't really store it in xml-like file.
> 2. Initialise objects with some kind of lambda or Action\<\> literal parameter. I can't imagine this is okay in terms of game resources, and probably is a hell for debugging.
> 3. Initialise objects with a string of parameters. Simple to initialise, but parsing requires extra processor time.
> 4. Initialise object with a struct-like list of actions. Simple to initialise, but number of childs in said mega-struct will become extremely big.
> 5. Hardcode a mega-function with a lot of calls like "if (objectID == GO2) then do" or cases. Sounds stupid, probably is.
> 6. Unity-way: assign each instantiated object an own script, pass script name on initialisation, similar to p. 2. Most simple way, but can't be easy for a machine to execute. Also, changing object parameters will be complicated.

It should not matter, but I'm using Unity3D with C#.

# Answer
> 0 votes
The Unity way to do this would be to implement each of these object behaviors as an own `MonoBehaviour`. Create a prefab for each object type and assign the appropriate MonoBehaviour to it. When a player spawns one of these object, instantiate the respective prefab.

# Answer
> 0 votes
I tend to tackle things like this using *Option 7:* **Polymorphism**

* All Objects inherit from the same basetype
* Store a data structure of the basetype (which allows the polymorphed versions to be in the same data structure for iteration)
* And overwritten function in the derived classes allows them to act different without managing what you're talking to

In case you're wondering, I do define these types as their own dedicated classes in my code at the moment (but may find a better way later as I get a lot of types.) In general (because most of my information is static at the moment and requires no additional functions) my derived classes are only a few lines of adjusted stats, a changed Update function, a reference to the model or texture it uses.

Anyway, I do this method for handling my guns/bullets/projectiles. I also use it as a way for all my things to use similar drawing code (and thus not have to implement it more than once) and they use a custom model-batcher. This is all to say that an implementation like this can work if you're patient with it.

In my case I have something like:

```
public abstract class BulletType
{
    public double Duration { get; set; }
    public uint Damage { get; set; }
    public double Speed { get; set; }
    public DrawData3D.TextureType Texture { get; protected set; }
}

public class Bullet3D : BaseObject3D
{
    public BulletType Type { get; set; }
    private int LifetimeTicksRemaining { get; set; }

    public void Set(...){
      //...
    }

    private void CalculateMovementVector()
    {
      //...
    }

    public override void Update()
    {
       //..
    }

    private void Reset()
    {
        //..
    }
}

public class TankRound : BulletType
{
    public TankRound() : base()
    {
        Speed = 4.0;
        Duration = 1.5;
        Texture = DrawData3D.TextureType.BIGBULLET;
    }
}

```

Which means all my bullets get to be managed and updated by a single manager and utilize the same code. My manager actually never deletes or creates bullets either *AND* the stats are stored inside that singleton struct, so those stats are memory efficient because they only exist in one place.

I hope this is enough to validate the idea that using polymorphism can do this for you.

---
Tags: unity, c#, optimization, resource-management
---


title: Surface Depth Intersection Shader

text:
# Question
Title: Surface Depth Intersection Shader
I recently asked a question about the creating an accurate Depth Intersection Shader.

When creating this in a fragment / vertex shader it could be achieved by the following code

```
SubShader
{
    Blend SrcAlpha OneMinusSrcAlpha
    ZWrite On

    Tags
    {
        "RenderType" = "Transparent"
        "Queue" = "Transparent"
    }

    Pass
    {
        CGPROGRAM
        #pragma target 3.0
        #pragma vertex vert
        #pragma fragment frag

        #include "UnityCG.cginc"

        struct appdata
        {
            float4 vertex : POSITION;
            float2 uv : TEXCOORD0;
            float3 normal : NORMAL;
        };

        struct v2f
        {
            float2 uv : TEXCOORD0;
        };

        sampler2D _MainTex;
        float4 _MainTex_ST;
        sampler2D _CameraDepthTexture;
        fixed4 _Color;
        fixed4 _GlowColor;
        float _FadeLength;

        v2f vert(appdata v, out float4 vertex : SV_POSITION)
        {
            v2f o;
            vertex = UnityObjectToClipPos(v.vertex);
            o.uv = TRANSFORM_TEX(v.uv, _MainTex);

            return o;
        }

        fixed4 frag (v2f i, UNITY_VPOS_TYPE vpos : VPOS) : SV_Target
        {
            float2 screenuv = vpos.xy / _ScreenParams.xy;
            float screenDepth = Linear01Depth(tex2D(_CameraDepthTexture, screenuv));
            float diff = screenDepth - Linear01Depth(vpos.z);
            float intersect = 0;

            if(diff > 0)
                intersect = 1 - smoothstep(0, _ProjectionParams.w * _FadeLength, diff);

            return fixed4(lerp(tex2D(_MainTex, i.uv) * _Color, _GlowColor, pow(intersect, 4)));
        }
        ENDCG
    }
}

```

However, when I try to put the same logic into a surface shader, the result does not show any depth intersections.

```
SubShader {
    Blend SrcAlpha OneMinusSrcAlpha
    ZWrite On

    Tags
    {
        "RenderType" = "Transparent"
        "Queue" = "Transparent"
    }

    CGPROGRAM
    // Physically based Standard lighting model, and enable shadows on all light types
    #pragma surface surf Standard fullforwardshadows alpha:fade

    // Use shader model 3.0 target, to get nicer looking lighting
    #pragma target 3.0

    sampler2D _MainTex;

    struct Input {
        float2 uv_MainTex;
        float4 screenPos;
        float eyeDepth;
    };

    half _Glossiness;
    half _Metallic;
    sampler2D _CameraDepthTexture;
    fixed4 _Color;
    fixed4 _GlowColor;
    float _FadeLength;

    // Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader.
    // See https://docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing.
    // #pragma instancing_options assumeuniformscaling
    UNITY_INSTANCING_CBUFFER_START(Props)
        // put more per-instance properties here
    UNITY_INSTANCING_CBUFFER_END

    void surf (Input IN, inout SurfaceOutputStandard o) {
        float2 screenuv = IN.screenPos.xy / _ScreenParams.xy;
        float screenDepth = Linear01Depth(tex2D(_CameraDepthTexture, screenuv));
        float diff = screenDepth - Linear01Depth(IN.screenPos.z);
        float intersect = 0;

        if (diff > 0)
            intersect = 1 - smoothstep(0, _ProjectionParams.w * _FadeLength, diff);

        fixed4 col = fixed4(lerp(tex2D(_MainTex, IN.uv_MainTex) * _Color, _GlowColor, pow(intersect, 4)));
        o.Albedo = col.rgb;
        o.Alpha = col.a;
        o.Metallic = _Metallic;
        o.Smoothness = _Glossiness;
    }
    ENDCG
}

```

# Answer
Credits to bgolus, a member of the Unity forums, as the code is still a little bewildering to me.

It is possible.

```
Shader "Intersection Shaders/Surface Intersection Shader" {
    Properties {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _Glossiness ("Smoothness", Range(0,1)) = 0.5
        _Metallic ("Metallic", Range(0,1)) = 0.0
        _GlowColor("Glow Color", Color) = (1, 1, 1, 1)
        _FadeLength("Fade Length", Range(0, 2)) = 1
    }
    SubShader {
        Blend SrcAlpha OneMinusSrcAlpha
        ZWrite On

        Tags
        {
            "RenderType" = "Transparent"
            "Queue" = "Transparent"
        }

        CGPROGRAM
        #pragma surface surf Standard fullforwardshadows alpha:fade
        #pragma target 3.0

        sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;
            float4 screenPos;
            float3 worldPos;
        };

        half _Glossiness;
        half _Metallic;
        sampler2D _CameraDepthTexture;
        fixed4 _Color;
        fixed4 _GlowColor;
        float _FadeLength;

        UNITY_INSTANCING_BUFFER_START(Props)
        UNITY_INSTANCING_BUFFER_END(Props)

        void surf (Input IN, inout SurfaceOutputStandard o) {
            float sceneZ = LinearEyeDepth(SAMPLE_DEPTH_TEXTURE_PROJ(_CameraDepthTexture, UNITY_PROJ_COORD(IN.screenPos)));
            float surfZ = -mul(UNITY_MATRIX_V, float4(IN.worldPos.xyz, 1)).z;
            float diff = sceneZ - surfZ;
            float intersect = 1 - saturate(diff / _FadeLength);

            fixed4 col = fixed4(lerp(tex2D(_MainTex, IN.uv_MainTex) * _Color, _GlowColor, pow(intersect, 4)));
            o.Albedo = col.rgb;
            o.Alpha = col.a;
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```
> 0 votes

---
Tags: unity, shaders, graphics, fragment-shader, cg
---


# Question
Title: Is information about game assets copyrighted?
Let's say I extracted some assets from a closed source game.

Am I allowed to publish information (something like a list of filenames, sizes, duration, dimensions...) about those assets?

# Answer
Facts are not protected by copyrights but you should check if there aren't other local laws that apply where you live.

From USA law, www.copyright.gov, Library of Congress

> Copyright does not protect facts, ideas, systems, or methods of operation, although it may protect the way these things are expressed.

Many countries have international treaties to follow the same general copyright law (See Berne Convention). But not all follow the USA's copyright term extension act (A.K.A. Mickey Mouse Protection Act) that were changed after the initial agreement and every country will have variation in their interpretation of what constitute fair use.
> 2 votes

---
Tags: assets, copyright
---


# Question
Title: is if statements important or do I need them
Hey I was wandering I am needing some advice I am using #if expressions to execute my code and I was wandering if you have #if expressions is it really needing to use if statements in your c++ source code let me know thanks

# Answer
> 3 votes
`#if` isn't the same as a regular `if` statement, it is what's called a preprocessor directive.

In C & C++, preprocessor directives are lines of code that are preceded by a hash symbol (#). Unlike regular lines of code, these lines are not program statements; instead they are instructions (directives) for the preprocessor. The preprocessor executes before the compiler. It evaluates the code before compilation of code begins and resolves all preprocessor directives. After they have been processed, the compiler evaluates (including any changes that may have been made by the preprocessor) and proceeds to generate object code from the 'regular' program statements.

As to if you need them, the answer is - it depends. `#if` statements are often used for conditional compilation. For instance, you may have some code that only needs to compiled under certain circumstances. A common example is to use them to guard against repeat inclusions / definitions of code. Less commonly, you might have code that is dependant on certain hardware.

Without seeing the code (and possibly the environment), it's impossible to say whether or not you do or do not need them. You should know what they do. When I was doing C/C++ I rarely used them myself, but they were common in various libraries that I made used of.

---
Tags: c++, windows, visual-studio
---


# Question
Title: algorithm for combining smaller tiles to balance the bigger ones
I have a field of tiles - basically each tile is a country that has some kind of sovereign. The tiles - countries - have different weight. For now I use some numerical value but in the future the weight will depend on tile size, produced resources and so on.

So I want for those countries to make alliances if their sole weight is much lower - or at least lower than a certain threshold - than the weight of the neighborhood tile (each sovereign is basically a primitive AI at that stage that is able to make decision to create the alliance). Here is couple of scenarios

Here are the examples for bigger maps with possible *alliances*

So my question is - is there some kind of algorithm that allows to achieve that or I have to create it myself or use training sets for AI to gain the ability to form alliances?

# Answer
> 0 votes
It seems my problem is the similar to Bin packing problem mentioned by @wondra. Here is the definition of bin packing problem

```
Given a multiset S = { s1, s2..., sN } of N elements and a bin
capacity C, all positive integers, the bin packing problem is
to separate the elements of S into as few subsets (bins) as
possible, such that the sum of each subset is no greater than C

```

The definition of my problem is

```
Given a multiset S = { s1, s2..., sN } of N elements and number C,
all positive integers, my problem is to combine elements of S
into a few subsets, such that the sum of each subset is no
much greater than C (or possible threshold)

```

They are indeed similar

---
Tags: algorithm
---


# Question
Title: How do I find the name of the current audio clip being played?
I have a title scene and a credits scene that use the same music. When I start my game the title scene music plays, and I have my game set up so the audio manager is not destroyed on load. When I enter my credits scene I do not instruct any new music to play, but each time I reload my title scene the title music restarts because a script in the scene tells it do so.

How can I get the name of the current audio track so that I will only play audio if it differs from what's currently being played?

This is my "LevelMaster" script which is responsible for handling the audio in each scene.

```
public class LevelMaster : MonoBehaviour
{
private AudioManager AudioManager;

[SerializeField]
private string trackName;

private void Start()
{
    AudioManager = GameObject.Find("AudioManager").GetComponent<AudioManager>();
    AudioManager.Play(trackName);
}

public void PlaySound(string soundName)
{
    AudioManager.Play(soundName);
}

public void StopSound(string soundName)
{
    AudioManager.Stop(soundName);
}

```

# Answer
Since you're passing a string on AudioManager.Play(), I assume you're using a Dictionary \< string, AudioSource \> on your AudioManager.

You could change the Start code to the following:

```
private void Start()
{
    AudioManager = GameObject.Find("AudioManager").GetComponent<AudioManager>();
    if (!AudioManager.dictionary[trackName].isPlaying)
        AudioManager.Play(trackName);
}

```

Or, you could store a reference to the AudioSource used when you call AudioManager.Play(). This way you'll always have a reference to the last AudioSource played.
> 1 votes

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


title: Tic Tac Toe Victory State Detection

text:
# Question
Title: Tic Tac Toe Victory State Detection
Below is the code I'm using to check if the board state has a tic tac toe style victory state. The board is always square and is made of an array of objects that keep track of their own completion state (the variable board\[x,y\].complete is a boolean on if that node is currently complete) The current method is to see if the player can count to the width of the array in a single pass and if so use breaks to skip any future necessary checks.

But at the moment the code either ignores legitimate win states or falsely detects win states.

I'd be appreciative if anyone can give me pointers on what might improve the code or help solve for arbitrarily sized square boards.

```
///check to see if the player has bingo

var board = global.board;
var score_ = 0;
var row = 0;
var col = 0;
var victory = false;

//check horrozontal complete
for (col = 0; col < array_height_2d(board); col++)
{
    if victory == true
    {
        break;
    }
    for (row=0; row<array_height_2d(board); row++)
    {
        if board[row,col].complete == true
        {
            score_ += 1;
        }
    }
    if score_ == array_height_2d(board)
    {
        victory = true;
        break;
    }
    score_ = 0;
    score2 = 0;
}

//vertical checks
score_ = 0;
for (row = 0; row < array_height_2d(board); row++)
{
    if victory == true
    {
        break;
    }
    for (col=0; col<array_height_2d(board); col++)
    {
        if board[row,col].complete == true
        {
            score_ += 1;
        }
    }
    if score_ == array_height_2d(board)
    {
        victory = true;
        break;
    }
    score_ = 0;
}

//diagonal checks
score_ = 0;
var diag = 0;
for (diag = 0; diag< array_height_2d(board); diag++)
{
    if victory == true
    {
        break;
    }
    if board[diag,diag].complete == true
    {
        score_ += 1;
    }
    if score_ == array_height_2d(board)
    {
        victory = true;
        break;
    }
}
score_ = 0;
diag = array_height_2d(board);
while diag > -1
{
    if victory == true
    {
        break;
    }
    if board[diag,diag].complete == true
    {
        score_ += 1;
    }
    if score_ == array_height_2d(board)
    {
        victory = true;
        break;
    }
    diag -= 1;
}
score_ = 0;

return victory;

```

Examples of arrays that fail to detect a win state:

# Answer
> 0 votes
The code mysteriously started working again when I added more debug flags to it. Not sure what was wrong but if you need a solution to a similar issue, the above should work as a template.

---
Tags: algorithm, game-maker
---


title: Debug.DrawLine doesn't go straight

text:
# Question
Title: Debug.DrawLine doesn't go straight
Heres the code:

```
void Update() {
    Debug.DrawLine(attackSpot.position, attackSpot.TransformDirection(Vector3.forward * distance), Color.red);
    Debug.DrawLine(transform.position,  transform.TransformDirection(Vector3.forward * distance), Color.green);
}

```

I'm drawing 2 lines, one is coming from attackSpot and one is coming from own transform.

Reason of this because my Raycast doesn't worked properly, so I decided to see visually to check.

Of course, attackSpot is pointing front direction.

Rotation of attackSpot in screenshot is local rotation. But when the play game, line coming from attackSpot doesn't go straight, it moves lower direction.

I also tried

```
Debug.DrawLine(attackSpot.position, attackSpot.forward * distance, Color.red);

```

But has same result. Why my ray doesn't go straight? What am I missing?

# Answer
`Debug.DrawLine(Vector3 inWorldSpace, Vector3 inWorldSpace2, Color color)`

`Debug.DrawLine(attackSpot.position, attackSpot.forward * distance, Color.red);`

Let's set `attackSpot.position` to be `new Vector3(0f, 5f, 0f)` for this example. And leave rotation at `0`s.

Then in your case you would have result - `Debug.DrawLine(new Vector3(0f, 5f, 0f), new Vector3(0f, 0f, 1f) * distance(4f), Color.red)`.

Thus your drawing positions would be from `new Vector3(0f, 5f, 0f)` to `new Vector3(0f, 0f, 4f)`.

You need to do this :

```
Debug.DrawLine(attackSpot.position, attackSpot.position + attackSpot.forward * distance, Color.red);

```
> 3 votes

---
Tags: unity, raycasting
---


# Question
Title: Procedurally-generated 2D curved roads on map
I've been experimenting with algorithms to automatically generate road maps for a game I am working on.

I'm using the "Kingdom Rush" games as a reference point as they have some great-looking maps.

I am new to procedural content generation, and was wondering if anyone here has any pointers. I have experimented with generating random road topologies, e.g. a few entrance/source nodes, several inner nodes (fork and merge), and some exit sink nodes, then using graph-layout algorithms to create an actual road map based on this information.

Here's one example using the Fruchterman-Reingold algorithm for road layout:

The blue graph uses some randomly-generated Bézier control points to make the edges look less straight.

Here's another example generated using the same algorithm but different random numbers:

The trouble is most of the results end up looking quite similar, and I am not sure what rules I can add to improve the controllability and diversity of the procedurally-generated maps.

Any advice appreciated.

# Answer
> 2 votes
Your example roads have curves on the segments between intersections where your generated ones do not. Have you tried adding more "redundant" control points on your roads?

How about having the number of loops be a generation parameter? Also "curviness" (number of redundant control points) Number of exits would be another.

I think you could also end roads when they hit intersections by giving them double control points. That should make the intersections look better.

---
Tags: 2d, procedural-generation, maps
---


# Question
Title: Tiled - isometric map - how to find out tile width/height
so I'm playing aroung with Tiled and want to create an isometric map. I found this tileset:

https://opengameart.org/content/isometric-landscape

The downloaded file contains a big spritesheet with many sprites in it. What is the best way to find out what settings I need to have in Tiled to work with these?

I need to set a tile width/height for the map, and width/height for a tileset itself. What's the best way to find out? The problem with this specific tileset is that the tiles all have different sizes (but it's all in one big image).

There are images of each tile sprite itself, but I don't know how to "mass add" these to Tiled.

Thanks for any help

# Answer
> The downloaded file contains a big spritesheet with many sprites in it. What is the best way to find out what settings I need to have in Tiled to work with these?

The spritesheet included in that download is not directly usable in Tiled currently, because the images are not aligned to a grid. Rather there is an XML file describing the locations of each tile, which Tiled currently does not support (#1008).

> There are images of each tile sprite itself, but I don't know how to "mass add" these to Tiled.

You can mass-add them by creating a new tileset (selecting "Collection of Images") and then clicking the "+" icon in the tool bar and selecting all the files (or use drag-n-drop to drag them to the tileset from your file manager).
> 1 votes

---
Tags: isometric, tiled, tilesets
---


# Question
Title: How can the lategame in a 4X game be made more exciting?
I played a lot of different 4X games lately (eXplore, eXpand, eXploit, eXterminate, like the Civilization series, for example), and noticed that most of them suffer from the same problem: As soon as one player got significantly more powerful than the others, that player gets almost unbeatable. The dominant player has access to vastly more resources than the others. Also, that player has a significant advantage in research, which means that the other factions will soon fall back in technology, giving the powerful player even more tools which the weaker factions can not counter, so it makes the game even easier for them.

During this phase it is pretty clear that this player will inevitably win. However, the game usually does not stop here. It continues for hours while the dominant player steamrolls all the weaker players one after another. This poses no challenge to them, because they are so vastly more powerful. So this phase of the game becomes a dull and boring chore for everyone. The dominant player moves their units from one enemy base/city/planet to another knowing that nothing they could encounter there could stop them as long as they avoid some easily avoidable mistakes, while the other players watch helplessly in frustration without any way to prevent their demise.

How could a 4X game be designed to avoid this boring and tedious endgame?

# Answer
> 34 votes
This is a difficult question to answer objectively, but I will try to construct a solution to your problem without guessing:

You describe the problem at hand as an end of competition to one player because that player became too powerful. Note one thing, though: The player became powerful by terms of the balancing incorporated in the game, so either you change this balancing completely, or you change the "rules" for this state of the game only.

The first option may not be what you want, because the early game was not part of your critique and seems to offer a fun and exciting gameplay. Additionally its hard to construct a change of the whole game balancing targeting only this aspect.

So lets see how we can set rules for only this state of the game. We need to find something that "punishes" overpowerful player(s) by making their life harder or by supporting other players. I have a few examples for you, that can fit this description:

1. Cheat. A lot of games use "random" events to bring life and alternation to the world. Some of those are beneficial and some of those aren't. Example: Sim City Catastrophes or Mongol Invasion in Total War. A lot of games have catastrophes that can bring additional challenge to players. You may be able to "randomly" challenge the leading player with a lot more of those catastrophes. But be careful, in Sim City a whirlwind destroying your beautiful city may have been the only challenge for a perfect player, but it can be equally frustrating.
2. Something similar but more predictable may be better to maintain fun at last. You could add not only benefits from having a lot of cities under control and being far the most developt nation, but insert new problems that occur. Large cities are more likely to develop spreading diseases, a big nation is harder to control, more revolutions occur, costs for a lot of armies could skyrocket. These problems are especially able to punish players that expanded or explored to fast, without proper preparation.
3. No other player is a challenge for your leading tyrant. A scary situation, especially for the other players. From my own experience I can say that humans can be pretty careful to avoid this type of snowballing incontestable player. Every time I play something like Risk it is not only my task to become the most powerful player, but instead to seem like I'm doing bad. Because if you are clearly the candidate to win a game, others will start working together and bring you down. Which can still be a threat for you, even though you are leading the board. Total War: Shogun 2 used this technique and totally overdid it. In that game, if you have a big number of territories under control every single clan starts beating you, if you aren't prepared to win fast after that happens you often loose for good. Diplomacy stops working for you. This could be something realistic to use, even though I would advise to balance it properly.
4. My last idea is the only one of the type: Support the other players. A lot of 4X games have neutral factions that are to be conquered or to be worked with. While some of them surely like to work with the best-paying/most powerful player on the board, some might resent the idea to be overrun as much as normal players do and might start actually working together with smaller nations in new ways, or even voluntarily become part of them.

A combination of the techniques may help you balance out your game. But be aware, a game needs to have an end, you might prolong the game for good or make it more interesting, but if the result is always the same as before, or you totally destroy the fun of being the most powerful, you might have just created new problems.

Still I think your idea of keeping up the challenge is not bad, maybe you even make it "impossible" to win alone and increase the value of diplomacy.

# Answer
> 18 votes
In terms of balance, competitive games can generally be sorted into one of three types:

1. **Positive reinforcement**: When one player gains a small advantage over the other, that advantage gives that player an even larger advantage, which gives the player an even larger advantage, and so on. The advantage of this approach is that games tend to be very even at the start, and then end very quickly once one player takes the lead, thus minimising boring end-games. Games of this sort include arm wrestling and StarCraft.
2. **Neutral reinforcement**: When one player gains a small advantage over the other, that advantage does not affect the game mechanics. Games of this sort are usually structured as "first to reach 'n' points", such as in FPS deathmatch games, or else give players "health bars", such as in fighting games. Tug-of-war is another example of this sort of game. Neutral games can be lengthy, with a lot of back-and-forth, or one side hanging on for a very long time in a losing position, without ever quite hitting the losing threshhold.
3. **Negative reinforcement**: When one player gains a small advantage over the other, that advantage becomes a penalty to them, making them weaker, and other players stronger. This sort of game tends to last a long time (often infinitely long), and so usually needs some external ending condition; usually a pre-set duration. Mario Kart is the classic example of this, where the players in the back of the pack are given better pickups and drive faster than the players in the front. The advantage of this approach is that you're likely to end up with your players closely grouped when the game ends; if your players are of similar skill level, then no one player should be far in the lead, which makes the ending exciting.

In a 4X game, you're most likely to go with positive reinforcement; you want a player, having gotten ahead, to be at an advantage over the other players. And once that advantage becomes large enough, you want the game to end quickly. (I think it'd be fascinating to design a 4X game around one of the other two reinforcement models, but that's probably not what you had in mind)

**If you tend to have a long and tedious end-game phase, that means that you aren't getting enough positive reinforcement to overwhelm your opponent and bring the game to a close**.

One interesting approach to giving better positive reinforcement is in Chris Crawford's The Global Dilemma: Guns or Butter released in 1990, which set up its economic systems so that doubling the amount of money spent on something quadrupled the amount of output. So for example, if $1000 bought a tank, then $2000 bought four tanks. And $4000 bought sixteen tanks. And $8000 bought sixty-four tanks. (Note that in Guns or Butter, your money had to be completely spent each turn; you couldn't "save up" between turns)

This meant that if you gained more production capacity than another player, you were very quickly able to leverage that economic advantage into a massive military advantage, to bring the game to a speedy and exciting conclusion.

It's also worth noting that in 4X games (and other territory-taking games), the larger the map you're playing on, the more positive reinforcement is required in order to bring the game to a close in a timely manner. If you don't want to put a lot of extra positive reinforcement into your game, you may find that simply reducing the size of your map makes things a lot more satisfying, without making any other changes to the game.

# Answer
> 16 votes
In my opinion, the way you fix this is to decouple the victory condition from the production mechanic.

For a great example, check Eclipse, the board game. You can score a lot of points just for researching tech and building monoliths. The monoliths don't give you anything except points, and tech doesn't give you anything *directly*. You also gain points for the usual conquest and fighting, but a sneaky player can avoid conflict and still score a lot of points.

Of course, this also works in tandem with the game's duration: 9 turns. The game is forced to end before the militarized player can completely destroy all of the non-fighting player's stuff.

So if you're making a 4X computer game, I'd say try use a similar principle. Game's end is not defined by conquering every one else (like the Alpha Centauri victory condition in Civilization or fixed time), and there are ways to approach victory without just conquering and fighting.

# Answer
> 7 votes
In fairly chaotic systems, like nature, you often find that when one thing rises to be the dominant force in the system, the system changes and something else will inevitably react to counter this - it might be something getting stronger, but it can also be the creation of something new.

I use the term country but it could be a game about any group entity.

**Real World Example**

One example I can think of is the company, it's competition and the unions.

In instances where a company becomes the dominant force in a market it is common for another company to rise to the challenge, invest more in research and development and try to become more competitive. These companies will compete in the market as well as over employees - with better wages and bonus packages etc. However, in instances where this doesn't work out and companies don't compete well enough over employees, the chances of a workers union being created can increase.

Now this is a very basic summary of the situation, but I felt it was analogous to this situation...

**Application as a Mechanic**

In the end game there are no countries left with a good competative edge. In these situations companies do tend to merge. So to make the end game more interesting it might be worth having countries form mergers - whether it's larger unions of countries or pacts or simply that two countries agree to merge.

However, it may also be that there is no way to merge enough countries to make a singular competitive entity, as is the case with companies.

In this situation you can increase the difficulty by providing a threat from within. When people in countries get more settled and comfortable they start to be more concerned with other things, like culture and societal structure.

So if providing unions of countries doesn't give a big enough threat, have the players country diverge in it's ideas and try to have the player balance it's own internal politics while also engaging other countries.

# Answer
> 7 votes
In multiplayer games, a very effective "automatic" balancing mechanism is that the weaker players can (and have a strong incentive to) join forces against the strongest one.

Some ways to make this work more effectively include:

* Make sure that your players *can* cooperate effectively. There should be ways for players to trade and/or simply donate resources, to combine forces for mutual defense (or offense) and perhaps to form mutual trade and scientific cooperation treaties (and, of course, to exclude some players from such cooperation).
* Consider building in mechanisms to encourage trust between cooperating parties. For example, you could allow binding mutual non-aggression pacts (possibly limited to specific units), so that players can safely invite neighboring players' units to help in their defense without having to worry about the units turning against them. There's something of a tradeoff here between realistic and complex diplomacy on one hand, and improved auto-balancing on the other, so you'll want to decide how much of this you want.
* If you have NPC factions, make sure their AI also tries to cooperate with weaker players against the strongest one. If one player looks too strong, you can even have NPCs factions offering to unconditionally merge with the weaker player factions.
* Make the relative strength of each player clearly visible at all times, so that it's easy for other players to tell who's strongest and how close they are to winning. Try to make sure that a player cannot *easily* enter the "steamroller" stage without the other players noticing and having the opportunity to stop them. (It's OK — and perhaps even desirable — to allow a careful player to quietly gather strength before suddenly making a bid for victory, but this should normally require actual strategic play, not just steadily building resources while others don't notice.)
* Give the players effective means, other than just plain direct offense, to sabotage others. These can, and probably should, be costly to the sabotaging player too — the important part is that several weaker players should be able to focus their sabotage efforts on the strongest one. Make sure your NPCs can use them strategically, too.
* Last but not least, don't give any consolation prizes. If there's something to be gained for being second-best, the weaker players will be tempted to compete with each other for the silver medal, instead of ganging up on the strongest player like they should.

You'll also want to ensure that, when one player (whether through guile or just brute strength and persistence) does get to the stage where they're undefeatable, even by all the other players and NPCs together, the game should end quickly.

One way to achieve this (and also the goal of clearly signaling when someone is close to winning) is to have some specific single goal whose achievement decides the game. For example, your game world could have a single heavily defended (but otherwise neutral) location whose capture wins the game. That way, it's pretty obvious when someone sets out to try and capture this location, and if they do succeed, they win immediately.

(Of course, to make this work, other players must be able to help defend the target location, or otherwise sabotage attempts to capture it. You could also, say, make players lose immediately if their capital site is captured; that way, if someone makes a premature play for victory and commits too much of their forces to it, others can attack their now poorly defended capital, and take it out before the over-eager player can win.)

By the way, to see this balancing mechanism in action, I'd very much recommend trying the card game Munchkin. It's nothing like a 4X game, but it does have a *very* strong emphasis on (sometimes literal) backstabbing and rapidly shifting inter-player alliances. The main victory condition is very simple (reach level 10 through combat) and, combined with the plentiful single-use resources that can be used to aid or (more commonly) harm any other player in battle, pretty much guarantees that the game ends in an epic one-against-all fight.

# Answer
> 3 votes
If a dominant power is in control, then give the other players non-dominant options to handle it. Star Wars: Forces of Corruption did something like this, by means of "Corruption", basically a criminal influence in other people's territory.

Some examples could be:

* Sabotage
* Crime
* Rebellion
* Assassination
* Bribery
* Theft
* Guerrilla Tactics

Another suggestion could be as a player advances, their progress is along a track, and based on this track, they have benefits and weaknesses. If the player is very advanced technologically, they might underestimate a weaker enemy, which can give the other player a bonus when using guerrilla tactics.

Hope this helps!

# Answer
> 2 votes
Many games suffer from linear progression. Things seem to difficult at the start, but later on it is too easy and becomes boring.

In the context of a 4X game this could be prevented by making spying easier when a civilisation is larger. It makes sense that if their borders are larger and their machines more numerous, then it should be easier to steal those ideas. This would mean that the leading civilisation will slowly help the others to advance.

Another issue facing civilisations is outside interference. Imagine a space 4X where if one civilisation got too far ahead and were mercilessly crushing others, perhaps an even older, even more powerful computer controlled civilisation could turn up and try to redress the balance of power. They could still win, but now there is a bigger threat for them to face and may have to rethink their strategy of steamrollering.

Perhaps something more "humane" could be added too. What if you were so advanced that the other civilisations were no match, and you decided to crush them. Not everyone you despotically rule over will like this. perhaps they will start to form dissident groups, then a resistance force and finally revolt and kill you! There you are forging ahead with your evil plans and you overlook your own people and are assassinated or deposed.

Anyway, those are a few that come to mind, but there are plenty of ways that an advanced civ might not automatically have so much of an advantage that they can roll over the others.

# Answer
> 2 votes
**Add other goals to win the game.**

Most X4 games concentrate on conquer victory. So you could add goals that can be reached by less powerful players by a good strategy.

Sid Meier's Alpha Centauri for example has multiple goals to win the game. Classic conquer victory, economic victory, tech victory and supremacy victory. These goals seems to be a bad idea, but in Alpha Centauri, research speed, tax collection and many other factors depend heavily on the society settings of your faction. So if you concentrate on research, you will be vulnerable for other types of war. And if you drive your war machine, research will decay and make you also vulnerable because of bad equipment. A good strategy balancing is needed. All in all, even the strongest player will have an vulnerability. These vulnerabilities are enforced by the alternative victory goals. The strongest player can fail because someone else collected enough money or reached a special tech or built a special project.

In your described bad case, the game can be ended quickly by supremacy victory, simply persuade 3/4 of all others players to accept you as supreme leader. There are also planet busters (nonconventional bombs) that can break even the strongest players but for the high cost of ingame reputation and sanctions.

# Answer
> 1 votes
# Look at the Munchkin!

What I am going to talk about has generally been said before, but I think that I have a *perfect* example to illustrate some of the points and gather them together: the tabletop game called Munchkin. This example is perfect not just because it has all the tools needed to ensure that it stays interesting for the whole session, but also because this game is so simple and easy to understand.

* There is an ultimate winning condition that ends the game: in the basic version, it is one player reaching 10th level. When this condition is met, the game ends, so the player with an upper hand doesn't have to chew through a series of boring adventure.
* It is clearly visible to all the players how are things going by any of them: which level does each player have, how many bonus power points, how many cards at hand... This allows to easily understand who is winning and should be stopped, and who is losing and could use some mutual help.
* Players have *a lot* of ways, a boatload of means to mess with each other without even directly attacking each other.

All in all, if someone gets a significant advantage, they are either stopped by the collective effort of all the other players or quickly get to the victory and enjoy winning if other players have no resources to use against the potential winner. No time is wasted.

## What exactly to look at?

As others have basically already noted...

* Make it possible to have active "diplomacy": ability to unite against each other and break up the alliances ***at will***. Could be as simple as being able to attack each other at will, like in Munchkin.
* Make it possible for the players to know (or roughly know) how are things going by each of the players so they know who to plot against. It could be as easy as a menu where everything is automatically available, or as interesting as a complicated bunch of mechanics of espionage! Concealing the fact of being close to victory, if even possible, should require a lot of investments.
* Make it possible to quickly (very quickly!) win the game if nobody can create a real threat for the advantageous player anymore. E.g. winning in a space race (Civilization), casting a Mastery spell (Master of Magic), building the Holy Grail (Heroes of Might and Magic)...

Note that negative reinforcements for advancing in the game are generally a lot more annoying rather than helping.

1. Often it doesn't allow others to win, but instead simply delays the inevitable, thus making the situation only worse. You should make the victory of the player who got a strong advantage *quicker*!
2. It feels like the victory being stolen from you.
3. For others, it feels like being condescending to them.

A victory should require effort to achieve, and this effort should stay valuable, otherwise, the victory itself loses its value.

---
Tags: game-design, balance, turn-based-strategy, 4x
---


title: Events vs direct reference in Unity3D?

text:
# Question
Title: Events vs direct reference in Unity3D?
I'm developing a simple NPC controller that the player can talk with.

At the moment a `NPCController` script on the NPC gameobject manages several "high level" feature of the NPC such as *intelligence*.

Every time the player talks with the NPC, the latter will respond with "Bzz", "Hello" or "Heya" depending on his *intelligence* level.

The talking part is implemented in a `TalkController` script. I did this way in order to have multiple behaviours depending on the player/npc interaction without creating a giant `NPCController` class. Plus some NPC may not speak at all (in this case I'd simply remove the `TalkController`).

I have a small dilemma on how to change the NPC response in `TalkController` based on the *intelligence* level in `NPCController`.

I could use Events:

```
// NPCController.cs

public delegate void OnIntelligenceLevelHandler(int level);
public static event OnIntelligenceLevelHandler OnIntelligenceLevelChanged;

// When intelligence increases
OnIntelligenceLevelChanged(2);

```

and:

```
// TalkController.cs

// Store _intelligence = 1;
// Subscribe to OnIntelligenceLevelChanged
// Upgrade _intelligence when the event fires
// Switch word on _intelligence when talking

```

I could use a direct reference:

```
// TalkController.cs

// Store _npccontroller = GetComponent<NPCController>();
// Switch word on _npccontroller.Intelligence when talking

```

What would be the best approach?

# Answer
> 0 votes
In your specific use-case, I'd say both are good.

The reference method will give you access ofc to all the other `public` elements of `NPCController`, so that's a plus if needed, whereas the event method will keep the objects decoupled.

The events in C# are there to implement very easily the observer pattern, keeping the observed and the observed decoupled and making "things happen" in more than one place when the observed object raises the event.

Getting references is useful when you need to access directly more than one element of the referenced object, but that goes with a strong coupling between the referenced and the referencer objects.

Personally, I like to use events if I don't need to access more than one element in the observed object, just to keep things "safer" in some way (I like to keep objects decoupled the most I can).

---
Tags: unity, events
---


title: Unity Movement Questions

text:
# Question
Title: Unity Movement Questions
I have recently been trying to learn how to make Unity games through Lynda.com using the tutorials provided by Jesse Freeman. But I have one issue, he doesn't explain any of the coding. This bit has me confused.

```
Body2D.AddForce (new Vector2 (forceX, forceY));

```

1.) Why is Body2D (this is a variable) separated by AddForce with a **.**?

2.) Why does a new vector2 have to be created?

3.) My last question isn't quite in the code itself but why must we add a () to methods?

---

(Full Code)

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

public class Player : MonoBehaviour {

public float Speed = 2.5f;
public Vector2 MaxVelocity = new Vector2 (5, 10);

private Rigidbody2D Body2D;
private SpriteRenderer Renderer2D;

// Use this for initialization
void Start () {
    Body2D = GetComponent<Rigidbody2D> ();
    Renderer2D = GetComponent<SpriteRenderer> ();

}

// Update is called once per frame
void Update () {
    var absValX = Mathf.Abs (Body2D.velocity.x);

    var forceX = 0f;
    var forceY = 0f;

    if (Input.GetKey("right")){
        if (absValX < MaxVelocity.x) {
            forceX = Speed;
        }
    } else if (Input.GetKey("left")) {
        if (absValX < MaxVelocity.x){
            forceX = -Speed;
        }
    }
    Body2D.AddForce (new Vector2 (forceX, forceY));

}

```

# Answer
> 1 votes
> But I have one issue, he doesn't explain any of the coding. This bit has me confused.

It sounds like the tutorials you are following assume a certain level of familiarity with the C# programming language used by Unity that you may not have. You may want to take a break from those tutorials to read a little bit about the language itself outside the context of Unity. The MSDN has some reference you might find helpful. At the very least you should consider looking at this material concurrently with the Unity tutorials.

> 1.) Why is Body2D (this is a variable) separated by AddForce with a .?

The "dot operator" is used to access members of a type (or namespace, but that isn't the case here). The type of variable `Body2D` has a collection of functions and properties, and the dot operator is used to access them -- in this case, to access and call the `AddForce` member function of whatever `Body2D`'s type is.

> 2.) Why does a new vector2 have to be created?

The `new` operator is how all new instances of objects are created. `AddForce()` requires a `Vector2` for its first parameter. One could create that vector earlier, like:

```
Vector2 force = new Vector(10, -1);
Body2D.AddForce(force);

```

*or* one could just create the new vector inside the function call, as in your original example.

> 3.) My last question isn't quite in the code itself but why must we add a () to methods?

The `()` in this case represent the invocation operator. They exist to indicate that the expression is a call to (an invocation of) some function, with parameters specified in between the opening `(` and closing `)`. When you define methods, they're used to indicate what the parameters to that method (if any) are.

---
Tags: unity
---


# Question
Title: When there are multiple objects of the same type, how do I know which one I am colliding with?
I'm working on a platformer game using Gamemaker Studio 2. , and currently I'm dealing with implementing platforms (those thin tiles that are able to pass through from the bottom, but remains solid when landing on).

To use some more advanced collision detection, I'm using `place_meeting()` instead of the build-in Collision Event.

It's working good and well for a single platform, but when I add multiple, then only the lowest placed platforms will work properly. I'm already aware that the problem lies on the second if-statement in the code below:

```
if (place_meeting(x, y+mySpeed[1], o_platform) &&       //If the player collides with a platform
    mySpeed[1] > 0  )                                   //if the player is falling
{
    if ((y + 29) < o_platform.y)                        //if the player's feets are located higher than a platform
    {
        while !place_meeting(x, y+sign(mySpeed[1]), o_platform)
        {
            y += sign(mySpeed[1]);
        }
        mySpeed[@ 1] = 0;
    }
}

```

The problem is likely because it's reading information from *any* platform. but not the higher platform I'm colliding with. So I should need a check to make sure the program knows it's the same object I'm colliding with.

If this was the build-in Collision Event, I could use the `other` statement to get the right instance, but currently I'm using `place_meeting` in a step method to collide, and `other` would be too broad to use properly. So how would I be able to archieve this?

# Answer
> 0 votes
Instance\_place did the trick.
If you want to use the object ID outside the collision event, then you can use `Instance_Place` instead of `Place_Meeting`.

```
var myObject = instance_place(x, y, object)
if (myObject != noone)
{
    //...you can use myObject as the object it's colliding with.
}

```

# Answer
> -1 votes
* Have an array objects (or a dict of )
* Give your objects a ulong ID field
* Whenever you create an object, assign it an ID incrementally and then index it into the array with that id

Now whenever you collide with an object you just called:

var myCollider = arrayOfObjects\[object.ID\]

*NOTE: It'd be better to do this with a **Dictionary** if you're in C#, but since I don't know what language you're in I gave you a starting point of using an array. An array in this implementation may well waste a lot of memory if you have lots of destructable objects.*

---

The other way to do this is usually done by a Delegate (or a callback depending on your language.) I would imagine if you're in game-maker that you can probably find something out there on this; but the above will work either way.

---
Tags: collision-detection, game-maker, gameobject, game-maker-studio-2
---


# Question
Title: Server/Client Design for Clash of Clans Like Game
I'm working on the server/client design for a game similar to Clash of Clans. I've read through dozens of articles and have some general parameters of what I'd like to accomplish.

* Scalable (Probably will use AWS for load balancing and multiple instances and what not)
* Secure - Server is authoritative
* Fast - Make as much code run on client as possible.

So on the note about Fast/Secure. My game will have a save file. For the sake of argument, let's assume that the save file contains an array of buildings `MapBuildings` and the player's current cash amount `cash`. From my reading, the server should manage the save file. For example, the server will update the cash quantity every few seconds be taking the time difference between the last update, multiply by the cash production rate, then set the cash value. If the player taps "upgrade" on a building, it will send a request to the server "hey, the player upgraded building at (x,y)", then, the server will verify the player has enough cash, subtract it, and return the new cash amount. I also read that using a save file ONLY on the server isn't the best, because then the client will experience more latency because it has to wait for a server response for everything. So the client should have a save file too that's instantly updated, but verified against the server's response. So this is where I'm stuck, verifying and rectifying differences between the server's save file and user's save file. Here's my currently proposed solution, it has some holes, which I'm hoping you can fill in.

* Game is launched, the client's save file is used to initialize the game state. The save file's values are NEVER updated by the client.
* User has $100, and taps "upgrade" on a building (upgrade costs $50). Client checks cash (in game state, not save file), subtracts $50, and upgrades building to the gamestate immediately.
* Cash is now $50
* Client performs tick method, let's say cash production is $1/second. Client will take the time since last tick, and calculate the cash to add. Let's say client does this and now says the player has $51 dollars.
* Client adds "building upgraded" request to the network queue
* The queue is sent to the server every x seconds (I'm thinking 5 or 10 seconds?)
* Server checks if the user has at least $50, they do, so the server subtracts $50 off, adds the upgraded building to the save file, internally calculates how much gold the player should have ($51, based off time) and returns the changed values to the client
* Client receives changed values, overwrites save file (keep in mind, save file wasn't updated by the client), and saves the file to the file system.
* Client then verifies the save file's values according to the game state, if they don't match, they need to be resolved.

Here are the holes I'm struggling with:

* How do I account for latency between the client's calculated cash value and the server's? For example, the client will have generated a small fraction more cash, and the server's value will be x seconds behind, where x is latency. I want this to be really stable, I'll elaborate on this more in the next items.
* How should I compare the game state and the save file? This would require quite a bit of code to make sure they match, is this performance friendly?
* If the game state and save file don't match, should I make the user relaunch the game (to load initial values from save file again), or should I try to over-write the values in the gamestate? This could be challenging, because overwritting the game state could make the game appear really messed up to the user (buildings rapidly changing position, values jumping to different values). I'd lean towards forcing the user to reload, but as state in hole #1, this needs to be rock-solid so that a normal, non-cheating user will rarely experience a force reload dialog.

So, is my analysis model correct? Should I use a different model? How can I change my current model to fix the holes and verify an insync and clean networking interface between server and client? Also, if you have some resources, it'd be great if you can post them.

# Answer
The server should maintain and store the game state. It's never going to be secure if the user has access to a save file, and as you noted, the whole business of figuring out whose game state to believe is trouble.

So the server verifies transactions and saves the state - when the client connects he gets a bulk download of everything he needs for the GUI. The real game state is always what the server says, but for the sake of convenience things the user tries to do (like spending money) can be reflected immediately in the GUI and then replaced when the server supplies a new authoritative value.

If there are many things that ought to change as a function of time, make the server broadcast a "game time" token, and let the client deduce and display all the changes independently of the server. Verify that they're still in sync by generating a hash of all the state variables and comparing the server and client values.
> 0 votes

---
Tags: libgdx, networking, multiplayer, client-server, server
---


title: Perlin Noise Problem with Falloff

text:
# Question
Title: Perlin Noise Problem with Falloff
I know this might be a bit of a noob question, but I can't figure out what I'm doing wrong, and the math that I have done should make this work correctly. I am trying to make a perlin noise map that is normal until a specific range, at which point it would decrease to where all the values trend towards zero, creating an island in an ocean. I am currently generating perlin "sample" values, and then dividing them by a factor which stays close to one up to a specific bound, and then increases polynomialy. The problem however, is that the noise stays stuck in the top right corner, and is darker than I would expect. Here is the mathematical function I am using graphed on Desmos where n is the boundary and x is the distance from the center of the map:

And here is the main body code I am using to generate the noise map:

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

public class GenNoise : MonoBehaviour {

public int width = 256;
public int height = 256;

public float scale = 20f;

public float offsetX;
public float offsetY;

public float falloffRange = 100;
public float falloffPower = 10;

public void RenderNoiseMap()
{
    Renderer renderer = GetComponent<Renderer>();
    renderer.sharedMaterial.mainTexture = GenerateTexture();
}

Texture2D GenerateTexture () {
    Texture2D texture = new Texture2D(width, height);

    for (int x = 0; x < width; x++)
    {
        for (int y = 0; y < height; y++)
        {
            Color color = GenerateColor(x, y);
            texture.SetPixel(x, y, color);
        }
    }

    texture.Apply();
    return texture;
}

Color GenerateColor(int x, int y)
{
    float xCoord = ((float)x / width * scale) + offsetX;
    float yCoord = ((float)y / height * scale) + offsetY;
    float falloffFactor = FalloffFactor(x, y, width, height);

    float sample = Mathf.PerlinNoise(xCoord, yCoord);
    sample = sample / falloffFactor;
    return new Color(sample, sample, sample);
}

float FalloffFactor(int x, int y, int width, int height)
{
    float falloffFactor = 1;
    float centerX = (float)width / 2;
    float centerY = (float)height / 2;

    float distanceFromCenter = Mathf.Sqrt(Mathf.Pow(2, ((float)x - centerX)) + Mathf.Pow(2, ((float)y - centerY)));
    falloffFactor = Mathf.Pow(2, (Mathf.Pow(falloffPower, (distanceFromCenter / falloffRange)) + 1));

    return falloffFactor;
}
}

```

And Here is the code that I am using to generate the image in the editor:

```
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(GenNoise))]
public class NewBehaviourScript : Editor {
public override void OnInspectorGUI()
{
    DrawDefaultInspector();

    GenNoise script = (GenNoise)target;
    if (GUILayout.Button("Generate"))
    {
        script.RenderNoiseMap();
    }
}

}

```

Here is a picture of the result:

# Answer
I think your `Mathf.pow` functions all have the arguments reversed. e.g. `Mathf.Pow(2, ((float)y - centerY)))` is `2^(y-centerY)`, where you probably meant to do `(y-centerY)^2` considering that you're trying to calculate a distance.
> 0 votes

---
Tags: unity, c#, perlin-noise, noise
---


# Question
Title: How to implement the graph for pathfinding using A*
The game I am working on is based on a maze where each level is procedurally generated. The pathfinding grid is a 2D array where each node holds its connections. Path requests are handled one at a time so there can't be two path calculations going on simultaneously. So far I have each node hold its data required for the A\* (H,F,G scores and its parent) and manipulate them directly in the algorithm. Since the nodes are the actual nodes and not copies of them, every time the algorithm runs the data changes permanently and I have to manually set them on default values before the next run.

**So my questions are :**

**1) Is this a valid way of handling pathfinding in a game?**

**2) What other data manipulation techniques I could use in order to avoid that?**

If you need a copy of the code it's all on my github under Pathfinding and Managers/PathfindingManager.

# Answer
> 2 votes
You can avoid the manual reset by also adding a counter to each node that is set whenever the data needs to change. You only need to store f though as that is what is being used to compare. Though that will depend on how expensive h is to calculate.

Every time you run the path search you increment the counter and if the counter in the node does not match it you treat it as if it's default. Only when that counter rolls over will you need to do a manual reset, if the counter is 64 bit then that won't happen in any reasonable-length play session even if you do \>1000 A\* per frame.

You will need to hold the result path *somewhere* so your entities can use it.

---
Tags: unity, c#, path-finding
---


title: LibGdx Box2D Touch Input Movement

text:
# Question
Title: LibGdx Box2D Touch Input Movement
I've created 2 buttons for movement in my game but when those button are being pressed, the character gets basically thrown away and by pressing only once the movement it's continuous and i don't understand with box2D what's the right way to handle the movement of the character

The code looks something like this:

```
public class PlayScreen implements Screen {

    private SuperShooter game;
    private OrthographicCamera gamecam;
    private Viewport gamePort;
    private Hud hud;
    private OrthographicCamera guicam;

    Rectangle wleftBounds;
    Rectangle wrightBounds;
    //Vector3 for keeping the coordinates
    Vector3 touchPoint;
    //Texture for touch buttons
    Texture leftRegion;
    Texture rightRegion;

    private TmxMapLoader mapLoader;
    private TiledMap map;
    private OrthogonalTiledMapRenderer renderer;

    //Box2D Variables
    private World world;
    private Box2DDebugRenderer b2dr;
    private John player;

    public PlayScreen(SuperShooter game){
        this.game = game;
        gamecam = new OrthographicCamera();
        gamePort = new StretchViewport(SuperShooter.V_WIDTH / SuperShooter.PPM, SuperShooter.V_HEIGHT / SuperShooter.PPM, gamecam);

        hud = new Hud(game.batch);
        mapLoader = new TmxMapLoader();
        map = mapLoader.load("Level1WithObjects2.tmx");
        renderer = new OrthogonalTiledMapRenderer(map, 1/SuperShooter.PPM);

        gamecam.position.set(gamePort.getWorldWidth()/2, gamePort.getWorldHeight()/2, 0);

        world = new World(new Vector2(0,-15), true);
        new B2WorldCreator(world, map);

        b2dr = new Box2DDebugRenderer();
        player = new John(world);

        guicam = new OrthographicCamera(480, 320);

        guicam.position.set(480/2F, 320/2F, 0);

        wleftBounds = new Rectangle(0,0,80,25);
        wrightBounds = new Rectangle(80, 0, 80,25);

        //creating the vector
        touchPoint = new Vector3();

        //Instantiating Textures
        leftRegion = new Texture(Gdx.files.internal("back.png"));
        rightRegion = new Texture(Gdx.files.internal("next (1).png"));
    }

    @Override
    public void show() {

    }

    public void handleInput(float dt){

        if(Gdx.input.isKeyPressed(Input.Keys.R)){
            game.setPlayScreen();
        }

        for (int i=0; i<5; i++){
            if (Gdx.input.isTouched(i)) continue;
            guicam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0));
            if (wleftBounds.contains(touchPoint.x, touchPoint.y)){
                player.b2body.applyLinearImpulse(new Vector2(-0.02f, 0), player.b2body.getWorldCenter(),true);
            }else if (wrightBounds.contains(touchPoint.x, touchPoint.y)){
                player.b2body.applyLinearImpulse(new Vector2(0.02f, 0), player.b2body.getWorldCenter(),true);

            }
        }

    }

    public void update(float dt){
        handleInput(dt);
        world.step(1/60f, 6, 2);
        gamecam.position.x = player.b2body.getPosition().x;
        gamecam.update();
        guicam.update();
        renderer.setView(gamecam);
    }

    @Override
    public void render(float delta) {

        update(delta);
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        renderer.render();
        //render our Box2dDebugLines
        b2dr.render(world, gamecam.combined);

        game.batch.setProjectionMatrix(hud.stage.getCamera().combined);

        hud.stage.draw();

        //draw touch buttons
        game.batch.begin();
        game.batch.draw(leftRegion, wleftBounds.x, wleftBounds.y, wleftBounds.width, wleftBounds.height);
        game.batch.draw(rightRegion, wrightBounds.x, wrightBounds.y, wrightBounds.width, wrightBounds.height);
        game.batch.end();

    }

    @Override
    public void resize(int width, int height) {
        gamePort.update(width, height);
    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void hide() {

    }

    @Override
    public void dispose() {
        map.dispose();
        renderer.dispose();
        world.dispose();
        b2dr.dispose();
        hud.dispose();
    }
}

```

So, the player moves with 0.2f and -0.2f and if i change it to 0.1f it won't move at all..and the movement feels like it's too fast, you touch it once and the character keeps moving :( are there any other ways to do this?or what's wrong with this code? should i change the way that the force it's applied to the character?

# Answer
Firstly. I am not sure that you are asking about a platformer or a top down styled game. And for reducing speed overtime you should do it by multiplying the speed to a float \<1 for example:

```
          Player.speed *= 0.75f;

```

Those value is common for physics place the code in update method or something that ran each frame. Btw sorry if it is not clear as i never worked with Box2d before.

And if those method wasnt working i suggest you make your own simple physics engine.

Another notes: some physics engine have a density field/variable on each object, maybe changing that would work.
> 0 votes

---
Tags: libgdx, movement, touch
---


# Question
Title: How to position spawned objects in diamond and grid (row x column) arrangements
I am creating clones of my objects using the code below:

```
public List<Vector3> clonePositions;
public List<GameObject> cloneObjects;

for (int i = 0; i < clonePositions.Count; i++)
    {

        cloneObjects.Add(Instantiate(clonedObject,
        clonePositions[i], quaternion.identity));

    }

```

How can I create and position the cloned game objects in a grid/matrix (row x column) arrangement (with equal spacing between and at equal spacing at the sides)? as seen below:

and also in a diamond shape arrangement as below:

I would like to keep the clones centered around the original game object.

# Answer
You should use nested for loops:

```
for (int x = 0; x < width; x++) {
    for (int y = 0; y < height; y++) {
        Vector3 pos = new Vector3(x * size, y * size, 0);
        cloneObjects.Add(Instantiate(clonedObject, pos, quaternion.identity));
    }
}

```

Where width is the grid width, height is the grid height and size is the distance between two points. The diagonal case can be achieved with a small change:

```
Quaternion rotation = Quaternion.Euler(0, 0, -45);
for (int x = 0; x < width; x++) {
    for (int y = 0; y < height; y++) {
        Vector3 pos = new Vector3(x * size, y * size, 0);
        Vector3 rotated = rotation * pos;
        cloneObjects.Add(Instantiate(clonedObject, rotated, quaternion.identity));
    }
}

```
> 1 votes

---
Tags: unity
---


title: What issue in the shot in unity 3D?

text:
# Question
Title: What issue in the shot in unity 3D?
when the start game in the client \[localserver\], the bullet can't forward in the space just fixed in the Gun, here image about what I say:https://i.stack.imgur.com/AjMPG.jpg "image"

network manager https://i.stack.imgur.com/ksHBg.jpg "image"

player https://i.stack.imgur.com/7kdr2.jpg "image"

bullet https://i.stack.imgur.com/s9Nz5.jpg "image"

and this my script

```
    void Update()
   {
      if(!isLocalPlayer){
          return;
      }
      if (Input.GetKey(KeyCode.Mouse0))
      {
         CmdBulletFire();
      }
   }
  [Command]
  void CmdBulletFire()
  {
    // create the bullet prefab
    GameObject bullet = Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation);

    //add velocity to bullet
    bullet.GetComponent<Rigidbody>().AddForce(transform.TransformDirection(Vector3.forward * 50000f));
    //Spawn the bullet
    NetworkServer.Spawn(bullet);
    //Destroy the bullet
    Destroy(bullet, 5f);
}

```

# Answer
I am sharing my code which works fine use this on hope so it will work

```
 public   void OnButtonDown()
{

    GameObject bullet = Instantiate(Resources.Load("bullet", typeof(GameObject))) as GameObject;
    Rigidbody rb = bullet.GetComponent<Rigidbody>();
    FireClick.Play ();
    bullet.transform.rotation = Camera.main.transform.rotation;
    bullet.transform.position = Camera.main.transform.position;
    rb.AddForce(Camera.main.transform.forward * 500f);
    Destroy(bullet, 3);

}

```

use this

```
 rb.AddForce(Camera.main.transform.forward * 500f);

```
> 1 votes

# Answer
'Vector3.forward' is shorthand for writing Vector3(0, 0, 1).

What you're looking for is 'transform.forward'. This is the direction your transform is facing.

```
 bullet.GetComponent<Rigidbody>().AddForce(transform.forward * 50000f, ForceMode.Impulse);

```
> 1 votes

---
Tags: unity, c#, 3d, multiplayer, character-development
---


# Question
Title: How do I convert OnCollisionEnter2D to OnMouseDown?
I created a simple animation.

I have a `"Gamer"` object, which I move and hit squares to destroy them.

Squares I have to destroy in the right order `(1-2-3-4-5 etc.)`

If I make a mistake, the animation comes to an end.

However, I would like to change this code now. I would like to change `OnCollisionEnter2D()` on `OnMouseDown()`.

I would like to continue to delete the squares one by one, but instead of using a collision - simply click on the squares.

Could anyone help you convert this code?

This is my code posted to the `"Gamer"` object:

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

    public class Gamer : MonoBehaviour {

    int index =1;
    public GameObject gameOverText, restartButton ;

    public GameObject WinningText, ExitButton, NextLevelButton ;

    public GameObject Manager;

    void Start () {
        gameOverText.SetActive (false);
        restartButton.SetActive (false);
        Manager.SetActive (true);
        WinningText.SetActive (false);
        ExitButton.SetActive (false);
        NextLevelButton.SetActive (false);
    }
    public void OnCollisionEnter2D (Collision2D col)
    {
        Debug.Log("Player hit object: " + col.transform.name);
        //check if the object you hit is one of the "collisionObjects":
        if(col.transform.GetComponent<collisionObject>())
            GetComponent<AudioSource>().Play();
        {
            collisionObject colObj = col.transform.GetComponent<collisionObject>();
            if(!colObj) return;
            if(index == colObj.myIndexNumber) {
                if (colObj.isHighestNumber) {
                    Debug.Log ("Yay you correctly hit the last Square, You WIN!");
                    WinningText.SetActive (true);
                    NextLevelButton.SetActive (true);
                    ExitButton.SetActive (true);
                    gameObject.SetActive (false);
                    Manager.SetActive (false);
                }
                Destroy(col.gameObject);
                index++;

            }
            // here, we know it didn't match the number. :)
            else  {
                gameOverText.SetActive (true);
                restartButton.SetActive (true);
                gameObject.SetActive (false);
                Manager.SetActive (false);

            }
        }
    }
}

```

And this is my code placed in the `"square"` object:

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

        public class collisionObject : MonoBehaviour {
           public int myIndexNumber;
           public bool isHighestNumber;
           public void Start()
           {

        isHighestNumber = true;
        //find all other objects:
        foreach (collisionObject cObj in GameObject.FindObjectsOfType<collisionObject>()) {

            //check if any of the other objects has a larger number than mine, if yes, note to self that i am not the highest number.
            if (cObj.myIndexNumber > myIndexNumber) {
                isHighestNumber = false;
                break;
            }
        }
        Debug.Log("Object number " + myIndexNumber + " is here // is highest Number: " + isHighestNumber);
    }
}

```

# Answer
> 0 votes
Inherit the object on which you want to detect mouse click with EventSystems.IPointerClickHandler and move your code from `OnCollisionEnter2D` to `void OnPointerClick()`

You'll need to add `PhysicsRaycaster` component on the camera to detect mouseovers/clicks

# Answer
> 0 votes
Move the `OnMouseDown` function to the `square` objects. Inside of it, call something like `gamer.ClickedSquare(myIndexNumber);` where `gamer` is your hero (I assume). Note that you should give a reference of the `gamer` to each `square` for this to work.

Then on the `Gamer` class, convert your `OnCollisionEnter2D(...)` with `ClickedSquare(int index)` (or any other name you want to give it). This function will be called every time a square is clicked, and give it's index number, then it's up to the `gamer` object to decide if the index is the expected one, or to ignore it if it's the wrong one.

---
Tags: collision-detection, mouse
---