# Question
Title: How can I clean up excessive player-created rubble?
In my latest game I'm making, you can slice a 2D object arbitrarily, demonstrated in this gif:

You can continuously cut it into hundreds or thousands of pieces. This doesn't create a lot of lag, because they're always in a sleeping physics state, but there's a problem when you cause them to move.

I'm not really sure how to deal with making it so there's not so much rubble from cutting something apart. I don't really want to delete them after a certain amount of time; I don't like how, if you go back to something you cut up after a while, it randomly disappeared.

How can I clean up excessive player-created rubble?

# Answer
> 71 votes
First of all, that game mechanic looks like it could be super fun, so congrats on thinking of it! Here are two simple solutions that could be used independently or together to solve this particular issue:

# Remove Very Small Pieces

There isn't much of a point to keeping around tiny pieces of collision that really won't impede the player or have any real effect on the environment. Calculating the extra collision logic simply isn't worth it, so either remove these pieces or remove collision on them.

# Limit Player Cuts

Having unlimited cuts could potentially make a lot of your puzzles really simple if you can just slice every impeding object into a pile of mush. Give the player only a few cuts to play with (or make it slowly recharge over time) and you'll likely find that it makes your puzzles more challenging in addition to eliminating the pains of dealing with collision on a thousand fragments.

# Answer
> 154 votes
---

## Figure out your bottleneck

A few hundred moving objects should not be a problem. However, a few hundred colliding objects might be. It will take some testing, yet I believe the bottleneck you have are the collision.

*By the way, about how many objects are we talking? What is the platform? A hundred objects for a mobile game is not the same as a hundred for a web game or a hundred objects for a desktop game.*

Test the same game but with collisions between the cut objects disabled, and see if you get it to lag on similar amounts of objects. If that is the case, it means that the sheer amount of objects is the cause of trouble; otherwise, the collisions are the problem.

This will inform your decision on what you will do to improve performance. Not all of the ideas below will apply, and you will need testing anyway.

---

I will not talk about optimizing for a large ammount of objects far from the player, as the trouble seems to come when interacting with the objects.

> there's a problem when you cause them to move.

If the problem happens when interacting with the objects, it is unclear how removing not visible objects will solve it... yet, I'll assume it might help.

I'll just say that if objects far from the player are a problem, you could start by having smaller levels, or look into dividing the game in chunks that you can load and offload depending on where the player is going.

---

## Out of bounds

I believe that when it comes to cleaning up rubble, the first thing to have is to remove objects that are out of bounds. For example, the piece that fell to a pit. If there is no way the player should be able to get there to see it, there is no reason to keep it around.

*I will come back to this.*

---

## Make it more *realistic* (part 1)

When you cut wood with a saw, axe or similar tool, there will be lost material (to sawdust, shavings, etc). Even if you cut with a laser, the laser will burn some wood. In addition, for thing that are not wood there will usually be deformation around the cut, crumbling, etc.

What I am saying is that the cut is not perfect, and some material will be lost. You can model that in your game. That magic cutting red thingy has thickness. Remove that thickness from the objects (add particle effects if you feel too guilty).

This means that you will not be able to cut anything that is smaller than that thickness, in fact, attempting to do it will remove it from the game. That is good! It means that there is an upper bound the amount of rubble that there will be, and there is mechanically sound way to clean it up in game.

---

## Change gears for small objects

*This will work better if collisions are the problem.*

Once an object is too small, the details of the different angles it has is less relevant. You could change to a less accurate collision mechanic. For example, you could use circle colliders.

You may treat even smaller objects without collision among themselves; only consider collision between them and agent objects (such as the player’s avatar or AI controlled characters).

Finally, very small objects could just turn into dust (particle effects).

---

## Make it more *realistic* (part 2)

*This will work better if collisions are the problem.*

Material deforms and breaks under pressure. If you end up with long objects with very little thickness, break them down into smaller objects so they can take advantage of the solution above.

*We can pretend that it had too little thickness that it crumbles and breaks when you hit it.*

---

## Merge objects

*This will work better if the number of objects are the problem.*

A common trick that many games use to deal with large amounts of drop that might hurt performance is to bundle drops together.

You could try something similar for small objects that are nearby each other. Have them become a single object. However, I do not mean to stick the pieces together. I mean to create a single object to handle their physics; you can still represent the individual pieces that made up the object, perhaps using techniques akin to particle effects.

---

## Make it more *realistic* (part 3)

Have you heard of wind? There is wind in the real world.

Use wind to push small objects away.

I know it can sound counter intuitive, because it means small objects do not get to rest, at least not right away. Read below before you make your judgement.

You can *use* *wind* to push away small object before – or as soon as – they start to pile up. Which will work better if you are using optimizations for small objects (such are combining them or removing collisions among them).

Furthermore, if you can use wind to push items to pits or otherwise out of bounds, you can use as an excuse to remove the items. *I told you I was going to go back to that.* Even if you don’t, it can serve as an excuse to remove small objects that are too far away from the player, just pretend wind got rid of them while the player wasn’t looking.

*You can remove some objects while the player is not looking, you have my blessing.*

In addition to that, you now have an excuse to add wind, which you can add wind as part of other mechanics or obstacles of the game. *You could even add into the narrative the spirit of wind that tries to keep things clean, if you are so inclined.*

**Note**: You do not necessarily have to trigger wind when there is rubble to clean (although that would work), you probably can have wind happen at random intervals.

---

## Beavers!

Some annoying beaver comes along and steal your wood!

*Now you have an enemy type!*

In addition, of course, they remove wood while you were not looking. You can even design it so you return to see one beaver running away with a piece of wood where used to be a pile. That would make for a memorable moment, will explain why the wood disappeared and will solve some of the performance problems you face, all at once.

---

## It is all tradeoffs

There are limitations of the platform or the tools you have chosen, even the time and budget you have to develop the game is a limitation. You cannot make a perfect simulation of reality, *yet*. *Nobody can*.

Every developer works within the limitations that their target platform and the tools they had at the time imposed on them, and the best games had to do tradeoffs to make the game fun and engaging... even if that means less realism, in fact, often times they are fun and engaging because they are not realistic.

*Let creativity come from those limitations.*

Although, you can also make your game *more realistic*, by picking the parts of reality that are convenient for your development. Consider that sometimes removing objects that are away from the player is the part of the cost of making a fun game.

# Answer
> 1 votes
The world is discrete. You can't render an object smaller than a pixel, so don't allow such objects to exist. (This is similar to some of the realism points made by Theraot.)

Indeed, you might get this for free: the player specifies their cut line as essentially a discretized line on the screen. The effect of the cut is to divide every object into the sub-objects consisting, respectively, of the pixels on or below that line, and the pixels strictly above it. A one-pixel object can't possibly be both above and below the line, so it can't be cut by this algorithm.

If cutting all the cuttables into individual pixels would still leave you with too many objects to track, a larger minimum size might still work.

Or just don't worry about it. If the player is prepared to spend a long time cutting objects into dust, they're obviously not in a hurry so they can deal with the lag they caused. ;-)

---
Tags: unity, 2d, performance
---


# Question
Title: How to Stop Background Music When The Game is Over?
I am working on a 2D Angry Birds type Unity game. I Created Menu Scene and Level One Scene and all the required scripts are added. After adding background music to Level One, when the game is over and return to Menu I can't stop the music. The Menu scene has its own music and when the level one is over, it continues with its own music and gets mix with the menu scene music. I tried to add `Destroy()` function to level one GameObject but Level One music became silent after I restart with my menu scene. Here is my code for the attached music game object:

```
public class background_sound : MonoBehaviour {
    public static bool soundBreaker = false;

    public void Start () {
        if (!soundBreaker) {
            AudioSource myAudio = GetComponent<AudioSource> ();
            myAudio.Play ();
            DontDestroyOnLoad (myAudio);
            soundBreaker = true;
        }
    }
}

```

And here is the Menu Script:

```
public class MenuScript : MonoBehaviour {

    public void StartGame () {
        SceneManager.LoadScene ("Level One");
    }
    ...

```

Here is the code that loads the Menu Scene..

```
public void GameOver() {
    musicObject.setActive(false);
    startCoroutine(restTime());
}

IEnumerator restTime() {
    yield return new WaitForSeconds (3);
    SceneManager.LoadScene("Menu");
}

```

# Answer
Change your class to:

```
public class background_sound : MonoBehaviour {
    public static bool soundBreaker = false;

    public AudioSource audio;
    public void Start () {
        if (!soundBreaker) {
            audio = GetComponent<AudioSource> ();
            audio.Play ();

            soundBreaker = true;

            DontDestroyOnLoad(this.gameObject);
        }
    }

    public void StopPlaying(){
        audio.Stop(); // or audio.Pause();
    }

    public void StartPlaying(){
        audio.Play();
    }
}

```

In your `GameOver()` do:

```
musicObject.GetComponent<background_sound>().StopPlaying();

```

And a tip: Don't name your classes with a lowercase character and don't add `_` to it. It's a bad programming practice. Change it to `BackgroundSound` or something and rename it's file too.
> 1 votes

# Answer
Just remove the DontdestroyOnLoad
> 0 votes

---
Tags: unity, music
---


# Question
Title: Voxel traversal intersection float position
I have a 3D grid of cubes, and using the algorithm from this paper http://www.cs.yorku.ca/~amana/research/grid.pdf I've been able to get the integer coordinates of the first tile intersected by a random line.

My question is, is there any simple way to get the intersection floating point position? I've been able to get the normal, but not the position...

# Answer
> 2 votes
The algorithm you linked is known as 3D-DDA. (2D-DDA is the 2D version). When you collide with a voxel it is with either tMaxX, tMaxY, or tMaxZ since that's when the ray intersects that 3d plane. You just need to take:

```
length = tMax? / rayDirection?

```

So if you collide with the tMaxX plane then you take:

```
length = tMaxX / rayDirectionX

```

where rayDirectionX is the X component of the normalized ray direction. Length in this case is the distance along the ray until it collided. Thus:

```
intersectionPoint = rayPosition + rayDirection * length

```

Sidenote: You can take intersectionPointY and intersectionPointZ and modulus them with the voxelSize to get the offset inside of the voxel face. Useful for texture lookups. (Obviously which two axis you modulus with depends on which plane you've hit).

---
Tags: 3d, raycasting, voxels, grid, raytracing
---


# Question
Title: How To Rotate A Vector around A Pivot Point
In Unity, I'm trying to figure out how to rotate an object around a pivot point. I found a snippet of code over on the regular stack overflow, but it wasn't working even close to correctly. I have edited it a bit and now its starting to work a little better, but its still pretty off from what I need. It rotates around the object, but about half way through it jumps to another position. The one half actually rotates with the pivot point, albeit a little bit offset from where it should be, and if you keep rotating it the offset becomes greater and greater. Then the other half is just completely off, still not as bad as the original code though.

Sorry I'm having trouble explaining, here is a GIF to make it easier.

```
 public Vector3 RotTesta(Vector3 point, Vector3 pivot, Quaternion pointRotation, Quaternion pivotRotation)
        {
            //To rotate an object around an arbitrary point, translate first (the arbitrary offset) then rotate as opposed to rotate-scale - translate

            Vector3 offset = point - pivot;
            Vector3 rotationOffset = pivotRotation.eulerAngles - pointRotation.eulerAngles;
            offset = Quaternion.Euler(rotationOffset) * offset;
            return offset + pivot; // calculate rotated point
        }

```

This just handles its position, after you call this you would just do transform.rotation = pivotRotation.

If someone could please help me out with this I would be very grateful.

# Answer
There's built in functionality for this: RotateAround.

> Rotates the transform about axis passing through point in world coordinates by angle degrees.
>
> This modifies both the position and the rotation of the transform.

Basically, pick a point and an axis. Then rotate around that axis by the degrees specified. Example:

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    void Update() {
        transform.RotateAround(Vector3.zero, Vector3.up, 20 * Time.deltaTime);
    }
}

```
> 1 votes

---
Tags: unity, c#, mathematics, rotation, pivot
---


# Question
Title: Which style/technique is more time efficient for an inexperienced artists?
For a top-view 2D mobile game where you have to create and animate humanoids (human, golems) and "objects" like fire, boulders, levers, etc.

Considering the artist has no prior experience with drawing, nor with any related software.

# Answer
Using a cartoon art style with thick outlines and minimal colors. I recommend drawing in Flash using a drawing tablet. You might find it easier to draw on paper with pencil, then scan it into a computer to create the final asset in Flash. YouTube has plenty of tutorials for drawing in Flash and tons of games use this simple art style. I recommend using references like Castle Crashers and Kingdom Rush. You can make the style unique by experimenting with different line styles, proportions, gradients, and textures.
> 2 votes

---
Tags: animation, art
---


title: Custom Unity launcher localization

text:
# Question
Title: Custom Unity launcher localization
I would like to localize Unity launcher using **own** texts. At the very least I would like to change "play!", "quit", "Graphics" and "Input" to own arbitrary labels. How can I achieve that?

# Answer
It depends of your OS :

* If you are running on **OS X** you can use Interface Builder to create your own launcher interface.
* If you are on **Windows** you will have to create a special configuration so that your game launches automatically without having a launcher window. If you really want to change the buttons text and design you could also use some software like ResHacker, it is a bit tricky but I guess it should do the job.

Regardless of your OS you can modify the 'Graphics' part of your launcher as you can see in the documentation.
> 1 votes

---
Tags: unity, localization
---


# Question
Title: How do I restart tweens in DOTween and Unity?
I am trying to restart a couple of tweens when I load a new scene. So far, I have this in MainMenuController.cs :

```
void Start () {
    if (currentScene.name == "MainMenuScene") {
        Debug.Log("In current scene");
        tweenList[0] = mainMenuText.transform.DOShakePosition(5, 10)
                                   .SetAutoKill(false).SetRecyclable(true);
        tweenList[1] = playGameButton.transform.DOShakePosition(5, 10)
                                     .SetAutoKill(false).SetRecyclable(true);
        tweenList[2] = exitGameButton.transform.DOShakePosition(5, 10)
                                     .SetAutoKill(false).SetRecyclable(true);
        DOTween.RestartAll(false);
    }

}

```

However, this does not start when I reload the scene using

```
public void ExitToMainMenu() {
        SceneManager.LoadScene("MainMenuScene");
    }

```

The above is called from another script. Is there some way to restart my tweens when the scene is loaded again?

# Answer
You don't need to call these:

```
SetAutoKill(false)
SetRecyclable(true);

```

Don't mess with `DOTween's` settings unless you know what you're doing! :)

Also, don't call `Start()` from another script. `Start()` is for `Unity`, not for you :D. Make another method like `StartTweens()` and do:

```
public void StartTweens(){

    if (currentScene.name == "MainMenuScene") {
            Debug.Log("In current scene");

            foreach(Tweener tw in tweenList)
                tw.DOKill(); // or tw.Kill();

            tweenList[0] = mainMenuText.transform.DOShakePosition(5, 10);
            tweenList[1] = playGameButton.transform.DOShakePosition(5, 10);
            tweenList[2] = exitGameButton.transform.DOShakePosition(5, 10);

    }
}

```

Then call `StartTweens()` in `Start()`.
> 2 votes

---
Tags: unity, tweening
---


title: Bidirectional Path Tracing questions

text:
# Question
Title: Bidirectional Path Tracing questions
I'm coding a Bidirectional Path Tracing application for school in C++ and I have some questions (I haven't found useful explanations on the web)

1) Why does the EyePath have one more vertex?

2) When I compute the direct illumination during the EyePath creation, do I need to take account of the value of the previous vertex? I'm asking that because I saw it in some code but it seems weird.

3) I don't understand very well how to connect both paths. Randomly? Everyone with everyone? For the moment I randomly connect one vertex with another one.

4) Our PBRT book implements a contribution according to Eyepath and LightPath length. Do I need to do it, given that all the objects in my scene geometry are diffuse?

5) Are new rays randomly generated in a hemisphere at every bounce?

All objects are diffuse.

For the moment I get this result with 15 samples:

6) Do you have any idea what's going on ?

Thanks you for all of your replies :)

# Answer
> 1 votes
> 1) Why does the EyePath have one more vertex?

Compared to what ? I'm guessing you're talking about the half path starting from the eye being one vertex longer than the half path starting from the light source? If so, that is could be done because that very first ray starting from the eye is completely constrained (it must go from the camera through a particular pixel), so it isn't random. To keep the randomization & computation "balanced" between both half paths, this ray is considered additional. In general if you have several bounces, it won't matter either way.

> 2) When I compute the direct illumination during the EyePath creation, do I need to take account of the value of the previous vertex?

What value is that? if it's the direct/indirect illumination computed on that previous vertex, then no, this light flow has no business going to the next vertx *and then back up to the eye*. If however you were talking about the weighting and filtering accumulated from the eye to to thet point, then yes those transfer funtion should be carried over all the way through.

> 3) I don't understand very well how to connect both paths. Randomly? Everyone with everyone? For the moment I randomly connect one vertex with another one.

There are many strategies, but the goal is to link both half-paths with visibility path. You could chose a point randomly in your geometry and attempt to link both half-paths through that point, but then the generated points will have no guarantee of being in visibility from either half-paths, and uniformly sampling the surface of your entire geometry would be a tough task.

Rather, you should generate your links so you have at least *some* guarantee. For instance, you could generate points by sampling the hemisphere of the end of either half-paths and raycasting it into your geometry - this way the visibility to that half-path at least is guaranteed.

If you do it from both sides sequentially you may even reduce variation due to one geometry being in a more pathological configuration - don't put all your eggs in the same basket!

The ideal of course would be to chose a junction point `C` so that it is in visibility of both half-path ends everytime, that is typically impossible in non-trivial geometries.

Finally the *Everyone with everyone* strategy is not good if I understood your meaning. If you meant sample both hemispheres, project both samples into the geometry to obtain many couples and attempt to join those couples with a visibiltiy test, then you're back to square one - you've only lenghtened both paths by 1 ray.

4) Our PBRT book implements a contribution according to Eyepath and LightPath length. Do I need to do it, given that all the objects in my scene geometry are diffuse?

I don't really understand what that contribution is but I'm guesing this:

To reduce variance, the path length is left free, typically using russian roulette. Every time your path survives the roulette, its contribution is amplified (divided) by the change of surviving. Normally the length (accumulated distance is of no concern because light does not dim along a ray (it only dims in density along a widening one of light, but we're samppling rays here).

> 5) Are new rays randomly generated in a hemisphere at every bounce?
>
> All objects are diffuse.

With diffuse objects the light coming in from any direction will have the same contribution to the outgoing radiation (apart from the cosine factor, I'll come back to it) by the sheer definition of a "diffuse" surface. The stratified sampling theory tells us the optimal sampling strategy is uniform, so yeah, randomly generating rays in the hemisphere is what works best for diffuse surfaces.

That said, If we come back to my note about the cosine factor, there is a better sampling strategy, which is the cosine sampling. Instead of sampling uniformly, then dividing by the cosine factor, you could cosine-weighted sample the hemisphere, and ommit the division altogether. This would bring denser ray where the constribution will be greatest (so lower variance) and remove a division and cosine operation. This is typically done almost all the time, to the point that many people even forget to bring back the cosine division for non-diffuse surfaces!

> For the moment I get this result with 15 samples:
>
> 6) Do you have any idea what's going on ?

This looks like the first iteration of a fine-looking image. What is bothering you, exactly?

To me the graining is because you may need more samples. The only thing I find odd is that your light doesn't seem to be sampled by the direct rays from the camera (it is 'invisible' to the eye). This could mean some of your intermediate rays might also miss it, resulting in wrong lighting and artifacts.

---
Tags: rendering, raytracing
---


# Question
Title: How to use Bidirectional path tracing on sky dome for rendering indoor
Is it possible to use bidirectional path tracing to render an indoor scene where the light source is skylight(no sun) coming through a window? I think I roughly know how this is done if the light source was the window rectangle itself acting as a diffuse source but cannot get my head around on how it would work if the source is skylight and the camera is in a room: Is it the window shape that needs to be sampled or the sky dome? Would the light sample point be picked from the whole sky dome, or just a visible bit from the window?

Thanks.

# Answer
> 0 votes
There are several strategies.

* You could sample the hemisphere (according to the local material's brdf) liek any other bounce, and pray that the light escapes to the sky (if the ray extends to infinity, sample the skybox in that direction)
* You could sample the entire skydome, using its luminance as a probability distribution function
* You can (as you stated) sample the only parts of the geometry that allows a ray to escape, should you know that there are some (could be windows if you know your are indoors, but if you don't, you'll have a hard time selecting where to send your rays)

All three methods have their uses. If you know you have windows (and you know them all) then sampling the window shape and extending the ray to the skydome should be quite efficient.

If you're not always indoors or don't know what is or isn't a window, then the other two methods are much more general. Since the sky provides quite directional light, it would make sense to sample according to skydome luminance.

I'm a fan of hybrid methods, so I'd let the brdf decide: If it is very narrow/specific (like specular of glossy) then sample according to brdf. If brdf is broad (diffuse) then use window sampling if indoor, or skydome luminosity sampling when outdoors.

---
Tags: rendering, raytracing, global-illumination
---


# Question
Title: Optimal solution for storing card values in a multiplayer card game
I am developing multiplayer turn based card game(Mendikot)

in JAVA.There are four players in two teams, partners sitting opposite A standard international 52-card pack is used. The cards of each suit rank from high to low A-K-Q-J-10-9-8-7-6-5-4-3-2. Each player gets random 13 card each.

Now I have two ways to store this data,one is to store the data using data structure as below.

```
private static String[] suits = { "Hearts", "Spades", "Diamonds", "Clubs"};

private static String[] ranks = { "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King" };

```

and then store each combination of "suits and ranks" for each of the four players in a separate list and then update the list after each turn to remove played card.

Secondly I can go a database solution with table like "Players","Card","Moves" etc. where in the "Moves" tables will store cards own by each player.Which can be cleared after the game is over

I am considering this Portal as multithreaded as many players can form different rooms to play.

Please suggest me the optimal way to store the data considering the concurrent nature of the portal.

# Answer
What you are doing here is an example of stringly typing: Using strings when more specific data-types would be more appropriate.

In this case I would recommend you to use enumerations for both suits and ranks. A card should be a class with two public variables, `Rank rank` and `Suit suit`. A card doesn't change its rank or suit, so this should be an immutable class. You can do that with the `final` keyword.

```
public enum Suit {
     HEARTHS,
     SPADES,
     DIAMONDS,
     CLUBS
}

public enum Rank {
     TWO,
     THREE,
     FOUR,
     FIVE,
     SIX,
     SEVEN,
     EIGHT,
     NINE,
     TEN,
     JACK,
     QUEEN,
     KING,
     ACE
}

public class Card {
     public final Suit suit;
     public final Rank rank;

     public Card(Suit suit, Rank rank) {
          this.suit = suit;
          this.rank = rank;
     }
}

```

Why should you do this instead of just using strings? Take this code, for example:

```
player.giveCard("ACE", "SPADE");

```

There might be not one but two bugs in that tiny line of code which are undetectable by the compiler and will only appear at runtime. Can you spot them?

> It should be "SPADES", not "SPADE", and it might be the other way around, suit first, rank second.

Now take this code:

```
player.giveCard(new Card(Rank.ACE, Suit.SPADE));

```

In this case, both bugs will be caught by the java compiler. It will tell you that `Suit.SPADE` doesn't exist and that the types don't match the signature of the constructor of Card (the first parameter needs to be of type `Suit` and the second of type `Rank`).
> 1 votes

---
Tags: java, multiplayer
---


# Question
Title: How to receive shadows on animated object In optimize way?
I've been trying to add shadow to my flag that animated In my vertex shader but after adding shadow , my shadow is fixed and does not follow the animation of the flag.

for adding shadow I use below link:

> Diffuse has a fallback of vertex lit, which contains within it two passes; Shadow Caster and Shadow Receiver. These are the two passes that allow the shader to cast and receive shadows. http://polycount.com/discussion/131260/how-to-get-custom-shaders-to-recieve-shadows

my shader is here:

```
Shader "Custom/Flag" {
    Properties {
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _Speed ("Speed", Range(0, 5.0)) = 1
        _Frequency ("Frequency", Range(0, 1.3)) = 1
        _Amplitude ("Amplitude", Range(0, 5.0)) = 1
    }
    SubShader {
        Tags { "RenderType"="Opaque" "LightMode"="ForwardBase"  }
        Cull off

        Pass {

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile_fwdbase

            #include "UnityCG.cginc"
            #include "AutoLight.cginc"

            sampler2D _MainTex;
            float4 _MainTex_ST;

            struct v2f {
                float4 pos : SV_POSITION;
                float2 uv : TEXCOORD0;
                LIGHTING_COORDS(1, 2)
            };

            float _Speed;
            float _Frequency;
            float _Amplitude;

            v2f vert(appdata_base v)
            {
                v2f o;
                v.vertex.y +=  cos((v.vertex.x + _Time.y * _Speed) * _Frequency) * _Amplitude * (v.vertex.x - 5);
                o.pos = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
                TRANSFER_VERTEX_TO_FRAGMENT(o);
                return o;
            }

            fixed4 frag(v2f i) : SV_Target
            {
                return tex2D(_MainTex, i.uv);
            }

            ENDCG

        }
    }
    FallBack "VertexLit"
}

```

Finally I use `"LightMode"="ShadowCaster"` but this Tag prevents rendering my flag like this problem.A solution came to my mind that works correctly **"using two pass for implementing shadows: 1.normal pass 2.ShadowCaster pass"** but I think It's not optimize.

this is my solution as Pseudo Code:

```
   SubShader {
        Tags { "RenderType"="Opaque" }
        Cull off
        Pass {
            CGPROGRAM
            Shader "Custom/Flag" // normal Pass for animating flag
            ENDCG
        }

        Pass {
            Tags { "LightMode"="ShadowCaster" }

            CGPROGRAM
            Shader "Custom/Flag" //ShadowCaster Pass for recieving shadow
            ENDCG
        }
    }
    FallBack "VertexLit"
}

```

Flag shader.unitypackage

In short I finding a way for adding shadows for vertex animated objects In optimized way.

# Answer
> 1 votes
The 2 pass system is the only way. It's how the engine handles shadows.

Here's an example of a shadow pass from unity's manual. You'd need to modify the shadow pass' vertex shader.

```
    // shadow caster rendering pass, implemented manually
    // using macros from UnityCG.cginc
    Pass
    {
        Tags {"LightMode"="ShadowCaster"}

        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        #pragma multi_compile_shadowcaster
        #include "UnityCG.cginc"

        struct v2f {
            V2F_SHADOW_CASTER;
        };

        v2f vert(appdata_base v)
        {
            v2f o;
            TRANSFER_SHADOW_CASTER_NORMALOFFSET(o)
            return o;
        }

        float4 frag(v2f i) : SV_Target
        {
            SHADOW_CASTER_FRAGMENT(i)
        }
        ENDCG
    }

```

---
Tags: unity, shaders, shadows
---


title: Convert skew to rotation + scale

text:
# Question
Title: Convert skew to rotation + scale
I'm working on a plugin for Unity that takes data extracted from a 2D animation software and convert them to work with Unity Animator.

I'm blocked with the "skew" property. Here are the data I got in the animation software when I skew my object on Y axis.

And here is what a custom (very artistic) drawing looks like:

After few manual tests in Unity I know it's possible, with 3D rotations and 2D scale to get the same result.

However I can't understand the mathematical logic behind the input and the needed output (my knowledge in mathematics is limited). Do you know how I can convert a skew into 3d transformations (rotation + scale)?

Any help would be greatly appreciated.

# Answer
Skewing using perspective trick will be...well tricky, as it will depend of your fov etc... (maybe a bit simpler in orthographic but still, that would require more math using the projection to transform that 3D transformation into a 2D plane skew)

I would recommend trying to use a BaseMeshEffect (https://docs.unity3d.com/ScriptReference/UI.BaseMeshEffect.html) to directly skew the mesh from the UI element (skewing is then just moving the vertex Y up or down depending of its distance right or left from the center)

An example of that would be :

```
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIEffectTest : BaseMeshEffect
{
    public float skew = 1.0f;
    List<UIVertex> verts = new List<UIVertex>();
    public override void ModifyMesh(VertexHelper vh)
    {
        if (!IsActive())
            return;
        vh.GetUIVertexStream(verts);
        for(int i = 0; i < verts.Count; ++i)
        {
            UIVertex pos = verts[i];
            //just need to find the factor to match whatever your animator set in skew
            pos.position.y += pos.position.x * skew;
            verts[i] = pos;
        }
        vh.Clear();
        vh.AddUIVertexTriangleStream(verts);
    }
}

```

Put that on a gameobject with a UI element and it will change the mesh generated. This is the class used by the Outline/shadow effect (you can see it use din the UI bitbucket, here : https://bitbucket.org/Unity-Technologies/ui/src/0155c39e05ca5d7dcc97d9974256ef83bc122586/UnityEngine.UI/UI/Core/VertexModifiers/Shadow.cs?at=5.2&fileviewer=file-view-default)

Of course, this can be costly as it regenerate the vertex buffer each time the ui element is dirtied, but as usual profile and find what is worth optimizing if there is problems!
> 1 votes

---
Tags: unity, mathematics, transformation
---


# Question
Title: Editor Window Show method is not working properly
Documentation says that `EditorWindow.Show` show the EditorWindow.

I have two classes:

```
public class WindowOne : EditorWindow {

    public static WindowOne windowOneInstance;

    [MenuItem("Window/Open Window One")]
    public static void Init() {
        windowOneInstance = GetWindow<WindowOne>(false, "Window One", true);
    }
}

```

and

```
public class WindowTwo : EditorWindow {

    public static WindowTwo windowTwoInstance;
    public static WindowOne windowOneInstance;

    [MenuItem("Window/Open Window Two")]
    public static void Init() {
        windowTwoInstance = GetWindow<WindowTwo>(false, "Window Two", true);
        windowOneInstance = WindowOne.windowOneInstance;
    }

    public void OnGUI() {
        if (GUI.Button(new Rect(0, 0, 200, 50), new GUIContent("show window one"))) {
            windowOneInstance.Show();
        }
    }
}

```

In menu I click `Open Window One`, then `Open Window Two`, then I close the first window

Now if I click a `Button` on `WindowTwo` it doesn't show me `WindowOne`. Or at least it shows one-pixel of window that I cannot move or resize or do something else.

If I use `GetWindow(typeof (WindowOne));` instead of `.Show()` \- it shows the window, but I'm not sure that it shows the same instance I created before, because `instanceID` of that window will be different.

---

Why `Show` method works so strange? Am I doing something wrong? And what should I do to show the same instance of closed (temporarily hidden) window?

*Unity* version - 5.6.0p4

# Answer
> 2 votes
See here:

> OnDestroy is called when the EditorWindow is closed.

It seems like Unity destroys the instance of the editor window when you close it.

After the instance is destroyed, when you call the `Show()` method, it fails to find the instance so it probably falls down to a default window, which is what you are referring to as *one-pixel of window*.

But as you can see here in the documentation of `GetWindow()` method:

> Returns the first EditorWindow of type t which is currently on the screen.
>
> **If there is none, creates and shows new window and returns the instance of it.**

`GetWindow()` method creates a new instance for you if there is no instance available. So you are getting a fresh instance when you call `GetWindow()` after closing the existing instance.

---

About your concerns on the windows being the same instance:

If your purpose is the persistence of data between editor windows, you can achieve so using serialization or a data holder class.

---

**Edit:**

After some research, I have come to the conclusion that there is no way to "hide" an editor window rather than "closing" it.

There is no way to prevent an editor window from receiving input, so somehow making it invisible and allowing input to go through is not possible either.

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


title: player 2d rotation

text:
# Question
Title: player 2d rotation
Hello i have one problem with my 2d game a made 2d endles racing game and i add cars spawner with prefab and on this scripts i add and coin whith box collider 2d and make trigger and when i play the game when i take the coin my car is rotation on z where is my problem here my code.

```
using UnityEngine;
using System.Collections;

public class carSpawner : MonoBehaviour {

 public GameObject[] cars;
 int carNo;
 public float maxPos = 1.7f;
 public float delayTimer;
 float timer;

 // Use this for initialization
 void Start () {

  timer = delayTimer;

 }

 // Update is called once per frame
 void Update () {

  timer -= Time.deltaTime;
  if (timer <= 0) {

   Vector3 carPos = new Vector3 (Random.Range (-1.7f, 1.7f), transform.position.y, transform.position.z);
   carNo = Random.Range (0, 10);
   Instantiate (cars[carNo], carPos, transform.rotation);
   timer = delayTimer;

  }

 }
}
```

```
void OnCollisionEnter2D(Collision2D col) {
        if (col.gameObject.tag == "coin")
        {
            col.gameObject.SetActive(false);
        }
    }
```

# Answer
> 0 votes
I can't really understand your problem, that being said, the Z rotation looks really minimum, it probably has something to do with the car controller script. If you don't want to rotate on the Z axis at all, just mark this inside your car's rigidbody.

---
Tags: unity, 2d, rotation
---


# Question
Title: Player prefs is not saving data with error Namespaces cannot be used as expressions.?
code:

```
var score:GameObject;
function OnCollisionEnter(){

PlayerPrefs.SetFloat("Score",score.GetComponent(Events).i);

}

```

*Events* is the script I assigned to gameObject *score* which contain the float variable *i*.

I am trying to access this var from another function.

But it give an error as-

```
'Events' is a namespace. Namespaces cannot be used as expressions.

```

when I give quotation mark in *Events* it does not give any error initially But when *OnCollisionEnter* is called it gives an error as-

```
Object reference not set to an instance of an object

```

# Answer
> 0 votes
As you can see here, the namespace Events is already defined in Unity, change your script's name from Events to something else.

https://docs.unity3d.com/462/Documentation/ScriptReference/Events.UnityEvent.html

The UnityEngine has a Events namespace.

---
Tags: unity, unityscript
---


title: Extensible RNG system

text:
# Question
Title: Extensible RNG system
My question is pretty general. What is the simplest way to code an RNG system or algorithm that easily accommodates additions and changes? For example, let's say I have an RNG system that will spawn an item based on the random value that is rolled. Then I guess some basic, slapped-together solution could look like

```
if (randomNumber > 0 && randomNumber <= 0.2)
{
    // spawn something
}

if (randomNumber > 0.2 && randomNumber <= 0.4)
{
    // spawn some other thing
}

```

or for the chance to spawn multiple items, maybe

```
if (randomNumber < 0.4)
{
    // spawn something
}

if (randomNumber < 0.2)
{
    // spawn some other thing
}

```

Now, let's say I add lots and lots of possible items that can spawn in the game. It would be a hassle to go back and modify all these values while maintaining their relative rarities, etc. How do I make a more flexible RNG system?

# Answer
You can use an algorithm which I call *Distributed Probability RNG*.

It looks like this:

```
public class Item {}

public class ExampleBucket
{
    private List<Item> bucket = new List<Item>();

    public void Add (Item item, int count)
    {
        for (int i = 0; i < count; i++)
        {
            bucket.Add(item);
        }
    }

    public Item GetRandom (Random rng)
    {
        var index = rng.Next(0, bucket.Count);

        return bucket[index];
    }
}

```

You can initialize like this:

```
private void InitBucket()
{
    var itemA = new Item();
    var itemB = new Item();
    var itemC = new Item();

    var bucket = new ExampleBucket();

    bucket.Add(itemA, 1);
    bucket.Add(itemB, 2);
    bucket.Add(itemC, 3);
}

```

You can get items by calling `GetRandom(Random)` on your `ExampleBucket` instance.

---

**How does it work?**

We have a list named `bucket` in `ExampleBucket` class. First off it is empty. By calling `Add(Item, int)` method, you add a specific amount of `Item`s to the `bucket` list.

At the end of our `InitBucket()` method, the `bucket` list will look like this:

```
itemA // 1 x itemA
itemB // 2 x itemB
itemB
itemC // 3 x itemC
itemC
itemC

```

Then we simply generate a random number between `0` and `bucket.Count`, and return the item that corresponds to that index in the `bucket` list.

The probability of getting a specific item from a list is `Item Count / Total Count`. The more items you have of a specific type in the list, the more chance that item gets selected.

So in this case;

```
Probability of getting itemA = 1 / (1+2+3)
Probability of getting itemB = 2 / (1+2+3)
Probability of getting itemC = 3 / (1+2+3)

```

When you run `GetRandom()` for 100000 times (the test is here in Fiddle) you can see the values are pretty close to perfect results:

```
A count = 16690 | Expected = 16666
B count = 33519 | Expected = 33333
C count = 49791 | Expected = 50000

```

---

What I like most in this algorithm is, you don't need to specify a total item count. You can just add any item at any time you want and don't worry about the rest.

For example, if you want to increase the chance of getting `itemA` from the list, you can simply call

```
bucket.Add (itemA, theAmountYouWant);

```

and you don't need to do anything else.
> 7 votes

# Answer
# Weighted Randoms

Rather than stuffing more *copies* of an item into a list, we can do this instead:

```
private class WeightedItem {
    public readonly int weight;
    public readonly Item drop;
    //constructor omitted
}

```

We then shove *these* into a list:

```
private List<WeightedItem> bucket = new List<WeightedItem>();
private totalWeight = 0;
public void Add (Item item, int count) {
    if(count <= 0) throw new Exception("Invalid random weight");
    bucket.Add(new WeightedItem(item, count));
    totalWeight += count;
}

```

And then we get our result like this:

```
public Item GetRandom (Random rng) {
    int randomVal = rng.Next(0, totalWeight);
    foreach(WeightedItem item in bucket) {
        randomVal -= item.weight;
        if(randomVal <= 0) {
            return item.drop;
        }
    }
}

```

This method is more flexible than just shoving items into a list because we can make the wrapper class responsible for turning the Item into an ItemStack and applying extra data (such as the stack size, or NBT data--if we think of Items in the Minecraft sense where `Item` is the prototypical definition and `ItemStack` is what actually shows up in the player's inventory: size and NBT data are just extra bits of data on top of the prototypical definition that tell us about *this* grouping specifically; what your project actually has and how it's represented is up to you).

What this means is that we can have multiple random genereators each with their own collection of weighted lists and any given entry in that list (say, Apples) can generate a *unique quantity* depending on which generator they're in. Eg. a wrapper like this:

```
public class RandomSizeStackDrop extends WeightedItem {
    public readonly int weight;
    public readonly Item drop;
    public WeightedItem(Item i, int w) {
        drop = i;
        weight = w;
    }

    public ItemStack GetStackFromDrop() {
        //Creates a stack with a size from 1 to 5
        return new ItemStack(drop, Random.Next(1,5));
    }
}

```

And rather than returning `Item` in the GetRandom() method, we're instead returning `item.GetStackFromDrop()`

So we could have a bucket for items being generated in a chest near a farm and have stacks of 1 to 5 apples show up, but in another chest, down in a mineshaft say, only generates 1 apple any time an apple shows up. Even if the probability for both is the same, the chest near the farm will generate *more total apples* as a result.
> 9 votes

# Answer
Most of your conditions are useless which makes your code longer for nothing. This is the bread and butter way of doing things.

```
if (randomNumber <= 0.2)
{
    // 20% chance
}else if (randomNumber <= 0.4)
{
    // 20% chance
}else{
    // 60% chance
}

```

If you want to make it even more convenient, you could try with weighting.

Let's assume you have a data structure that takes an `Action`. Here's some pseudo-code.

```
WeightedRandomizer wr = new WeightedRandomizer();

wr.addAction(Action.MOVE, 1); // 1 in 7 chances of happening
wr.addAction(Action.JUMP, 2); // 2 in 7 chances of happening
wr.addAction(Action.FLY, 4); // 4 in 7 chances of happening

Action action = wr.getAction();

```

You have a bit less control on the exact %, but it is definitely a much cleaner approach.
> 2 votes

---
Tags: unity
---


# Question
Title: How to prevent creation of game object clones
Within the script of one game object I am initializing another game object with a prefab. To make development easier (so I don't have to run the game for every change) I call the function in `OnValidate()`. Anytime I select the `hasWindow` bool a Window clone is created. So in situations that I select then deselect (doesn't go away) and reselect, two clones are created. I don't even have a window game object in my hierarchy, so I don't get why any clone is created. I want the window to appear when I select `hasWindow` and disappear (not hide) when I deselect within the inspector. How can I do this? The relevant code follows:

```
public bool hasWindow;

void OnValidate ()  {
    prepareWindow();
}

void prepareWindow  ()  {
    if (hasWindow) {
        window = (GameObject)Instantiate(Resources.Load("Prefabs/OtherPrefabs/Window"));
    }

}

```

# Answer
> 0 votes
You need to destroy the previous instantiated window, i'm assuming you run this in EditMode? That's why we need to use DestroyImmediate. Also, the (clone) thing, it's just a naming convention, every instantiated object has it. You can change it,

```
window.name = "Window";

```

---

```
void prepareWindow  ()  {
    if (hasWindow) {
        window = (GameObject)Instantiate(Resources.Load("Prefabs/OtherPrefabs/Window"));
    }
    else if (window != null)
        UnityEditor.EditorApplication.delayCall += () =>
        {
            DestroyImmediate(window);
        };
}

```

---

Edit: I would personally activate and deactivate the window, but it's up to you.

Edit2: When using the OnValidate callback, it looks like you can't Destroy components right away, but i found this solution with delayCall.

# Answer
> 1 votes
How about only creating the window if it doesn't already exist?

```
void prepareWindow  ()  {
    if (hasWindow && window == null) {
        window = (GameObject)Instantiate(Resources.Load("Prefabs/OtherPrefabs/Window"));
    }
}

```

---
Tags: unity
---


# Question
Title: Video recording and editing for game promo video
I would like to screen record a beta of an RPG I've created. The format will be narration over video with the ability to edit. It's an indie game I'm marketing, so the video quality and narration need to be semi-professional.

I'm curious as to which video production packages are of good enough quality to accomplish this without breaking the bank (free is the best!). If there are no good packages, then separate software recommendations for screen recording, editing, and narration would be helpful!

Notes:

* I have a Mac
* I would rather do video recording first, then narration later with an overlay
* I've used Quicktime in the past, not sure if there was something better
* This video is for my Kickstarter campaign

# Answer
> 1 votes
Here's how I go through the process:

1) Record footage via Open Broadcast Software (OBS). It's free, works pretty well, is very customizable and is supported on Mac (although, never used it on Mac so don't know how different it is). I personally prefer it over Xtreme Broadcaster.

2) Edit footage in Adobe Premiere + Adobe After Effects. The combination is super effective and can get you anywhere as long as you can imagine what you want. Both work great on Mac. The drawback is that it isn't free (about $20/mo for student version) and the learning curve can be intimidating.

3) Audacity is what I use for voice recording. It's simple and supports most of the features you can think of. It should also be available on Mac.

---
Tags: marketing, video, game-recording, screen-recording
---


# Question
Title: Steering Behavior Pursuit quick question
In the code below, you will see Heading(). Is that just a position that is normalized? If not, then what is the heading?

```
Vector2D SteeringBehavior::Pursuit(const Vehicle* evader)

    {

      //if the evader is ahead and facing the agent then we can just seek

      //for the evader's current position.

      Vector2D ToEvader = evader->Pos() - m_pVehicle->Pos();

      double RelativeHeading = m_pVehicle->Heading().Dot(evader->Heading());

      if ( (ToEvader.Dot(m_pVehicle->Heading()) > 0) &&

           (RelativeHeading < -0.95))  //acos(0.95)=18 degs

      {

        return Seek(evader->Pos());

      }

      //Not considered ahead so we predict where the evader will be.

      //the lookahead time is propotional to the distance between the evader

      //and the pursuer; and is inversely proportional to the sum of the

      //agent's velocities

      double LookAheadTime = ToEvader.Length() /

                            (m_pVehicle->MaxSpeed() + evader->Speed());

      //now seek to the predicted future position of the evader

      return Seek(evader->Pos() + evader->Velocity() * LookAheadTime);

    }

```

# Answer
> Is that just a position that is normalized?

Heading most likely implies a direction( which im certain of in this piece of code). But it's not a position but a Vector. Vectors don't have position. They describe direction and magnitude ( = length).

You can definitely define vectors from positions. The difference between two points is a vector with length and magnitude. A vector from a single point would look like a line from origin 0 to the point. Eventhough we can store a point in a vector, don't see vectors themselves as having a position. They describe direction and magnitude.

Edit:

To copy what I said in the comment

You can see that they are using the dot product. Heading is a normalized vector. Meaning that it's a direction. if you place a normalized vector into a unit circle you can see that the x and y components give you cos and sin. You can get the angle with atan2 even if it's not normalized. Point being that vectors and angles go hand in hand.

```
if(ToEvader.Dot(m_pVehicle->Heading()) > 0)

```

This neat trick here is using the sign of the dot product to determine if something is in front or behind the heading

like in the code the dot of 2 vectors give you a scalar ( a single number rather than a vector ) with which you can also tell an objects orientation without working with actual angles.
> 0 votes

---
Tags: steering-behaviors
---


# Question
Title: How to find and send data about on-screen players to a client in a real-time multiplayer game?
I'm surprised I couldn't find much information on this.

I am making a top-down browser game in which the players see a small section around their player (see the image). Since the player doesn't need to render the players far away that they can't see, it would be unnecessary to send data about them. I want to know how the server should calculate who is near enough to the client that they appear on their screen and therefore receive data from the server about those players.

The way my problem differs from what I have found is that I need to track many players (at least 50 and preferably up to 100) and many can be on screen at one time (assume a maximum of 10 on screen at any one time).

Some assumptions/considerations that are made:

* The players are always moving and positions constantly changing
* Must handle at least 50 players at one time (preferably up to 100)
* Players can drop in and out at random locations so should be able to adapt to this quickly
* Screen sizes vary
* Player input is just movement (but there should be scope for other simple actions)
* Data sent over TCP as will be browser based
* Node.js server

Initially I thought about sending data for all the positions of the players to each player but this seems like a terrible idea with so much unnecessary data being sent - from what I understand the server should be sending as little as possible.

My current strategy (shown in the image) is to have the server periodically (every second for example) calculate the distances between all players to determine those near enough to each other to appear on screen. For the next second, data will only be sent to the client regarding those near it. After the next second, new distances are calculated to decide what to send (and render) for each player.

Some problems to take into account:

* A lot of calculations must be performed by the server for all the players
* Extra information would need to be sent about players just outside the screen to account for any movement between updates
* Interpolation would probably be required
* Different screen sizes will mean that some players can see more than others (the fairness isn't the issue here, but tracking to what distance to let players see)

The main issue is the ability of the server to process all of this with everything else that it must already do. I am not convinced this is a very good way.

This is trivial for off screen entities in a single player game, however for multiplayer games with many players moving at once this becomes much more difficult.

How can I figure out what players are on screen efficiently and what data should be sent regarding this? Or please point me to where I can find information on this.

# Answer
If you divide the game's map into different chunks then you can map each player's position into a separate data structure for each chunk where every other player a given chunk is visible to every other player within that chunk respectively.

The rest is really up to you (what the size of a chunk is), and in essence each player in a "chunk" or subsection gets the same data so you don't have to re-compute it every tick or so. This makes for constant time lookup and is nice since you don't have to do any distance calculations to check which players are visible for every other player since the size of a chunk will demarcate the region of visibility. This approach is basically quadtrees and games like Minecraft use this approach.

If an entity X moves from position A to position B then you find the chunk where position A was, remove entity X from that chunk and place entity X in the chunk where position B is. This move operation is **O(n)** in the size of the chunk, but you can probably make it constant time with a hashmap or something clever. The cost of this approach is the space allocated for the quad tree. Finding a chunk is constant time, though.

Also, you may not want to send n(n-1) packets each frame for n players regarding every other player's n positions necessarily if you're concerned about performance too much. The best approach may be to fit all of this data each tick into one giant packet containing the positions of every other player within the same chunk as the player you're sending position data to, so there are as few `send()` calls as possible (then again, this may not be a huge performance hit either in practice depending on the game). The size of one packet in this case is upper bounded by the `num of players in a chunk * size of player packet`.

In the worst case there could be 100 players in one chunk in your case, but it's up to you how you divide the map. The smaller the packet the better, and a packet can be up to 1500-65,000 bytes in size so you shouldn't have a problem unless you're dealing with thousands of players/poor network speeds. This is completely dependent on how much data is represented for each player, and how many players there are.

**EDIT:** But yeah, I wouldn't be concerned at all with sending data for players that aren't visible at all using this approach. It's very practical to send all of surrounding chunks in a game if they have the potential to be visible depending on the size of a chunk compared to your screen's size.
> 0 votes

---
Tags: javascript, multiplayer, client-server, node.js, realtime
---


title: Perlin Noise unwanted artifacts

text:
# Question
Title: Perlin Noise unwanted artifacts
I am trying to write a perlin noise class with c++ and sfml, but I am experiencing unwanted visual artifacts in the output. In the image, there are obvious lines being drawn between the points of the lattice:

---

The class template representing the noise is a specialization of lattice noise for vectors. The important function, GetValue() expects values between 0.0-1.0, representing the coordinates at which to get the value of the noise, which should also return a value between 0.0-1.0. Calling the function at (0, 0) should return the value at the top left corner. NormX and normY are the distance between lattice points x0-x1 and y0-y1, again in the range 0.0-1.0.

Before calculating the dot product, the distance vector from each corner lattice point is calculated instead of only using the distance from the top left corner. Because the final value at any point may be negative (-1.0 - 1.0), it is mapped to the range 0.0-1.0 by adding 1 and dividing by two before being returned.

```
template<>
inline float LatticeNoise2D<sf::Vector2f>::GetValue(float u, float v)
{
    float normX = u * resX_;
    int x0 = normX;
    int x1 = x0 + 1;
    normX -= x0;

    float normY = v * resY_;
    int y0 = normY;
    int y1 = y0 + 1;
    normY -= y0;

    float fadeX = Fade(normX);
    float fadeY = Fade(normY);

    sf::Vector2f dist(normX, normY);
    float dot0 = Dot(At(x0, y0), dist);
    dist = sf::Vector2f(1 - normX, normY);
    float dot1 = Dot(At(x1, y0), dist);
    float lerp0 = Lerp(dot0, dot1, fadeX);

    dist = sf::Vector2f(normX, 1 - normY);
    dot0 = Dot(At(x0, y1), dist);
    dist = sf::Vector2f(1 - normX, 1 - normY);
    dot1 = Dot(At(x1, y1), dist);
    float lerp1 = Lerp(dot0, dot1, fadeX);

    float value = Lerp(lerp0, lerp1, fadeY);
    return (value + 1) / 2;
}

```

The At(x, y) function returns the pre-generated vector on the lattice (a 2d std::vector) at the given index. The dimensions of the lattice in each dimension are resX\_ and resY\_, respectivley.

```
template<typename value_type>
inline value_type LatticeNoise2D<value_type>::At(int x, int y)
{
    return lattice_[x % resX_][y % resY_];
}

```

The vectors at each point on the lattice are generated on the unit circle by randomly choosing an angle in radians (0-2pi) and then calculating the x & Y components given that the length of their hypotenuse is 1.0.

```
template<>
inline sf::Vector2f LatticeNoise2D<sf::Vector2f>::Random()
{
    float pi = 4 * atan(1);
    float theta = static_cast<float>(rand()) / RAND_MAX * 2 * pi;
    return sf::Vector2f(cos(theta), sin(theta));
}

```

The Lerp() function performs linear interpolation, and the Dot() function calculates the dot product of two vectors. The Fade(t) function maps a value from 0.0-0.1 to an S Curve to be used in the Lerp function instead of just the linear distance between lattice points.

---

Why am I getting these lines between the points of the lattice, and how can I fix them? My goal is to make noise like this example:

# Answer
> 6 votes
I don't entirely understand why, but I shouldn't have been doing 1-normX/Y. Instead, I looked at the question posted here and our approaches were similar enough that I could make It work. Changing from 1-x to x-1 seemed to do the trick.

---
Tags: c++, sfml, perlin-noise, noise
---


# Question
Title: OpenGL - Changing blending modes using sprite batching
I'm working on a game which uses sprite batching to render sprites efficiently where each sprite gets batched with its VBO data into a VAO every frame (containing vertex coordinates, texture data and color data). So far so good. I'm sorting them on the CPU and ordering the batch before each draw call according to render order to simulate z-ordering.

However, there's one problem: what do I do when I want to draw particles, for instance, which require a blending mode change? All of the sprites are drawn using `glDrawArrays` use the same blending mode, but for my particle data I want to change the blending mode. If I put the particles in the same batch then I won't have the ability to change it necessarily. My goal is to switch from normal blending (GL\_SRC\_ALPHA, GL\_ONE\_MINUS\_SRC\_ALPHA) to additive blending (GL\_SRC\_ALPHA, GL\_ONE).

**1st solution:** use a separate draw call for every sprite and don't batch them at all. then for each call I can change the mode appropriately

**2nd solution:** add a z-coordinate to each sprite to do z-ordering automatically on the GPU using depth testing (this means I can render particles separately in their respective batches with ~2 calls -\> +1 for sprites & +1 for particles) which will allow me to change blending modes.

Is there another way of approaching this problem? What am I missing?

# Answer
**Background**

OpenGL blend funcs are just a means of specifying a mathematical formula as follows:

* `src`: the output from your fragment shader.
* `dst`: the colour in the framebuffer.
* `sfactor`: multiply `src` by this.
* `dfactor`: multiply `dst` by this.
* And add the two results together.

(As a simplifying assumption I'm ignoring blend equation, blend func separate and multiple render targets, and also assuming that you don't care about destination alpha).

So if we look at your two blend funcs we see that they work out as follows:

```
glBlendFunc (GL_SRC_ALPHA, GL_ONE)                  =  src * src.a + dst * 1
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)  =  src * src.a + dst * (1 - src.a)

```

The objective is to find a way to use a single blend func for everything.

---

I'm going to assume, for the purposes of this answer, that your fragment shader writes it's output to `gl_FragColor`. If it doesn't, just replace any references to `gl_FragColor` in the remainder of this answer with whatever you do write to.

---

Let's repeat the two blend funcs again:

```
src * src.a + dst * 1
src * src.a + dst * (1 - src.a)

```

The only difference between the two is the value used for `dfactor`, and it's `(1 - src.a)` in the latter, so if we can modify our fragment shader to output 0 for `src.a` in the former case, then the two blend funcs become the same (because 1 - 0 = 1).

However, we see that `src.a` is also used as `sfactor` in both, so we can't modify `src.a` without also affecting that.

Let's see if we can find a way of modifying the fragment shader to remove that restriction. Since we don't care about destination alpha we can just do this:

```
gl_FragColor.rgb *= gl_FragColor.a;

```

After having done that, the two blend funcs become:

```
glBlendFunc (GL_ONE, GL_ONE)
glBlendFunc (GL_ONE, GL_ONE_MINUS_SRC_ALPHA)

```

Or:

```
src * 1 + dst * 1
src * 1 + dst * (1 - src.a)

```

So the only remaining thing is to find a means of setting `src.a` to 0 in the former case; something like this in your fragment shader:

```
gl_FragColor.rgb *= gl_FragColor.a;
if (altBlend) gl_FragColor.a = 0;

```

So we want `altBlend` to evaluate to `true` in cases where you use `GL_ONE, GL_ONE` blending, or `false` in cases where you use `GL_ONE, GL_ONE_MINUS_SRC_ALPHA` blending, and we have the result; we can now use a single blend func for all drawing:

```
glBlendFunc (GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

```

Or:

```
src * 1 + dst * (1 - src.a)

```

And in cases where `src.a` is 0 this is exactly equivalent to:

```
src * 1 + dst * (1 - 0)

```

Or:

```
src * 1 + dst * 1

```

Or:

```
glBlendFunc (GL_ONE, GL_ONE);

```

---

So all that's remaining is how to set the value of `altBlend`, and how you do that is entirely up to you. You could set an additional vertex attrib that you pass along to your fragment shader, you could bind an additional texture and sample from it for the different types of objects, or you could do something entirely different; it all depends on which is most appropriate for the rest of your code.
> 3 votes

# Answer
For anyone interested, my solution was to just change blending modes in my sprite batcher by keeping track of the indices where blending modes change and then call glDrawArrays as many times as I need whenever the blending mode changed. They're still batched, but the chunks are as small as the gaps between blending modes.
> 0 votes

---
Tags: opengl, particles, blending, batching
---


title: Android Playback Engine in Unity

text:
# Question
Title: Android Playback Engine in Unity
Should I install Android Playback Engine in Unity if I am going to make games for Android? What the Android Playback Engine is used for?

I got the question when decided to reinstall Unity and met it:

I tried to figure out what it is used for on my own, but found almost nothing. It seems that I am a bad seeker. I found just this:

**Movie playback**

Movie textures are not supported on Android, but full-screen streaming playback is provided via scripting functions.

Is it just about showing you the game backwards? (з

# Answer
> 2 votes
`Android Build support` is self-explanatory. If you want to build games for Android, you **must** select `Android Build support`.

To play video on Android (and iOS), MovieTextures are not supported natively. You have to use either a plugin on the asset store or the `Handheld.PlayFullScreenMovie` function : https://docs.unity3d.com/ScriptReference/Handheld.PlayFullScreenMovie.html

---
Tags: unity, android
---


# Question
Title: Third-person spaceship camera follows object, but rotation becomes strange after moving object
This code should follow the game Object in every step, but it does not. In the beginning we can rotate the object wherever we want and it works, but after moving it some the camera starts doing weird moves. I don't understand it because the camera position should always be along the line of `object position + target`

```
GameObject::GameObject()
{
    type = 1;
    speed = 1.0f;
    position = { 0,0,0 };
    direction = {-1,0,0};
    up = { 0,1,0 };
    D3DXMatrixIdentity(&rotation);
    graphic_model = NULL;

}

GameObject::GameObject(LPDIRECT3DDEVICE9 dev, Model *gModel, D3DXVECTOR3 p , D3DXVECTOR3 d,float s,float t)
{
    type = t;
    speed = s;
    position = p;
    direction = d;
    up = { 0,1,0 };
    D3DXMatrixIdentity(&rotation);
    D3DXMatrixIdentity(&scalem);

    graphic_model = gModel;

}

void GameObject::createMatrix()
{
    D3DXMATRIX translation;
    D3DXMatrixIdentity(&translation);

    D3DXMatrixTranslation(&translation, position.x, position.y, position.z);
    model = (scalem*rotation*translation);
    //D3DXMatrixMultiply(&model, &rotation, &translation);
}
void GameObject::translate(float x, float y, float z)
{
    position.x = x;
    position.y = y;
    position.z = z;

}

void GameObject::scale(float sx,float sy, float sz)
{
    D3DXMATRIX sca;
    D3DXMatrixScaling(&sca, sx, sy, sz);
    scalem *= sca;
}
void GameObject::move() {
    D3DXVECTOR3 f;
    D3DXVec3Normalize(&f, &direction);
    position += (f*0.05);

}

D3DXMATRIX GameObject::getModelTransform()
{
    createMatrix();
    return model;
}

int GameObject::redirect(D3DXVECTOR3 target) {
    D3DXVECTOR3 P1, P2, L, T, tempV, axisOfRotation;
    float angle;
    P1 = position; //The D3DXVECTOR3 location of the object
    P2 = target; //The D3DXVECTOR3 location of the target

                    //Calculate the normalized vector from the object to the target
    D3DXVec3Normalize(&L, &direction);
    D3DXVec3Subtract(&tempV, &P2, &P1);
    D3DXVec3Normalize(&T, &tempV);

    //Take the cross product of T and L to compute the axis rotation
    D3DXVec3Cross(&axisOfRotation, &L, &T);
    if(D3DXVec3Length(&tempV)<0.5)
        return 0;
    float d = D3DXVec3Dot(&L, &T);
    if (d > 1)
        d = 1;
    if (d < -1)
        d = -1;
    //Calculate the angle of rotation
    angle = acosf(d);

    //Now create the rotation matrix
    D3DXMATRIX matRotate;
    D3DXMatrixRotationAxis(&matRotate, &axisOfRotation, angle*0.1f);

    D3DXVec3TransformNormal(&direction, &direction, &matRotate);
    D3DXVec3TransformNormal(&up, &up, &matRotate);
    //direction = direction - position;

    D3DXVec3Normalize(&direction, &direction);
    D3DXVec3Normalize(&up, &up);

    rotation *= matRotate;
    return 1;

}

InputHandler::InputHandler()
{
}

void InputHandler::handleInput(Player *p, ThirdPersonCamera *camera)
{
    /*if (isPressed(BUTTON_X)) buttonX_->execute();
    else if (isPressed(BUTTON_Y)) buttonY_->execute();
    else if (isPressed(BUTTON_A)) buttonA_->execute();
    else if (isPressed(BUTTON_B)) buttonB_->execute();*/

    DIJOYSTATE2 state;
    Keyboard.poll(&state);
    Mouse.poll(&state);

    xoffset = state.lX * sensetivity;
    yoffset = state.lY * sensetivity;

    camera->adjustCamera(p, xoffset, yoffset, state.lZ);
    p->redirect(camera->getTLAT());
    lastMouseX = state.lX;
    lastMouseY = state.lY;

    //W is pressed
    if (state.rgbButtons[0] & 0x80)
    {

        p->move();
        //camera->kamera_fahrt(xoffset, yoffset, p->getSpeed(), state.lZ);
    }
    //S is pressed
    if (state.rgbButtons[1] & 0x80)
    {

    }
    //A is pressed
    if (state.rgbButtons[2] & 0x80)
    {

    }
    // D is pressed
    if (state.rgbButtons[3] & 0x80)
    {

    }

    //p->reachTarget(camera->getTarget());

}

ThirdPersonCamera::ThirdPersonCamera(GameObject * o, int Screen_Height, int Screen_Width,float clip, float min, float max)
{
    this->min = -min;
    this->max = -max;

    here_is_up = { 0,1,0 };
    there_i_look_at = o->getDirection();
    target = there_i_look_at;
    here_i_am = o->getPosition() + this->min * (there_i_look_at);
    here_i_am.y = 0;

    D3DXVec3Normalize(&target, &target);

    D3DXMatrixPerspectiveFovLH(&projection, D3DX_PI / 2, Screen_Width / Screen_Height, 0.1f, clip);
    CreateViewMatrix();
}

void ThirdPersonCamera::adjustCamera(GameObject * o,float mouseX,float mouseY,float scroll)
{
    scroll = clampScroll(scroll);
    here_is_up = o->getUp();
    kamera_schwenken(mouseX, mouseY);
    there_i_look_at = o->getPosition() + target;
    here_i_am = o->getPosition() + scroll * target;
    CreateViewMatrix();

}

void ThirdPersonCamera::CreateViewMatrix()
{
    D3DXMatrixLookAtLH(&view, &here_i_am, &target, &here_is_up);
}

ThirdPersonCamera::~ThirdPersonCamera()
{
}

float ThirdPersonCamera::clampScroll(float s)
{
    if (s > min)
        return min;
    if (s < max)
        return max;
    return -s;
}

void ThirdPersonCamera::kamera_schwenken(float seite, float hoch)
{
    D3DXVECTOR3 norm, blick;
    D3DXMATRIX rotation;

    /*if (target.x*target.x + target.z*target.z < 0.005)
    {
    if (((target.y > 0) && (hoch > 0)) || ((target.y < 0) && (hoch < 0)))
    {
    hoch = 0;
    }
    }*/

    D3DXVec3Cross(&norm, &target, &here_is_up);

    D3DXMatrixRotationAxis(&rotation, &norm, hoch);

    D3DXVec3TransformNormal(&target, &target, &rotation);

    D3DXMatrixRotationAxis(&rotation, &here_is_up, seite);

    D3DXVec3TransformNormal(&target, &target, &rotation);

    D3DXVec3Normalize(&target, &target);

}
void ThirdPersonCamera::kamera_bewegen(float seit, float hoch, float vor)
{
    D3DXVECTOR3 v, s, h, t;
    v = there_i_look_at - here_i_am;
    v.y = 0.0f;
    D3DXVec3Normalize(&v, &v);
    s = D3DXVECTOR3(-v.z, 0, v.x);
    h = D3DXVECTOR3(0, 1, 0);
    t = seit*s + hoch*h + vor*v;
    here_i_am += t;
    there_i_look_at += t;
}

void ThirdPersonCamera::kamera_fahrt(float seit, float hoch, float speed, float scroll)
{
    D3DXVECTOR3 delta;
    kamera_schwenken(seit, hoch);
    delta = there_i_look_at - here_i_am;
    D3DXVec3Normalize(&delta, &delta);
    delta = 1*delta;
    here_i_am += delta;
    there_i_look_at += delta;
}

```

# Answer
Use `there_i_look` instead of target:

```
void ThirdPersonCamera::CreateViewMatrix()
{
    D3DXMatrixLookAtLH(&view, &here_i_am, &there_i_look, &here_is_up);
}

```
> 1 votes

---
Tags: 3d, camera, rotation, transformation, third-person-view
---


# Question
Title: How to spawn multiple objects in the same frame?
I wrote some code to spawn coins every 20 seconds but it spawns just 1. I'd like to make spawn coins from 1 to 4 coins randomly. Here's what I have currently:

I found a solution for this script I made 4 prefabs with different coins 1,2,3 and 4 and this script work perfectly.

Thanks to all for answers.

```
using UnityEngine;
using System.Collections;

public class CoinSpaws : MonoBehaviour
{

    public GameObject[] coins;
    int coinNo;
    public float maxPos = 1.7f;
    public float delayTimer;
    float timer;

    // Use this for initialization
    void Start()
    {

        timer = delayTimer;

    }

    // Update is called once per frame
    void Update()
    {

        timer -= Time.deltaTime;
        if (timer <= 0)
        {

            Vector3 coinPos = new Vector3(Random.Range(-1.7f, 1.7f), transform.position.y, transform.position.z);
            coinNo = Random.Range(0, 4);
            Instantiate(coins[coinNo], coinPos, transform.rotation);
            timer = delayTimer;

        }

    }
}

```

# Answer
> 3 votes
You could use a **for** loop and a **random integer** between 1 and 4.

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

public class CoinSpaws : MonoBehaviour
{
    public GameObject coins;
    public float maxPos = 1.7f;
    public float delayTimer;
    float timer;

    void Start()
    {
        timer = delayTimer;
    }

    void Update()
    {
        timer -= Time.deltaTime;
        if (timer <= 0)
        {
            Random rnd = new Random();
            int nbCoins = rnd.Next(1, 4);
            for(var i=0 ; i<nbCoins ; i++){
                Vector3 coinPos = new Vector3(
                    Random.Range(-1.7f, 1.7f),
                    transform.position.y,
                    transform.position.z);
                Instantiate(coins, coinPos, transform.rotation);
            }
            timer = delayTimer;
        }
    }
}

```

# Answer
> 0 votes
```
 public class Coins
 {
    public GameObject Coin;
    public float spawnWait,setWait;
 }

 public class NewBehaviourScript : MonoBehaviour {

Coins coin;
//The position of coin
public Transform coinPosition;

private void Start ( )
{
    StartCoroutine(SpawnerCoins());
}

IEnumerator SpawnerCoins ( )
{
    while (true) {
        //minCount and mixCount is min and max Values Of Coins you want
        for (int i = 0; i < Random.Range(minCount,maxCount); i++) {
            Instantiate(coin.Coin,coinPosition.position,Quaternion.identity);
            //spawnWait is how many seconds between each spawning coin
            yield return new WaitForSeconds(coin.spawnWait);
        }
        //setWait is how many seconds between each set of coins
        yield return new WaitForSeconds(coin.setWait);
    }
}

```

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


# Question
Title: Rotation of objects from different axes in Flash AS3
In my game, I have made 4 lines with different colors to form a square but the colored lines are different objects. I want to rotate the lines in a way that the lines will still form a square. Eg:

But I'm only able to rotate them on the central axis, so, it forms a cross:

The code for `leftPressed` is:

```
if(leftPressed)
{
black.rotation -= 90;
blue.rotation -= 90;
yellow.rotation -= 90;
red.rotation -= 90;
}

```

So, I need to know how to rotate objects on different axes.

# Answer
> 0 votes
`addChild()` each line into a new parent `DisplayObject` called `square`. Then rotate `square` instead of each of the children, individually. Flash will handle the correct rotation of the children therein.

Do this once:

```
var square:DisplayObject = new Sprite(); //Can't instantiate DisplayObject - it's abstract. So use Sprite.

//you'll need to get references to each of the lines used here (left to you):
square.addChild(black);
square.addChild(blue);
square.addChild(yellow);
square.addChild(red);

```

Do this every update:

```
if (leftPressed)
{
    square.rotation -= 90;
}

```

---
Tags: flash, actionscript-3, actionscript
---


# Question
Title: glUniformMatrix4dv with a unidimensional array
I am trying to convert this C++ gml code to C and am getting the same array but I cannot see anything on the screen, is there something I am doing wrong maybe on the shader?

GML code in C++:

```
GLuint MatrixID = glGetUniformLocation(programID, "MVP");
...
glm::mat4 MVP = Projection * View * Model;
printf("MVP:\n");
for(int i=0;i<4;i++)
  for(int j=0;j<4;j++)
    printf("%.2f\n",MVP[i][j]);  //prints the same list as in C
...
//durante el loop
glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]); //draw a cube

```

C code:

```
GLuint MatrixID = glGetUniformLocation(programID, "MVP");
...
t_mat4 MVP;  //t_mat4 defined as typedef double t_mat4[16];
mulMatrix(Projection,View,MVP);
mulMatrix(MVP,Model,MVP);
printf("proj*view*model\n");
inrange(i,16)
    printf("%.2f\n",MVP[i]); //unidimensional array
...
//durante el loop
glUniformMatrix4dv(MatrixID, 1, GL_FALSE, MVP); //Nothing shows up

```

vertex shader:

```
#version 330 core

// Input vertex data, different for all executions of this shader.
layout(location = 0) in vec3 vertexPosition_modelspace;
layout(location = 1) in vec3 vertexColor;

// Output data ; will be interpolated for each fragment.
out vec3 fragmentColor;
// Values that stay constant for the whole mesh.
uniform mat4 MVP;

void main(){

    // Output position of the vertex, in clip space : MVP * position
    gl_Position =  MVP * vec4(vertexPosition_modelspace,1);

    // The color of each vertex will be interpolated
    // to produce the color of each fragment
    fragmentColor = vertexColor;
}

```

# Answer
> glUniformMatrix4dv(MatrixID, 1, GL\_FALSE, MVP); //Nothing shows up

This will yield an OpenGL `GL_INVALID_OPERATION` error. The reason being that the `MatrixID` variable is of type `mat4`, which is a *`float`* matrix, not a `dmat4` (which, BTW, is not supported in GLSL 3.30). You almost certainly meant `4fv`.

And of course, your C code should be using `float` arrays, not `double`s.
> 0 votes

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


# Question
Title: How can I properly display the distance with the unit in a string on the UI?
I wrote a script for distance of car and I don\`t know how to make distance like this *Distance: 156Km*. I wrote this code:

```
distanceText.text = ((int)distance).ToString() + "Km";

```

It works only from 1 to 9; when it goes to 10 Km, it disappears but if I write it like this:

```
distanceText.text = ((int)distance).ToString() + " Km";

```

It show like this: from 1 to 9 -\> "5 Km" and from 10 to 99 -\> "99Km" but when it goes to 100 Km and above, it disappears. What code should I write for this to show always Km after the distance.

And I have one more question. I have a gameover canvas and I'd like in gameover canvas to show the final distance I make with PlayerPrefs but it doesn't work.

Here it shows how it does not work:

# Answer
Instead of having two labels. One for `Distance :` and one for `X Km`, you should only have one. Set the label like this :

`distanceText.Text = String.Format("Distance : {0} Km",(int)distance);`

The String.Format method allows you to easily format strings, the ~~`%d` indicates you want it to be formated with an int.~~ `{0}` is where the argument 0 (distance) will be replaced.
> 1 votes

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


# Question
Title: Supporting uniform/non-uniform scale in hierarchical animation
I have worked with hierarchical blended animation systems for a number of years, but I have never been quite sure how to handle scale correctly. The introduction of non-uniform scale is additionally puzzling. Does anyone have any insight into the right way of doing it? What I am trying to determine is when in the hierarchical concatenation that scale is included. My components are stored as a follows:

```
vector3 position;
vector3 scale;
quaternion rotation;
quaternion stretch_rotation;

```

What I am finding is if I include scale into the matrix during concatenation, I run the risk of grossly amplifying the accumulated errors down the hierarchy. Does anyone have any insight or articles here? To be clear - I know how to do hierarchical animation just not the right way to handle scale.

# Answer
Maybe, in running through the hierarchy, you could multiply scalar scales for each separate axis, to get the distinct world-space scale for each separate axis. Unity's `Transform` calls this(?) `lossyScale`, and presumably because it is generated by multiplying the individual axes' scale all the way up the hierarchy, as I recommend, it is a `readonly` member. One can change the local scale at each level up the tree, individually. The brief doc for their implementation may be informative.
> 0 votes

---
Tags: animation, scale, blending, hierarchy
---


# Question
Title: Most efficient implementation for a Sokoban board?
I am making a Sokoban solver in C++ and I was wondering what would be the most efficient implementation for the board, as to say the least memory consuming possible and the quickest operations possible.

I have heard about bit boards but I'm not sure it would be better than a classic 2D array. This is what a Sokoban grid look like :

The player is the greend sqaure, walls are red and static, boxes are blue and goals are the empty blue squares.

**EDIT :** The purpose is too be as efficient as possible when creating/storing the tree of possibilites for a sokoban level.

**EDIT 2 :** What I am looking to store is sokoban boards, as to say a grid that has multiple elements : one **player**, multiple static **walls**, moveable **boxes**, static **goals** (cell to put the box in). I run out of RAM - I have 8Go - on reasonable size levels (+50 moves). The sequence of moves the player has made is also stored with basic integers, like 1 for up, 2 for right etc.

# Answer
Sokoban is NP-complete (Dor and Zwick 1999), see e.g. this survey.

Thus, you will not find a "quick" solver, the bottleneck is simply complexity. The only way to solve Sokoban is to use BFS (breadth first search) search, or, if memory is a problem, iterated DFS (depth-first search).

There are a few optimizations you can do:

* Implement a heuristic, to estimate number of steps needed to solve the puzzle. This allows you to change the BFS to A\*, which searches the space in a more efficient manner, while still guaranteeing an optimal solution.
* Only do moves on boxes (that is, you only consider moving to, and pushing a box, a valid move), instead of considering moving the avatar one step in one of the 4 directions. This will save you a lot of space, the number of game positions is reduced by roughly a factor n, where n is the number of squares on the board.
* You might want some conditions that easily detect if you reach an unsolvable position, such as a box in a corner, and thus disallowing such moves.
> 6 votes

# Answer
I'm not an expert in Sokoban solving, so I can't claim this is "the" most efficient method, these are just some possible efficiencies that suggest themselves.

First, let's reduce our problem space.

Storing the whole 19x11 map as an array of bytes would take 209 bytes.

Storing it as a bitboard of block positions would take 209 bits, or 27 bytes, plus an index for the unique pusher position which in this case we could fit in one additional byte for a total of 28. Already more than 7 times smaller.

We only care about passable tiles, since a tile representing a wall will never have a block in it and will always hold a boring value of 0. So that brings us down to 55 bits for the blocks, or 8 bytes in total. We're now 26 times smaller than the initial array.

But not all passable tiles are created equal. Some, like the non-goal corners, will never hold a block in any solution or intermediate state, since the block would be trapped there and couldn't be pushed away. So, we can do a pre-process to identify only the viable tiles - this will help us later in our search, since we can immediately prune any move that takes a block outside this set. If we use breadth-first search for this fill, we can also note down the generation number of each viable tile we find, and re-use that later as a distance heuristic if using an A\*-type search like Per Alexandersson suggests in another answer.

We start with only the goal tiles in our viable set's frontier, then flood-fill out from there, adding a passable tile to our viable frontier if it's a neighbour of one of our frontier tiles AND has a passable tile on the far side of it. This gives us this yellow region here, 41 tiles, taking us down to 7 bytes total.

Note that if any block starting positions are outside of the yellow viable zone, you can terminate early and conclude that the puzzle has no solution.

Now within *this* set, we only care about the tiles our blocks could actually reach. We can find this set by a similar flood fill starting from our initial block positions, and only adding a neighbouring viable tile to our frontier if there's a passable tile behind us from which we could be pushed into that viable neighbour.

If any of the goal tiles aren't covered by this new search, then we can again early-out with a "not solvable" conclusion, before we've done any of the hard work. :)

That gives us this green region, of only 33 tiles the blocks could ever occupy in a solution intermediate step, so we can store the state in just 6 bytes (or even 5 if we don't mind getting fiddly with our bit-packing, since we only need the bottom bit of the last byte in our bitboard, and can store the pusher position in 6 bits while still being able to express every pathable location).

So we've reduced the size of each state by about a factor of 30, while still retaining the ability to express any solution & intermediate step, and along the way building a few tools we can use to filter and prioritize possible moves.:)

Since our board states fit in a `long` in this case, we can compare two states for equality in a single operation, which is a nice perk too.

Another method to consider is to store just the index of each block within the viable-reachable set, sorting them to keep your representation order-independent, followed by the index of your pusher in its reachable set. Here that's 6 bits each for 7 items, or 42 bits - still about 6 bytes, unless we want to get fancy with bit packing to save the fractional bits and end up with 37 bits / 5 bytes. (Even though this number may look tiny, it's still 71 billion potential board states we might need to search, which could take something on the order of 30 GB of storage for our cache even with minimal overhead)

In this case the two options come out to within a 4-byte alignment padding anyway so it won't make a difference in terms of real storage used, but a big board with few boxes, or a small board with many boxes will shift the advantage one way or the other.

One last possible space saving: you said you store the *sequence* of moves the player has taken - but we don't really need to store all that (and some Sokoban solutions or attempts can get quite long indeed). Instead, we just need to know what was the *last* move we made, which can be expressed in 2 or 3 bits.

To reconstruct our full solution, we start from the goal state our search found, and undo the last move to get the intermediate state immediately before. Then we look up that state and undo *its* last move to get the state before, etc.

If you're using just 2 bits to store the last move, then when you're standing next to a block there's 2 possible preceding states: one where the block was where you're now standing, and you pushed it, and one where it was already in place and you walked up to it. So, it's probably safest to store a third bit for "push/no-push," but if you're being really frugal you can try both and abandon a branch if it tries to look up a prior state that you never generated.
> 2 votes

# Answer
To answer your literal question, first note that a Sokoban board contains both fixed state (the positions of the walls and the goal squares) and mutable state (the positions of the player and the boxes). For a solver, you should have only one copy of the fixed state. Thus, no matter how inefficiently you store it, the space cost of the fixed state is negligible. All you really need to worry about is compactly storing the mutable state.

A simple solution is to sequentially number the passable tiles (including the goals) on the board, and store the numbers of the tiles containing the player and each of the boxes. For example, your example board state above could be represented as (46;3,8,11,13,28,31), where the first number is the tile number of the player and the remaining numbers are the tile numbers of the boxes, with the tiles numbered in top-down, left-to-right order starting from zero.

Note that, to make comparing board positions simple, you'll want to always sort the positions of the boxes in some consistent (e.g. ascending) order. That way, you won't need to worry about the same example position sometimes getting represented as, say, (46;28,3,11,31,8,13) instead.

If you use a single byte for each position, you can handle boards of up to 256 tiles, and only need *N*+1 bytes for a board with *N* boxes. Using two bytes per position would let you have a board with up to 65536 passable tiles. In general, unless you're *really* strapped for storage space, I'd recommend this format as the likely "sweet spot" between compactness and ease of access.

---

If you really need more space, you could always use a smaller number of bits per position. For example, your example board only has 56 passable tiles, so six bits would be enough to encode each tile number, allowing you to squeeze the board state into 7 × 6 = 42 bits, or 5.25 bytes. But this extra space saving will come at the cost of slower encoding and decoding.

An even more compact representation would be to interpret the list of player and box positions as an integer written in base *B*, where *B* is the number of passable tiles on the board, and store that integer. For example, the number:

> 1,420,417,900,415 = (46 × 566) + (28 × 565) + (3 × 564) + (11 × 563) + (31 × 562) + (8 × 56) + 13

encodes the board state (46;3,8,11,13,28,31) in base 56. Using this encoding, no state of your example board can exceed the number 567−1 = 1,727,094,849,535, which can be stored in just 41 bits, saving *a whole bit* over the 6-bits-per-tile encoding. Of course, it also slows down encoding and (especially) decoding even more.

This representation is still not quite the most compact one possible, since some numbers in the range from 0 to *B**N*+1−1 correspond to invalid board states (with two boxes, or a box and the player, on the same tile) and others to non-canonical encodings (i.e. where the box positions are not listed in increasing order). If you *really* wanted to squeeze things as tight as they'll get, you could encode the box and player positions using the combinatorial number system, and then also encode which of the *N*+1 positions is the player. In principle, this would let you encode each board state using a number between 0 and (*B* choose *N*+1) × (*N*+1) − 1 inclusive, with each number in the range corresponding to a distinct valid (although not necessarily reachable) board state. For your example board, with *B* = 56 and *N* = 6, the maximum possible state number using this optimal encoding works out to just 1,623,421,799, which fits in only 31 bits!\* But, of course, the encoding and the decoding would be even slower than with any of the other methods above.

Of course, as noted in the other answers, in practice it's probably much more efficient to rewrite your solver algorithm to avoid the need to store quite so many versions of the board state to begin with.

\*) The fact that the combinatorial encoding saves about 10 bits over the simple base 56 encoding isn't really that surprising, since there are 6! = 720 possible ways to shuffle the 6 boxes, and this number is pretty close to 210 = 1024. So, compared to the optimal encoding, the base 56 system wastes about 10 bits redundantly encoding the order of the boxes.
> 2 votes

# Answer
The board access and memory usage during normal gameplay is unlikely to be your bottleneck. You will only need to check movement every few frames and check sliding once every second at most. At a 16 ms per frame that's not worth optimizing beyond not being an idiot with it.

The real bottleneck related to the board will be rendering it. That requires looping over all tiles and switching over the contents every frame. So any structure that allows a fast iteration of the state will be enough.

---

For a solver implementation you care most about the "push points" and wether you can path to them from the last move.

So store all push points in a separate array and update them on each push. Then when going to select the next move you floodfill from the current location and filter the accessible push points as the next set of moves. This reduces the amount of steps you need to backtrack over.

The most efficient data structure for the floodfill would be a bit board.

1. clear the board and mark the starting position
2. shift the board 1 position in a direction
3. AND the shifted board with a board where only the walkable tiles are set.
4. OR the ANDed board with the current board
5. go to step 2 with a new direction.
6. if the new board after doing all directions is different from the previous board (tested using XOR and a reduce) you are done

This assumes that there isn't anything that happens while you move. Like an enemy that patrols a region.
> 1 votes

---
Tags: c++, 2d, ai
---


title: Prefab instatiation not going well

text:
# Question
Title: Prefab instatiation not going well
I'm trying to Instantiate a prefab when the mouse goes over collider of some GameObject so I'm using OnMouseEnter to instantiate and will use OnMouseExit to destroy it after (when this part of code works fine), the problem is that no error appears in the console but the prefab are not being instantiated, does not appear in the inspector or in the scene, even so, when I print it's name in the console (last line), it appears right. Is my syntax correct?

```
void OnMouseEnter ()
{
    string nomeSeta = "SETA" + direcao.getNome ();
    GameObject seta = Resources.Load<GameObject> (nomeSeta);
    float[] pontosXeZ = Util_CalculosGeometricos.ObterPontosCentraisXeZDeUmRetanguloPorNumeracaoSemRotacao (terrenoPai, direcao.getCoeficienteHorario ());
    seta.transform.localPosition = new Vector3 (pontosXeZ [0], 0.0f, pontosXeZ [1]);
    seta.name = nomeSeta;
    print ("seta.name: " + seta.name);
}

```

# Answer
> 4 votes
Replace

```
GameObject seta = Resources.Load<GameObject> (nomeSeta);

```

with

```
GameObject seta = Instantiate(Resources.Load<GameObject>(nomeSeta));

```

This will load the GameObject from your resources directory and then instantiate it into the scene. Otherwise it's just data local to the scope of your method (which is why your print method works).

# Answer
> 1 votes
I'm not in front of Unity so I can't verify, but I think you need to do `Object.Instantiate` rather than `Resources.Load`

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