# Question
Title: Interpolate object collision stuck in Unity
I am working on a very basic test in 2D. The problem I am having is that, when my sprite collides with the ground, it is checking the event too frequently. The sprite stays in limbo, as it doesn't have a chance to leave the ground. By the time it does, the check tells it to turn around, resulting it quickly going up and down. I uploaded an example clip to YouTube.

When contact is made, the sprite needs to change it's Y axis direction. How do I fix this? Please see my code, below:

```
void Update ()
{
    hitWall = Physics2D.OverlapCircle(wallCheckUp.position, wallCheckRadius, whatIsWall);

    if (hitWall)
    {
        moveUp = !moveUp;
    }

    if (moveUp)
    {
        transform.localScale = new Vector3(-1f, 1f, 1f);
        GetComponent<Rigidbody2D>().velocity
            = new Vector2(speed, GetComponent<Rigidbody2D>().velocity.x);
    }
    else
    {
        transform.localScale = new Vector3(1f, 1f, 1f);
        GetComponent<Rigidbody2D>().velocity
            = new Vector2(-speed, GetComponent<Rigidbody2D>().velocity.x);
    }
}

```

Here is my object:

# Answer
> 0 votes
You could apply a timeout to prevent the collision from being acknowledged the second++ times. For instance, you know it won't collide again for 1s, so make a float and decrement it to 0 when the boolean gets switched. Don't when it gets to 0, turn the boolean back to receive and react to collision again.

---
Tags: unity, c#, 2d, interpolation, rigid-body-dynamics
---


# Question
Title: Is developing 2D sprites as projections of 3D models viable?
I am a solid programmer and have a strong desire to make a 2D top down game. My immediate stumbling block, however, is the art. I am currently using placeholder images, but I really want to develop my own IP. The problem is that I simply can't draw that well. However, I do have really great three dimensional reasoning, and I am rapidly improving in 3D modeling with Maya.

My hope is that I can develop models in three dimensions, and then generate sprites from cross sections, or use of those models. Is this a viable path of developing production quality 2D art?

# Answer
Donkey Kong Country or Abe's Oddworld Oddessy both come to mind as using 3D models to make 2D Sprites. That was from back in the day when computers were powerful enough to model complex 3D assets, but consoles and PCs were not yet able to display those high quality renders in real-time. The examples you could find of this are near limitless.

The actual pipeline one uses is personal preference. The basic idea for these games that I've used as examples is to

1. Model in a 3D environment including textures and lighting.
2. Render the model in each pose that is required for your Sprite sheet and save those renders as bmp files or png or whatever.
3. Use some sort of software (photoshop, gimp, or an application made specifically for compiling Sprite sheets) to make a Sprite sheet.
4. Use this Sprite sheet in your game engine

There are a plethora of tutorials on using Sprite sheets for game dev. I will leave you to search out one that appeals to you.
> 8 votes

# Answer
Projection from 3d to 2d simply follows one important rule - If you can find point (x,y,z) that is inside the 3d object, you can mark one 2d point (x,y) as inside the object. Simplest solution is to just drop the z coordinate.
> -3 votes

---
Tags: 2d, 3d, sprites, art
---


title: Actions abstraction in Goal Oriented AI

text:
# Question
Title: Actions abstraction in Goal Oriented AI
I am back with another question about Goal Oriented AIs.

To explain my problem, I will use a specific example.

In my game, population nodes are spawned on a world map, and important characters called "Migration leaders" can spawn, take in migrants, lead them to a good spot, and then establish a new population node there and finally despawn as they have served their one-time purpose.

What I want to achieve is having only one action called "MoveToTarget" which has no pre-conditions apart from having a target location, and has the effect of setting the fact "Reached target location" to true, which itself is the precondition for other actions. Not sure this is the right way to structure that in the GOAP but that's not exactly my problem, at least I do not think so.

My problem is that, since you can't work with actions that take in an argument, I have little notion of how the AI should determine the location which it will move to when the "MoveToTarget" action triggers, for the following reasons :

* Depending on the character type and generally what is happening, each character will think differently about where they're interested in going. Furthermore, what happens when I have to interrupt the AI's "plan" for some reason ? The original target location for, say, transporting migrants is lost !
* I do not which to make different actions like "MoveToMigrationTarget" because then I'll have to make many MANY more actions, like "MoveToCombatTarget" or "MoveToRessources" and I do not think that will work as that will make me have to keep a "Migration target", a "Combat target".. in memory even for characters that have nothing to do with either of those.

So my question exactly is, where is the AI supposed to do the "practical thinking" in a GOAP ? The Actions themselves must be abstract, and can't take in any argument so I have to somehow have target location(s) in memory and have the GOAP planner know which target corresponds to which action.

I could also extend that question to basically any action that need a specific target / object to work.

# Answer
You could have a universal method (`public static void MoveToTarget(Transform targetLocation, GameObject objectThatNeedsMoving) {/.../}`) that can be reused, regardless of the goal location, as long as you intend for their pattern of movement towards the path to be the same. For instance, you may intend to simply lerp to that location, regardless of character type.

If you need a variety of path patterns, you could inspect the `GameObject` to determine what kind of object it is, and what pattern you would choose to follow. For instance, perhaps a `GameObject` has a script called `Monster` attached to it, so I can see if the passed in `Object` has a `Monster` script, and if it is *not* `null`, tell it to follow a parabolic curve rather than a straight line. From there, forward the `targetLocation` and `gameObject` to your method for moving in that special pattern, perhaps you would have named it `MoveToTargetParabolic(Transform targetLocation, GameObject objectThatNeedsMoving)` or `MoveToTargetMonster(Transform targetLocation, GameObject objectThatNeedsMoving)`.
> 2 votes

# Answer
Generally your problem seems to be focusing on actions more than goals. Your migrant characters have the goal of establishing a new population center, not going to point a. This goal can remain unchanged, even if the target location becomes unavailable, or if a better location becomes available.

Establishing a population center can be broken down into prerequisites: having migrants and being at the location. Since being at the location is a prerequisite for the goal, the character should search for a good location, and then initiate an attempt to move there (this would initiate the moveToTarget action.) When the current action of a character no longer favors their goal, they will stop perusing it (ie: if they arrive at a good location along the way, the prerequisite is met, no need to keep moving). As for if the location becomes unavailable, moveToTarget should fail/become impossible to initiate. The character will have to look for other means to satisfy the "good location" prerequisite.

You can continue breaking down prerequisites into less abstract levels until you get something you can implement. For example a good location could be broken down into having food, water, ect.

The practical thinking occurs by characters selecting the "best" action available, when one action becomes infeasible/impossible, it is no longer a candidate for the best action, and something else must be selected as a means to satisfy the goal prerequisites.
> 3 votes

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


title: Processing Vs Memory Optimization

text:
# Question
Title: Processing Vs Memory Optimization
I'm creating a game with a lot of elements. Should I store all components that I'll eventually access on class variables (memory) or should I access them when running the script(processor)?

Example:

```
private SpriteRenderer sprite;

void Start () {
   sprite = GetComponent<SpriteRenderer>();
}

public void StartMovement()
{
    sprite.doSomething();
}

```

VS

```
void Start () {

}

public void StartMovement()
{
    GetComponent<SpriteRenderer>().doSomething();
}

```

# Answer
Yes you should store them. Storing a reference takes up only 4 or 8 bytes (32bit vs 64bit) space in memory while fetching them using `GetComponent()` can use a lot more, while also it will be a lot slower to execute.

Premature optimization (which you seem to be doing) is a bad thing. You should worry about memory consumption and performance, but not before it becomes a problem. If something is known to be slow (like using `GetComponent()` inside the `Update()` function), you should design your code around that fact. Make the game first, and only after you profile it if it uses too much memory you should start optimizing.
> 4 votes

---
Tags: unity, optimization
---


# Question
Title: WebGLRenderingContext.texImage2D does not implement interface ArrayBufferViewOrNull
I'm working on a WebGL project and all my textures render fine. When i wanted to implement a cubemap i started getting this type error. `Argument 9 of WebGLRenderingContext.texImage2D does not implement interface ArrayBufferViewOrNull.` in all browsers. A fragment of my code i use to load the textures is,

```
    var cubeMap = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_CUBE_MAP, cubeMap);

    for(var i = 0; i < 6; i++)
    {
        var img = cubeMapArr[i];
        console.log(img);
        gl.texImage2D(
            gl.TEXTURE_CUBE_MAP_POSITIVE_X + i,
            0, gl.RGB, 1024, 1024, 0, gl.RGB, gl.UNSIGNED_BYTE,img);
    }

```

the `cubeMapArr` holds HTMLImageElements. Any ideas or experiences about this issue? Using `gl.texImage2D()` like for example this,

```
gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,gl.RGBA,gl.UNSIGNED_BYTE,normalMapTexture);

```

works with no issues. Again `normalMapTexture` holds a HTMLImageElement.

Thank you.

# Answer
> 1 votes
Actually it was my bad,

First form of the function `gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,gl.RGBA,gl.UNSIGNED_BYTE,texture);`

accepts these types https://developer.mozilla.org/en/docs/Web/API/WebGLRenderingContext/texImage2D but second form accepts only ArrayBufferView or null. https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView `gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGB, 1024, 1024, 0, gl.RGB, gl.UNSIGNED_BYTE,texture);`

So i used the first form with the cubemap, then it worked.

Also `webgl2` context accepts other types in the both forms of these functions, you can check it from the first link again.

---
Tags: opengl-es2, webgl, cubemap
---


# Question
Title: How do I make an infinitely scrolling background?
I am trying to make a game where a torpedos keep coming from random directions and the player has to maneuver a submarine to escape them.

I am currently offsetting the background to give it an illusion that the submarine is moving i.e. if the submarine moves forward, I move the background (quad) backwards. This is primarily being done as I want it to be an infinite space. The position of the submarine does not change, the player just controls the rotation of the submarine and the background moves in the opposite direction. The background is set to repeat to give it an infinite space illusion.

The torpedo gets spawned at a random distance and moves towards the submarine. Since, the position of the submarine does not change, the torpedo will always hit the submarine. How do I structure this game, specifically the background repeat so that I can actually move the submarine in absolute dimensions and still maintain the infinite space illusion?

# Answer
If this is as complex as your game gonna be, you could move the torpedo with the background when the player presses a direction key.

i.e., if the player moves up, you don't actually move the player but you move the background AND the torpedo down.
> 1 votes

# Answer
Make your torpedoes a child-object of the background quad. They will become bound to the background's transform and will move as the background moves (it won't matter what your torpedoes are doing, it should look fine). It will be as if you're moving everything BUT the submarine.

Although, making the submarine move and just stretching or tiling a background would be the more efficient way of making this. This wouldn't really mean infinite space but it would mean a HUGE space where the player can't really reach the edge even if they tried to (not the best way of doing it though).

The best way would be to just spawn new backgrounds as the player moves and delete the ones that the player gets too far away from. Something like this only in four directions instead of just one. I'm afraid you'll need to think of ways to do that on your own.
> 1 votes

# Answer
What is usually done with parallax scrolling is **draw the background according to the player's position**.

This means that instead of doing :

```
if (moveRight)
    background.x -= 50;

```

as I suppose you are doing right now, you should do :

```
if (moveRight)
    player.x += 50;

drawBackground(player.x, player.y);

```

Then if you want to keep the submarine in the center of the screen, just apply an offset to all the objects you are drawing.

There are several articles as this one treating about parallax scrolling and video-games : Parallax scrolling
> -1 votes

---
Tags: unity, c#, game-design
---


# Question
Title: What are the advantages and disadvantages of exporting spritesheets instead of models from Spriter into Unity?
I'm working on a simple 2D platformer in Unity and have been using the Spriter2Unity tool to import my Spriter animations directly into Unity. I have noticed that this creates large hierarchies of gameobjects within the imported prefabs, basically 1 per image piece.

Since the animations are fairly simple, I am thinking it would be cleaner to import each of them as a spritesheet and hook them up with a spriterenderer on the player object rather than using the importer tool.

Would this actually result in any performance benefit at runtime or are the impacts of animating a lot of game objects at once negligible?

# Answer
> 1 votes
When you import Spriter animations into Unity, then Unity can use the skeleton-based procedural animation system of Spriter. The advantage of that is that you get far more fluent animations, because Unity can interpolate between the different keyframes. The drawback is that this can become a bit CPU-intense.

When you export your Spriter animations to static spritesheets, you will likely get far better performance. You will also get far simpler game objects which are, as you found out yourself, more intuitive to deal with. But on the other hand your animations will be limited to those frames you export, so they won't be as fluent as they could be with procedural animation. You also lose the ability to switch out parts of your sprites at runtime. This isn't a requirement for *every* game, but for those games where it is required, it's a real killer-feature.

---
Tags: unity, sprites, spritesheet
---


title: Compare Lists in Unity3D/C#

text:
# Question
Title: Compare Lists in Unity3D/C#
Hi guys I am working on a combo feature and I want to compare two C# lists, something like this

```
bool found = false;

List<int> combo = new List<int>();
combo.add(1);
combo.add(1);
combo.add(1);

List<int> playerCombo = new List<int>();
playerCombo.add(1);
playerCombo.add(1);
playerCombo.add(1);

if(combo == playerCombo){
  found = true
}

```

The thing is that == seems that does not work, always throws false, any ideas?

Update: already answered here https://stackoverflow.com/questions/3669970/compare-two-listt-objects-for-equality-ignoring-order

# Answer
Your condition needs to be something like this:

```
public bool IsListSame(List<int> combo, List<int> playerCombo) {

    if (combo.Count != playerCombo.Count)
        return false;

    for (int n = 0; n < combo.Count; n++) {
        bool found = false;
        for (int m = 0; m < playerCombo.Count; m++) {
             if (combo[n] == playerCombo[m]) {
                 found = true;
                 break;
             }
        }
        if (!found) {
            return false;
        }
    }

    return true;
}

```
> 0 votes

# Answer
LINQ provides the extension method Enumerable.SequenceEqual() that can be used as follows:

```
using System.Linq;
// ...

found = combo.SequenceEqual(playerCombo);

```

This method will return true if the two lists are the same length and the corresponding elements are equal according to their default equality comparer.
> 5 votes

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


title: Configure unreal engine to run faster

text:
# Question
Title: Configure unreal engine to run faster
I don't have a dedicated GPU on my laptop and would like to know which settings to change in order to get semi decent performance. I don't care if the 3D camera will render everything pixelated.

At this moment when I try and run the First person shooter demo it will run around 40fps and when shooting the gum the frame rate drops to around 25fps.

I think my CPU is pretty descent for an laptop. Its an i7-3667U & I have 16gb ram. Intel HD Graphics 4000. Also I already have unreal installed on my SSD.

My goal is development only and I will use low poly models when possible.

# Answer
By default UE4 has many post processing effects turned on that may lower your performance, especially on low end GPUs.

Go to Project Settings -\> Engine -\> Rendering

Then disable everything under "Default Postprocessing Settings".

Additionally, in the toolbar above your vieport (where you have a Play button) select "Settings" and "Engine Scalability Settings". There you can set the "Quality" to Low and you have a "Resolution Scale" slider. This slider allows you to use lower resolution, but it works only in Play mode, not in editor itself. You may also try other settings in "Scalability" group.
> 2 votes

---
Tags: unreal
---


title: Load large .obj file

text:
# Question
Title: Load large .obj file
I am working with the 3D model and I am using the Scene Kit for rendering and Model I/O for loading the obj file. It works perfectly fine for the small size of obj. But now I have 250MB of file and when It starts loading it takes too much memory and lower end devices are crashing.

How can I read this obj files that is used by the scene kit or any alternate way to read this file? Below is the line of code I used for reading obj file:

```
MDLAsset *asset = [[MDLAsset alloc]  initWithURL:mapURL];
MDLMesh *object = (MDLMesh*)[asset objectAtIndex:0];

```

Is there any alternative way to load large obj files?

# Answer
Finally I resolved issue. Issue is with the Xcode I uninstalled everything and installed again and its stared working perfectly. And also there are some memory leaks in OpenGL so that I released.
> 1 votes

---
Tags: ios, scenekit
---


title: How big is a Game World in LibGDX?

text:
# Question
Title: How big is a Game World in LibGDX?
I know that the game world is like the whole game itself and most of the time, the developer sets the Screen to be a particular section of the Game World. However, how big is the Game World? For instance, when we run the default code for libgdx once we first create a project, a simple texture is shown with a red background. Does that mean that the Game World can be endlessly big? If we set the desktop launcher's size to be really big, does the red background still fill the whole launcher?

# Answer
> 2 votes
The world can be as big as you want, up to reasonable limitations of the numbers you use to store information about the world. You get to pick both the types of numbers you use (integers or floats) and the metric you assign to those numbers: are they measuring tiles, pixels, feet, meters, furlongs?

If you use 64-bit integers to store information about the positions of things in your world, your world can go from `-2^63` to `2^63 - 1` in size. If you use floats, you have an even larger range.

Note that your choice here does have consequence: integers are all representable within the available range, but you don't have decimal points to do precise positioning, and you may need to convert things to a local floating-point coordinate frame to render them. Floats, on the other hand, allow you to do very fine fractional positioning but have precision errors the further you get from zero. Either choice might involve you doing more work somewhere else to translate between coordinate systems and representations using in your code to the ones expected by some third-party library (most notably the underlying graphics API).

But the main point is that the decision is yours to make.

# Answer
> 0 votes
A game world is just an abstraction used to make drawing stuff to the screen simpler (would you rather manage coordinates at `(x,y) -> (160000000,160000000)`, or `(x,y)->(1600, 1600)`? The "world coordinate" is converted to screen coordinates and drawn on the screen via a series of mathematical operations involving a projection matrix. This matrix is used in a SpriteBatch (it's been a while since I have fiddled with libgdx, but I believe each SpriteBatch has a default projection matrix that maps the ratio of pixels per world coordinate to 1) to perform aforementioned mathematical operations. You can create custom projection matrices and set the sprite batch projection matrix for an almost infinite set of possibilities. The libgdx camera classes have projection matrices that you can use to set the batch matrix.

So, this all means that there really is an infinite number of places to "draw stuff". Well, mot really infinite technically, but infinite in practice. And if you don't like one coordinate system you can configure your own and set the SpriteBatch to render to that.

---
Tags: libgdx
---


title: Isometric tiles

text:
# Question
Title: Isometric tiles
I am trying to figure out what is the best way ( in terms of performance) to create a ground to place my 2d isometric sprites on..Should it be tiled ( using 2d sprites ) or just use a plane ( or terrain ) and add a texture to it?

# Answer
The best way is often *whichever way you prefer*. At the end of the day, you should not have performance issues as a result of dividing your background into smaller pieces. If it suits your design better, do it.
> -2 votes

---
Tags: unity
---


# Question
Title: LibGDX How to set spacing between list items in a Scene 2D Select Box Widget?
I have created a Select Box (Scene2D widget) which holds a list of items, to be selected. My code works fine, but I would like to make a little more spacing between each list item in the dropdown list in the select box. How can I achieve that??

My code for the list box is this.

```
List.ListStyle selectBoxListStyle = new List.ListStyle();
selectBoxListStyle.background = new NinePatchDrawable(new NinePatch(this.selectBoxListBackgroundTexture, 10, 10, 10, 10));
selectBoxListStyle.font = this.textFieldFont;
selectBoxListStyle.fontColorSelected = Color.WHITE;
selectBoxListStyle.fontColorUnselected = Color.BROWN;
selectBoxListStyle.selection = new TextureRegionDrawable(new TextureRegion(this.textFieldSelectionTexture));

SelectBox.SelectBoxStyle selectBoxStyle = new SelectBox.SelectBoxStyle();
selectBoxStyle.background = new TextureRegionDrawable(new TextureRegion(this.selectBoxMiddleBackgroundTexture));
selectBoxStyle.backgroundOpen = new TextureRegionDrawable(new TextureRegion(this.selectBoxMiddleActiveBackgroundTexture));
selectBoxStyle.font = this.textFieldFont;
selectBoxStyle.fontColor = Color.WHITE;
selectBoxStyle.listStyle = selectBoxListStyle;
selectBoxStyle.scrollStyle = new ScrollPane.ScrollPaneStyle();

SelectBox<String> selectBoxWidget = new SelectBox(selectBoxStyle);
selectBoxWidget.setItems("Test 1", "Test 2", "Test 3");

```

# Answer
You can do this using:

```
selectBoxStyle.listStyle.selection.setTopHeight(10);

```
> 2 votes

---
Tags: java, libgdx, gui, scene2d
---


# Question
Title: How do I force a game object to move along projectile trajectory, like in Angry Birds?
I am a new Android game developer. I want to force my game object to move in a projectile trajectory, like in Angry Birds.Related example here and my example You can see an example in the image.

I used jbox2d to write a little bit of code, but I don't know how to make it work. How do I force movement along a projectile trajectory?

My code is below:

```
    private static class ProjectileEquation {

        public float gravity;
        public Vector2 startVelocity = new Vector2();
        public Vector2 startPoint = new Vector2();

        public float yogx(float t) {
            return startPoint.x + t * startVelocity.x;
        }

        public float yogy(float t) {

            float u = (float) -4.97741939970554;
            float v = (float) 30.88079;
            float tt = 1/6f;
            float n = (u+v)/2*tt;

            return startPoint.y + n * t *startVelocity.y + 0.5f *(n*n+n)
                * t * t * gravity;
        }
    }

    private static class Controller {
        public float power = -66f;
        public float angle = 585f;
    }
}

 public float P2M(float xPixels) {
    return xPixels * metersPerPixel;
}

public float M2P(float xMetres) {
    return xMetres * pixelsPerMeter;
}

public float MaxHeight(){

     if (projectileEquation.startVelocity.y > 0){

            return projectileEquation.startPoint.y;
     }
        return projectileEquation.startPoint.y;
        }

public void Update() {
    projectileEquation.startVelocity.set(controller.power,controller.power);
    projectileEquation.startVelocity.rotate(controller.angle);
     //     bd = bodies;

}

    @Override
    protected void onDraw(Canvas c) {
        super.onDraw(c);

        MaxHeight();

        Update();

        float t = 0f;
        x = c.getWidth()/2;
        y = c.getHeight()-20;

        float timeSeparation = this.timeSeparation;

        for (int i = 0; i < trajectoryPointCount; i++) {

            float x = this.x +  projectileEquation.yogx(t);
            float y = this.y +  -projectileEquation.yogy(t);

            t += timeSeparation;

            if(A) {
                c.drawBitmap(bmp, x, y, null);
            }else if(B) {

                float bX = M2P(body.getPosition().x);
                float by = c.getHeight() - M2P(body.getPosition().y);
                body.setActive(true);

                c.drawCircle(bX, by, M2P(body.m_fixtureList.m_shape.m_radius), circlePaint);
            }
        }
    }

public class jbox2d {

    public float targetFps = 30.0f;
    public float timeStep = (1.0f / targetFps);
    private int interations = 2;
    public Body body;
    private World world;
    private BodyDef bodydef;

    public void Create(){

        Vec2 gravity = new Vec2(0,-10f);
        boolean doSleep = true;
        world = new World(gravity, doSleep);
    }

    public void addboll() {

        bodydef = new BodyDef();
        bodydef.type = BodyType.DYNAMIC;
        bodydef.allowSleep = true;

        bodydef.position.set(8.24f,10f);

        body = world.createBody(bodydef);
        body.setActive(false);
        float tt = 0f;

        Vec2 stx = new Vec2();
        Vec2 sty =new Vec2();

        for (int it = 0; it < 20; it++) {

            stx = M2P(projectileEquation.startVelocity.x);
            sty = M2P(projectileEquation.startVelocity.y);

            stx = M2P(projectileEquation.yogx(tt));
            sty = -M2P(projectileEquation.yogy(tt));

            body.setLinearVelocity(new Vec2(stx,sty));
            body.applyLinearImpulse(body.getLinearVelocity(), body.getWorldCenter());

            tt += timeSeparation;
        }

        CircleShape circle = new CircleShape();
        circle.m_radius = (float).42;

        FixtureDef fixturedef = new FixtureDef();
        fixturedef.density = 1.0f;
        fixturedef.restitution  = 0.9f;
        fixturedef.friction = 0.2f;
        fixturedef.shape = circle;
        body.createFixture(fixturedef);

    }

    public void update(){
        world.step(timeStep, interations, interations);
    }
}

```

# Answer
You should think the other way around. Instead of defining an arc and then forcing the game object to follow it, you should let the game object define the arc.

Games usually solve this by giving the object a velocity vector (an x and y component in 2d and an additional z in 3d), set it to something, then each frame they add it to the position vector. They also subtract gravity from the velocity vector's y component to make it eventually start falling down.

Then you could apply some physics-based wizardry to move the object just the right way. Do you want the ball to reach `x` in time `t` while having a maximum height of `y`? No problem (vx and vy are the velocity vectors, px and py are the positions and g is the gravity):

```
vx = (x - px) / t
// s = v0*t+at^2/2 -> v0 = s/t-at/2
vy = (y - py) / t - g * t / 2

```
> 3 votes

# Answer
I would recommend a physics based approach as Bálint stated.

He covered how you could pick what your Vx and Vy would be based on a desired distance and tie.

You can also define those values based on launch velocity and angle

```
vX = vLaunch * cos( launchAngle )  //Be careful of radians / degrees
vY = vLaunch * sin( launchAngle )

```

Then in your update loop you simulate physics:

```
x += vX * dt
v += vY * dt - 0.5*g *dt*dt
vY += -g *dt

```

And there you go. dt is your delta time. The time between each frame. You can also have it run faster or slower than real time by modifying that. g is the acceleration due to gravity. If each pixel represents 1 meter (3 feet), you would make it 9.8 to reflect Earth-like gravity. Make it smaller if you wanter a smaller scale (for example .98 would give you 10 pixels to a meter.

The nice way about this is that you can modify it to be more dynamic and respond to a change in forces. You could, for example, have it reverse the velocity if it detected a collision to have it bounce (real bouncing is a bit more complicated, but you can get something fairly convincing).

ALTERNATIVELY

If you want to force a projectile to move along a predefined parabola:

each step you would do the following in your update

```
t+=1;
x+=vx*t
y = h + vy*t -0.5*9.8*t*t    //h is the starting height

```

This will move it along the parabola defined by your parameters. Personally, I prefer the first way, but I also used to be a Physicist.
> 0 votes

---
Tags: java, jbox2d
---


# Question
Title: What does the alpha channel on a back buffer do?
I see that e.g. in OpenGL it is possible to create a back buffer with an alpha channel (RGBA8888). What's the effect/advantage over having an RGB888 back buffer?

# Answer
You can use the destination's alpha (backbuffer) as a factor in blending functions such as `GL_DST_ALPHA` and `GL_ONE_MINUS_DST_ALPHA`.

This, among other things, lets you do front-to-back transparency/blending.

On some platform this also lets you have transparent windows and overlays that use the front buffer's alpha value.
> 3 votes

---
Tags: opengl, graphics, graphics-programming, srgb
---


# Question
Title: How to count rotations or spins when using addtorque?
I have a rigidbody and use 4 keys to addtorque in 4 different directions:

* W adds torque positively along the X axis (pitch forward)
* S adds torque negatively along the X axis (pitch backward)
* A adds torque negatively along the Y axis (yaw left)
* D adds torque postively along the Y axis (yaw right)

The rigidbody is able to rotate around/spin in any combination of these directions, but my issue is how can I count the number of rotations it has done in any given axis? Eg. if the player has completed 2 360 rotations to their left I would like to display "2 Left Spins" etc.

I have tried storing the eulerangles of each axis but this is no good as it resets after certain degrees.

I think the way it could work is on keydown reset a degrees counter, while the key is being held I could continue to store the change in rotation for that axis, and then on keyup I could divide this total number of degrees by 360. I'm not sure how to do this in C# though, or if this is the best way to do this.

How could I do this?

# Answer
> 2 votes
Might be advantageous to not demand a totally full circle (= airplane back completely horizontal rotation) for an "accepted roll" - maybe it's sufficient, and more user-friendly, to reach an *almost* horizontal position in order to consider it a completed roll? In addition, it's always a bit hairy to use an accumulation over a long period of time - it may diverge. I talk about roll below, but one can ofc do it for any axis. I didn't bother with gimbal lock issues.

1. Grab the Euler angle each frame, change it to -180 ... 180 degree domain using

```
if (angle > 180) {
    angle -= 360;
    }

```
2. If abs(angle) passes a threshold, say 40 degrees (can be any between 1 and 179), resolve a value to be -1 if the rotation was clockwise, 1 if it was counterclockwise, add that to A (that was originally 0):

```
if   ( (abs(angle) > 40) AND (abs(prevangle) <= 40) )
orif ( (abs(angle) < 40) AND (abs(prevangle) >= 40) ) {
    A += sign(angle - prevangle); // sign() should return 1, 0 or -1
    }

```
3. Check if abs(A) has reached 2:

```
if (abs(A) = 2) {
    [Add one to number of rolls (can even count left and right rolls separately, based on sign of A]
    A = 0; // Reset A
    }

```
4. Always store angle for next frame:

```
prevangle = angle;

```

That is: Passing the threshold in either direction adds 1 or -1 to A. Passing again in the *same* direction adds again 1 or -1 to A. If A reaches 2 or -2, a roll was made.

Aborting the roll before the 2nd "add" just causes A to become 0 again.

# Answer
> 3 votes
Get the difference between the last and the current `EulerAngles` variable, add it to another variable, check that variable and if the variable is over 360, subtract 360 from it and add one to the spin counter.

So, something like this (might not work exactly as it's typed in, didn't test the code but it can at least be used as pseudo-code):

```
float rollDegree = 0, previousRollAngle;
int leftSpins = 0, rightSpins = 0;

void Start(){ previousRollAngle = gameObject.transform.eulerAngles.x;}
void Update(){
    if(rollDegree >= 360)
    {
        rollDegree = rollDegree - 360;
        leftSpins++;
    }
    else if (rollDegree <= -360)
    {
        rollDegree = rollDegree + 360;
        rightSpins++;
    }
    rollDegree = rollDegree + (gameObject.transform.eulerAngles.x - previousRollAngle);
    previousRollAngle = gameObject.transform.eulerAngles.x;
}

```

---
Tags: unity, physics, rotation, rigidbody, torque
---


# Question
Title: Drawing a partial sprite with batch-LibGdx
I have a sprite like this.

I want to draw this sprite in such a way that sprite is growing from bottom to top, using sprite batch on tap.for that,I have written the following code:

```
  if (MyInputProcessor.isTap)
{
Sprite stickSprite = new Sprite(stickTexture);
stickSprite.setPosition(stick.getX(),stick.getY());
for(float n=0;n<100;n++)
{
     float i = 0.01f * n;
    batch.draw(
    stickSprite.getTexture(),
     stick.getX(),
     stick.getY(),
         stickSprite.getWidth() / 2,
         stickSprite.getHeight() / 2,

         stickSprite.getWidth(),
         stickSprite.getHeight()*i,  //multiplying with height
         stickSprite.getScaleX(),
         stickSprite.getScaleY(),
        0 ,
        stickSprite.getRegionX(),
        stickSprite.getRegionY(),

        stickSprite.getRegionWidth(),
        stickSprite.getRegionHeight(),
        false,
        false);

 }
MyInputProcessor.isTap = false;

```

}

Here the i value increments but not taking effect in the code to scale. Whats wrong with the code?

I tried this also:

```
   private void drawStick() {

    Sprite stickSprite = new Sprite(stickTexture);

    if (MyInputProcessor.isTap)
    {
       stickSprite.setPosition(stick.getX(),stick.getY());
       for(float n=0;n<=100;n++)
       {
        float i = 0.01f * n;
        stickSprite.setSize(stickSprite.getWidth(),stickSprite.getHeight()+i);
        }
    }
  stickSprite.draw(batch);

```

But rendering full sprite only.

# Answer
> 0 votes
**EDIT:** You need to separe sprite's *initialization* and *display*

1. Make your sprite ONE time in your create method for example
2. Update your sprite's height on tap
3. Draw your sprite in your render method

---

Your code won't do what you want because you *make a new sprite at every tap*. You want to have a single sprite which you *resize in height at every tap*.

You should have something like this

```
// On tap
stickSprite.setSize(stickSprite.getWidth(), stickSprite.getHeight() + addValue);

```

This way you could draw your sprite easier like that

```
// On draw
stickSprite.draw(batch);

```

The setSize will resize your texture to the size you tell him. It will do it perfectly for your unicolor texture.

Hope it helps

---
Tags: libgdx, sprites, spritebatch
---


# Question
Title: Bullet: btCollisionWorld::contactTest doesn't work
I added some boxes in a collision world, then use btCollisionWorld::contactTest to test if any box contact with a given sphere. Below is the code:

```
    int SpacePhysics::SphereContactTest(const btVector3 &center, btScalar radius) {
        btSphereShape *sphere_shape = new btSphereShape(radius);
        btCollisionObject *sphere = new btCollisionObject();
        sphere->setCollisionShape(sphere_shape);
        sphere->setWorldTransform(btTransform(btQuaternion(), center));
        collision_world_->contactTest(sphere, result_callback);
        delete sphere;
        delete sphere_shape;
        return result_callback.hit_count;
    }

```

However no contact can be detected(when it should), if I use btCollisionWorld::contactPairTest to test the sphere with all the collision objects in the world, the contacts can be detected. But using `btCollisionWorld::contactTest` nothing can be detected. What's the proper way to use `btCollisionWorld::contactTest`?

# Answer
Found the reason:

`sphere->setWorldTransform(btTransform(btQuaternion(), center));`

set the sphere with a invalid transform, therefore no collision can be detect. Although I don't understand why `contactPairTest` can still detect collision.
> 1 votes

---
Tags: bullet-physics
---


# Question
Title: [Unity2D]Make a bullet move toward player and keep moving when past him
Basically I'm trying to make enemies attack player and shot bullets towards player and for now is kinda working, but my problem is the bullet stop when it reach the player position instead of keep moving.

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

public class EnemyTwoBulletScript : MonoBehaviour {

    public float bulletDamage;

    private float bulletSpeed = 9.5f;
    private float spriteWithDelta;
    //private Rigidbody2D bulletBody;
    private Transform playerTransform;
    private Transform selfTransform;
    private Vector3 playerPosition;

    // Use this for initialization
    void Start() {
        //bulletBody = GetComponent<Rigidbody2D>();
        spriteWithDelta = GetComponent<SpriteRenderer>().bounds.size.x / 2;
        playerTransform = GameObject.FindWithTag("Player").GetComponent<Transform>();
        bulletSpeed = 9.5f;
        playerPosition = playerTransform.position;
        selfTransform = GetComponent<Transform>();

    }
    // Update is called once per frame
    void Update () {
        selfTransform.position = Vector3.MoveTowards(selfTransform.position,playerPosition,bulletSpeed*Time.deltaTime);
    }
}

```

I don't want the bullet to follow player either, I just want to shot a rect between origin and player, but keep moving when the bullet past player.

# Answer
You have to use a direction vector instead of the MoveTowards function. It can be easily done as follow :

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

public class EnemyTwoBulletScript : MonoBehaviour {

    public float bulletDamage;

    private float bulletSpeed = 9.5f;
    private float spriteWithDelta;
    //private Rigidbody2D bulletBody;
    private Transform playerTransform;
    private Transform selfTransform;
    private Vector3 playerPosition;
    private Vector3 direction ;

    // Use this for initialization
    void Start() {
        //bulletBody = GetComponent<Rigidbody2D>();
        spriteWithDelta = GetComponent<SpriteRenderer>().bounds.size.x / 2;
        playerTransform = GameObject.FindWithTag("Player").GetComponent<Transform>();
        bulletSpeed = 9.5f;
        playerPosition = playerTransform.position;
        selfTransform = GetComponent<Transform>();
        direction = (playerPosition - selfTransform.position).normalized ;

    }
    // Update is called once per frame
    void Update () {
        selfTransform.position += direction * bulletSpeed * Time.deltaTime;
    }
}

```
> 2 votes

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


# Question
Title: Unity assembly files missing from "Temp/bin/Debug"
I'm trying to use VS Code on a Mac with Unity and C#. When I try to open a Unity project in VS Code, it can't load *Assembly*.dll\* files from few locations which are defined by default in *.csproj* files; *"Temp\bin\Debug\\"*.

When I check the \*Temp\bin\Debug\* paths, while Unity is running, they are empty; they doe not contain the assembly files, where I assume they should. The files are in *"Library/ScriptAssemblies"*. Moving them is not an option, because I would have to do that manually every time I change *sth.* in any script file. Changing the path in the *.csproj* files is also not a good idea, because those files get rewritten every time you open a project in Unity.

---

This issue causes lot of problems in the editor:

> \[WARNING:OmniSharp#MSBuild\] Unable to resolve assembly '/\[...\]/Temp/bin/Debug/Assembly-CSharp-firstpass.dll'
> \[INFORMATION:OmniSharp#MSBuild\] Update project: Assembly-CSharp-Editor-firstpass
> \[WARNING:OmniSharp#MSBuild\] Unable to resolve assembly '/\[...\]/Temp/bin/Debug/Assembly-CSharp-firstpass.dll'
> \[INFORMATION:OmniSharp#MSBuild\] Update project: Assembly-CSharp-Editor
> \[WARNING:OmniSharp#MSBuild\] Unable to resolve assembly '/\[...\]/Temp/bin/Debug/Assembly-CSharp-Editor-firstpass.dll'
> \[WARNING:OmniSharp#MSBuild\] Unable to resolve assembly '/\[...\]/Temp/bin/Debug/Assembly-CSharp-firstpass.dll'

All type references coming from my custom scripts and the `UnityEngine` namespace are missing, and highlighted as errors:

However, intellisense seems to be working fine for `UnityEngine` types:

---

I tried to reinstall MonoDevelop it a few times, including a brew and downloadable package. MonoDevelop seems to be installed properly:

> `$ mono --version`
> `Mono JIT compiler version 4.6.2 (mono-4.6.0-branch/ac9e222 Wed Dec 14 17:02:09 EST 2016)`
> `Copyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com`
> `TLS: normal`
> `SIGSEGV: altstack`
> `Notification: kqueue`
> `Architecture: x86`
> `Disabled: none`
> `Misc: softdebug`
> `LLVM: yes(3.6.0svn-mono-master/8b1520c)`
> `GC: sgen`

.NET works as well:

> `$ dotnet --version`
> `1.0.0-preview2-1-003177`

---

How do I fix this?

# Answer
> 4 votes
Solution came quicker than i expected, after some experimentations with creating new project and running it in VS Code (which was a successfull try) I've decided to remove whole `.vscode` directory from project dir and it worked.

Thx guys ;)

---
Tags: unity, c#, macos, visual-studio-code
---


title: Recreate UI or move it out of view?

text:
# Question
Title: Recreate UI or move it out of view?
Which method would be best? What are the pros and cons? For example, if I have a main menu screen, I can easily start my game loop right as the user presses 'Start'. Which would be better, moving the 'Start' button as well as, 'settings, leaderboard, etc' buttons out of view? or to erase them and then recreate them when needed?

# Answer
Erase them and recreate them as-needed. It is logically simpler and cleaner, and it avoids any potential problems that might arise from focus issues leaving the buttons and whatnot still accessible via the keyboard or other input device.

The only real reason to consider keeping them around but hiding them is if they are costly to re-create or show; generally this will *not* be a performance concern, and if it is it's worth first looking at whether or not you're doing something incorrect during the creation (such as reloading the textures from disk or whatever).

If for whatever reason you do have to go the route of simply moving the UI offscreen, make sure to take whatever precautions are needed to ensure they are totally disabled.
> 2 votes

# Answer
It is simpler to debug 2 distinct simple code paths than it is to debug 1 code path where a boolean flag is used a lot to enable or disable features.

In other words for stuff like the main menu, pause screen you would have a different function you call from the main game loop:

```
switch (mode){
case MAIN_SCREEN: do_main_screen_stuff(); break;
case PAUSED: do_pauze_screen_stuff(); break;
case GAMEPLAY: game_update_and_render(); break;
case LOADING: loading_screen(); break;
}

```

But just because you aren't in `GAMEPLAY` doesn't mean that you can't render the player character doing some animations.

For example Assassin's Creed loading screen let you run around in a empty world. The only code needed for that is the animation blending systems and the inputs, there is no need to check collisions with the world geometry or trigger areas, no need to run the render culling operations because there is nothing to render except the player character.

There is reason to move stuff offscreen when not used however. For example if you want to avoid lag in late game because more stuff becomes available in the hub world, instead you can move the trigger areas that activate later out of bounds so the extra checks are always happening and framerate stays constant.
> 0 votes

---
Tags: architecture, gui
---


# Question
Title: How to make sure that when two bodies collide, there is only one collision detection on box2d?
I'm using LibGDX with Box2D and, when two bodies collide, the collision is detected multiple times.

Here's the code:

```
public void preSolve(Contact contact, Manifold oldManifold)
{
  Body a = contact.getFixtureA().getBody();
  Body b = contact.getFixtureB().getBody();

  if ((Utils.IsPlayer(a) && Utils.IsEnemy(b)) ||
      (Utils.IsEnemy(a)  && Utils.bodyIsPlayer(b)))
  {
    player.isHit = true;
    player.destroy();
    System.out.println(player.isHit);
  }
}

```

The player is destroyed multiple times; I want the player to be destroyed only once.

# Answer
> 3 votes
I recommend you look into how box2D works.

Anyways use one of the below, most likely BeginContact.

```
void BeginContact(b2Contact* contact);
void EndContact(b2Contact* contact);

```

Excerpt from the from the greatest source of Box2d knowledge know to mankind to explain why.

## iforce2d.com: Anatomy of a collision

---

# Impact 1, 2, 3

When fixtures are overlapping, Box2D's default behavior is to apply an impulse to each of them to push them apart, but this does not always succeed in a single time step. As shown here, for this particular example the two fixtures will be overlapping for three time steps before the 'bounce' is complete and they separate again.

During this time we can step in and customize this behavior if we want to. If you are using the contact listener method, the PreSolve and PostSolve functions of your listener will be repeatedly called in every time step while the fixtures are overlapping, giving you a chance to alter the contact before it is processed by the collision response (PreSolve) and to find out what impulses were caused by the collision response after it has been applied (PostSolve).

To make this clearer, here is the output obtained for this example collision by putting a simple printf statement in the main Step function and each of the contact listener functions:

```
...
Step
Step
BeginContact
PreSolve
PostSolve
Step
PreSolve
PostSolve
Step
PreSolve
PostSolve
Step
EndContact
Step
Step
...

```

Outcome: PreSolve and PostSolve are called repeatedly

# Answer
> 0 votes
Firstly, your question is very unclear. It doesn't have all the necessary information. Nothing at all in fact. Try to be a little more informative or precise in the future.

When two bodies collide in Box2D there are numerous collisions. Collisions in Box2D are really the fixtures which are used to detect when a collision occurs.

Collisions can happen in all kinds of ways so they have a lot of information that can be used in the game logic.

An object named 'b2Contact' has information of the list of colissions occuring. This is how you can access that list.

```
 for (b2Contact* contact = world->GetContactList(); contact; contact = contact->GetNext())
  contact->... //do something with the contact

```

or you can make use of collision listeners. Also, these kinds of collisions and lists state the collisions with the AABBs meeting. And if you wish to know if the fixtures itself are meeting, you can use IsTouching() method.

# Answer
> 0 votes
For many collisions, there will be several contacts to resolve. This is why you're getting multiple calls to your `player.destroy()`.

I don't know what you're doing in the `destroy` method, but you shouldn't destroy any **Box2D** bodies of fixtures in there, as they might be needed for other `preSolve` calls.

What you could do is instead of immediately destroying the `player` when the `Contact` is solved, set a *pending destruction* flag on the `player` (in your case the `isHit` member might work for you;

```
public void preSolve(Contact contact, Manifold oldManifold) {
  Body a = contact.getFixtureA().getBody();
  Body b = contact.getFixtureB().getBody();

  if ((Utils.IsPlayer(a) && Utils.IsEnemy(b)) || (Utils.IsEnemy(a) && Utils.bodyIsPlayer(b))) {
    player.isHit = true;
  }
}

```

Then in your update method (possibly the `Screen.render` method or where ever you handle what you need to do in your game loop), you read the flag and `destroy` the `player` then. Destroying **Box2D** bodies in callbacks like `preSolve` is likely to cause **Box2D** to crash.

# Answer
> 0 votes
It's totally possible for multiple collisions to occur in your situation. What you can do is to check for the first time that happens, and then destroy your player only once.

You can then disable collision detection for the player after that to prevent the 2nd, 3rd or more collisions from occurring anymore.

You can also check to see if the player is destroyed before attempting to destroy it again.

There are so many ways of going about doing this :)

# Answer
> 0 votes
I was searching for an answer because I had the exact same problem, and I thought of a great and light workaround. When you create your method of what happens to your B2D Body after the collision, just create an object and assign it to the obects' .getUserData. Then when the collision is called again, you can "save yourself" with an "if statement".Example:

```
public void onHit() {
    if (object != body2.getUserData()){
        setToDestroy = true;
    object = body2.getUserData();

}

```

It actually worked for me!

# Answer
> 0 votes
If one of the body has two (or more) fixtures, then the touch event will occur several times. You check it in preSolve.

---
Tags: collision-detection, libgdx, box2d
---


title: Phaser Shooting Game

text:
# Question
Title: Phaser Shooting Game
I am making an shooting game in Phaser. I want to control the gun using the arrow keys i.e.: upArrow, DownArrow and Enter

upArrow : is to increase the angle
downArrow : is to decrease the angle
Enter : To hit the target

I do not know, how to do this thing?

# Answer
> 1 votes
I know very little about Phaser, but for my pure JS/canvas projects I handle key input with eventListeners. Here is how I do it:

```
var keys = {up:false, left:false, down:false, right:false};
//Add one for every key you want
//Change canvas to the active element
document.getElementById("canvas").addEventListener("keydown", function(e){
   switch(e.keyCode){
      case 38: //38 is keyCode for up arrow
         keys.up=true;
         break;
      case 37: //37 is keyCode for left arrow
         keys.left=true;
         break;
      //And so on... (No default needed)
   }
}
document.getElementById("canvas").addEventListener("keyup", function(e){
   switch(e.keyCode){
      case 38:
         keys.up=false;
         break;
      case 37:
         keys.left=false;
         break;
      //And so on... (No default needed here either)
   }
}
function gameLoop (){
   //Now you can check if the key is pressed or not
   if(keys.up){
      player.moveUp(); //Or whatever you use for moving
   }
   if(keys.left){
      player.moveLeft();
   }
}

```

I have seen similar solutions, but with an array to save the key presses. To get the keyCodes, I would reccommend using keycode.info.

I hope this helps! (Maybe there is a much simpler way to do it with Phaser)

---
Tags: javascript, phaser
---


title: Item find rate formula

text:
# Question
Title: Item find rate formula
I have an RPG game where players can fight monsters limitless, and can get drops from these monsters.

Currently I store in my database a table called `monster_drops` with `find_rate` column which is a number between 1 to 10,000. Whenever a player kill a monster, a number is generated and if it's lower from the current number stored in the monster find\_rate column, he gets the item.

For example, if the find\_rate of the item will be 10k, he will get the item every monster. If the find\_rate will be 1k, there is 10% chance he will get it.

My question- is there any better way, maybe simpler, or more accuarate, to calculate and set item drops?

# Answer
> 3 votes
The problem with random drops, is that those are random! :).

You could get too much misses in a row, or you could be very very lucky. In my game I use an approach that allows both to keep some randomness, and also to avoid to avoid player frustration.

**You need 3 columns in your table `monster_drop_rates`**

```
drop_ID |  find_rate  |  entropy

```

Basically each enemy will have configured a couple of possible drops.

```
enemy_ID | drop_ID1 | drop_ID2 | drop_ID3

```

Note that each drop have its own entropy (the concept of entropy is the same we see in PathOfExile)

however notes that I improve a bit the PoE concept:

```
foreach(var drop in enemy.drops)
{
     drop.entroy += drop.find_rate*Random(0.75f,1.25f);
}

enemy.drops.SortByEntropy();

var first_drop = enemy.drops.GetFirst();

while(first_drop.entropy>100){

    first_drop.entropy -=100;
    SpawnDrop(first_drop.drop_ID);
    enemy.drops.SortByEntropy();
    first_drop = enemy.drops.GetFirst();
}

```

Basically for each possible drop of a enemy we add a slightly randomized chance, when we get over 100 treshold, we spawn that drop, note that we do that in a loop, so that in example we could spawn multiple items if we set a spawn chance greater than 100 (similiar to what happens in Diablo III).

The content of a drop is randomized too.

---

**What is entropy?**

It is just a way to get around very lucky or very unlucky rolls.

In example if you have a item that drops 90% of times, You could still have a 1/1000 chance that item won't be spawned 3 times in a row.

In my system, the % of success is fixed and slightly randomized between 0.75 and 1.25

So actually 90% of success means your success is randomized between

```
90*0.75 and 90*1.25 = 67,5 and 112,5%

```

***That success rate is added directly to entropy***

* Assume you have entropy starting at 13.
* You first roll makes the worst possible outcome 90% dropping chance 90\*0.75 = 67,5%
* You add to entropy so 13 + 67,5 = 80,5 (less than 100 =\> no drop)
* Regardless of what you next roll is you will be sure you will spawn the item (because 80,5+65,5 \> 100)
* So if you actually make again a worst roll, you have 80,5+65,5 =\> greater than 100.

Basically with this system you are sure that items are spawned randomly but without too much misses in a row.

Actually this system will never miss more than twice in a row (and it miss twice only 1 out of 1000 cases, when dropping chance is 90%), and will actually spawn 2 items sometimes, but in average it will spawn items equals to 90% of killed enemies. So it is likely on 10 killed enemies:

* 2 enemies don't spawn drop
* 1 enemy spawn twice the drop

Note that actually it is impossible that an item spawn twice if its **drop\_rate** is `<=` than 80%.

---

## Alternative approach

Just set a countdown counter for each drop, but you have to use a "out\_of" column instead of a "drop\_ratio":

**I.E:**

```
drop_ID |  out_of |  counter

```

So if you have that drop once out of 100 cases, you just randomize it by a +/- 5%

You just subtract 1, when counter reaches 0, you randomize it again.

```
if( --drop.counter <=0)
{
    DropItem( drop.drop_ID);
    drop.counter = drop.out_of*Random(0.95,1.05),
}

```

While this approach is simpler, that does not allow to handle spanw chances greater than 100%.

# Answer
> 2 votes
There are 2 scenarios you want to avoid, a player doesn't get a rare drop in 1500 kills and a player gets 5 rare drops in a row. Neither is fun™ to experience. Never getting a rare drop is frustrating and getting cheesed by your own luck robs you of the satisfaction that can only come after working for the reward.

So you'll want to set the drops in relation to longer periods of time. For example in a 1 hour grinding session the player should get between 2 and 5 medium rare drops, he has a 25% of getting a single super rare drop. (numbers are examples, this kind of thing needs very careful tuning).

Instead you can set counters on how often rare items get dropped. When a monster gets killed and you select the drops you can change the item pool based on previous drops the player received; as the last rare drop is further and further in the past you can increase the chance of the player getting another one.

---
Tags: rpg, mathematics
---


title: Instancing effectiviness

text:
# Question
Title: Instancing effectiviness
At about how many instances would instancing become effective? DirectX dynamic buffers seem to take a little more out of the fps than an immutable one would. So obviously you wouldn't want to make a dynamic buffer for one mesh. What about two or three? I realize there's probably many variables to take into account but just to get a grasp on it?

# Answer
> 1 votes
Your best bet with these kind of questions is to implement it and see on your target/example hardware how it works out.

For Direct3D 11, you can try out the InstancingFX11 sample from MSDN Code Gallery.

# Answer
> 0 votes
First, instancing will save you only CPU cycles.

You can get most of performance when drawing thousands of small meshes (e.g. 100 triangles). So it's useful for sprites, particles, trees in distance etc.

Bigger meshes save you same amount of CPU cycles as small, but overall impact isn't that great, because you won't be drawing thousands of them.

It's good idea to create immutable vertex buffer with instances for static and sleeping objects (not moving). You can use UpdateSubresource to update it occasionally.

For moving objects, it's good to use either dynamic vertex buffer or just constant buffer. One constant buffer can store up to 1024 world matrices. You can put material data into separate constant buffer...or not.

For moving objects, you update your constant buffers anyway. With instancing, you'll do just one big update and one draw call per batch. Overall impact should be positive even for small number of objects. You move same data from CPU to GPU in same way (to CBs) and render same objects, but with lower number of DirectX calls.

**Is it worth it?**

It depends how much CPU time you spent rendering objects and how many instances of same objects you're rendering.

Lets say you render 5000 objects and it takes 10ms. There are 500 different objects. Theoretical improvement is 9ms (you go from 5000 batches to 500 batches).

But it won't be so good, you still need to move the same amount of data from CPU to GPU. Also, when rendering 5000 objects, you might sort them to reduce render state changes (if you sorted by shaders, there was only 500 SetVertexShader/SetPixelShader calls and 5000 draw calls).

Based on conditions above it's realistic to expect 5 - 8ms improvement for our case.

---
Tags: c++, directx, instancing
---


# Question
Title: How to license free assets but prevent asset flipping?
I'm a hobbyist prop artist and give away everything I make for free, even for commercial use. At the moment I use the CC BY 4.0 license which is great except for the fact that someone would be able to download my assets and sell unmodified for a profit.

Ideally, I would like a license where you are free to download and use my assets for free but can only be used for commercial purposes where the assets are not the primary focus of the product e.g. included as part of a game.

Does anyone have any experience here about how best to achieve this?

# Answer
> 1 votes
Whether an asset is in "primary focus" is a fairly subjective criterion, which is difficult to capture in a license text. You could crayon one and have it checked by a lawyer, but crayon licenses have the usual potential pitfalls.

I would suggest releasing them with CC BY-NC 4.0 (the "NC" stands for "non-commercial"), and also advertising that you provide free commercial licenses on a case-by-case basis.

Doing this *would* partially defeat the point of a public license—by making all potential commercial users have to contact you—*but* you could then easily vet all applicants yourself by your criteria, without having to figure out how to translate them into legalese and worry about whether you did so correctly.

---
Tags: licensing
---


# Question
Title: How do I stop Unity's default FPS Controller from keeping momentum?
Unity's default FPS Controller keep momentum after you let go of the keys. Once you are up to full speed with WASD and let go, it continues to move for a bit.

How do I stop this momentum? Immediately upon letting go of the keys, I want the character to stop.

I am looking into the script already, but I am new to Unity. If someone can point me to what I am looking for, please do!

P.S. It appears it may be due to a connection to GetAxis which has built in momentum. https://docs.unity3d.com/ScriptReference/Input.GetAxis.html

# Answer
> 3 votes
The answer is using `Input.GetAxisRaw` instead of `Input.GetAxis`:

*"Returns the value of the virtual axis identified by axisName with no smoothing filtering applied. The value will be in the range -1...1 for keyboard and joystick input. Since input is not smoothed, keyboard input will always be either -1, 0 or 1. This is useful if you want to do all smoothing of keyboard input processing yourself."* \- https://docs.unity3d.com/ScriptReference/Input.GetAxisRaw.html

I tried it in my game demo and it worked. As soon as you let go of WASD the character stops, exactly as you would expect.

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


# Question
Title: How do I know if memory isn't being handled right?
My (2D) game's memory footprint seems to increase any time I load a texture, e.g. when I start my game it uses 30 mb private RAM, after transversing a ~367mb background file, so it's all in RAM at some point, it increases to 54 mb private RAM.

The same thing happens after going the same distance but going back and forth between two points repeatedly.

However, my readouts are showing that the program is correctly calling glDeleteTextures about a second after textures go off screen; and valgrind isn't finding any leaks.

How do I know if I should be worried about this, or if it's just a quirk of how the OS pages memory?

# Answer
> 21 votes
Virtual memory is allocated from the OS in large chunks, when even a byte is left still in use in that large chunk it cannot be released back to the OS.

Allocation libraries in user-space also keep a certain amount for re-use to avoid repeatedly demanding and releasing memory from/to the OS which is extremely slow.

E.g. you allocate a texture, the OpenGL driver reserves a table of 32 texture slots, you keep allocating textures, the driver then needs to allocate a larger table of 1024 texture slots this new table is now taking space in the large chunk of RAM, you free all the textures, the driver isn't shrinking nor re-allocating that table in the expectation that your game/application will need to use as many textures later so that large chunk of RAM cannot be released back to the OS.

This is perfectly normal and wanted. The unused RAM will be re-used eventually by your app.

---
Tags: opengl, memory
---


# Question
Title: How can I roll N dice in constant time and preserve a binomial distribution?
If I want to throw a 100d6, I have to:

```
int sum=0;
for(int i=0; i<100; i++)
    sum += Random.BetweenInclusive( 1, 6);

```

But for high dice count it may be expensive.

Does there exist any algorithm that is able to throw many dice with an algorithm that always require the same time (it is CONSTANT in the number of dice) and that will still produce a binomial distribution?

The goal is to write a function that:

```
int RollADice( int rolls, int faces)
{
    if( rolls <1245) // constant determined by profiling
    {
        int sum=0;
            for(int i=0; i<rolls; i++)
                sum += Random.BetweenInclusive( 1, faces);
        return sum;
    }
    else
    {
        return RollArbitraryDice( rolls, faces); // how would be that function?
    }
}

```

The only progress so far is throwing 2 dice at the same time (by noting that the distribution of 2 dice is a linear ramp, so we could cut the ramp in the middle and get a rectangle).

I also found an algorithm that does roll many dice preserving entropy, but it actually have a cost that is binomial on number of dice, not really a good trade (unless you need entropy).

# Answer
> 1 votes
Rolling dices approaches a normal distribution as explained in this answer : https://math.stackexchange.com/questions/397689/why-convolution-regularize-functions/398146#398146

So for n \> 1245 I believe you can safely use that distribution!

You can then just generate a random number in that distribution using the Muller Transform

---
Tags: optimization, random
---


title: Equation for bouncing graph?

text:
# Question
Title: Equation for bouncing graph?
I basically want my camera in 3D move automatically. Currently, I have linear movement which is rather dumb, so I'd like to do a bouncing movement.

However, what is a good equation for bouncing? I mean, for a circle you can do `y = sqrt(1 - x^2)`, but if I were to have a bouncing graph, what would the corresponding formula be? I guess it's something with `abs` as it has to 'bounce'. Something like (I made this up with Paint):

What is a good equation that results in such a graph? The transformations I can do myself I guess, but I'm just looking for the *kind* of equation.

# Answer
> 8 votes
Using a graphical equation will not help you apply natural looking accelerations to the system. You may be surprised to find how easy it would be to simply use basic Newtonian equations here. Give the object a little mass and momentum and let the force of gravity and Newton handle the accelerations & position changes. It's far easier than you may think

# Answer
> 4 votes
Instead of providing a direct answer I want to point you in the right direction. If you google for AI for moving entities you will find algorithms using variables like speed, mass, velocity and accerelation. If you add the gravitational force into the equation you should get realistic behaviour.

As stated in one of the comments to your questions it is not that complicated.

I recommend Programming game AI by example which I found very helpful.

I also found this link explaining the forces involved for a bouncing ball.

# Answer
> 3 votes
If your movement should look a lot like your graph, you could make use of a bounce easing equation like this one (source):

```
// BOUNCE EASING: exponentially decaying parabolic bounce
easeOutBounce = function (t, b, c, d) {
    if ((t/=d) < (1/2.75)) {
        return c*(7.5625*t*t) + b;
    } else if (t < (2/2.75)) {
        return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
    } else if (t < (2.5/2.75)) {
        return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
    } else {
        return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
    }
};

easeInBounce = function (t, b, c, d) {
    return c - Math.easeOutBounce (d-t, 0, c, d) + b;
};

```

The movement would look in this graph (easeIn):

# Answer
> 2 votes
If you are looking for an equation closely but roughly describing a bounce, you can try:

```
y=(e^-x)*abs(4cos(5x))

```

where

* "4" is the coefficient for the height of the drop and subsequent bounces,
* "5" is the frequency of the bounces, and
* the "abs" part is to give a sharp trajectory to the lower part of the bounce.

# Answer
> 1 votes
If you want bouncing then look into the Coefficient of Restitution. It's a value between 0 and 1 that represents the "bounciness" of the camera. A value of 0 means that no bouncing will occur when the object collides with the ground, and 1 means that the camera will bounce back up to it's original height after it has collided with the ground (in this scenario anyway).

The easiest way to implement it is to give your camera an initial velocity vector (call it u) and you want to find the final velocity vector after the camera has collided (lets call this v). Lets call the CoR e.

e = v / u

So all you need to do is multiply your initial velocity by the coefficient, negate this velocity (for it to travel in the opposite direction) and voila, you have your final velocity and if you keep doing this for every time it collides, you have your bouncing motion. This is assuming you have a flat plane that you want to bounce against, if you have a complex mesh you're colliding against, then instead of negating the vector, simply multiply it by the normal of the polygon you collide with (which is essentially what negation does on a flat plane).

Use some sort of position update function (Euler, Verlet or even RK4 - see this link) and it will make this task a lot easier.

Hope that helps (and I hope my maths isn't too far off :P)

---
Tags: 3d, mathematics, camera, movement
---


# Question
Title: How does one model the sun in a ray tracer?
How is sun modeled when doing ray-traced rendering? Is it part of the scene, like a sphere with a centre in some far location or it is just considered as a point?

Also regarding sending shadow rays to the sun, is it, again, sampling a sphere or just sending shadow rays to one point?

# Answer
If you take sun as a point, you can not have shadows smoothing/blurring for tall objects. Notice how due to measurable sun angular size, the sahdow gets smoother/blurry the farther it lies from the runner:

For simplicity you can assume sun is a luminous disc facing your scene, placed far far away.
> 2 votes

---
Tags: shadows, raytracing
---


title: Help understanding camera/scene Unity

text:
# Question
Title: Help understanding camera/scene Unity
I'm a brand new unity developer and I watched a few tutorials and then found a game on the Asset Store to provide a nice base for my game. However the setup, especially with multiple scenes is quite different than the tutorials I watched and I can't figure out what is happening. Here is my Scene view from the main menu:

When I click on Main Camera the tiny little thing with the green outline in the corner is highlighted.

Now if I click play, that whole menu fits in the screen, even though the Main Camera is apparently tiny? Then, while playing, I click back to scene view I see this:

It shows the camera as being empty, even though in Game View I can see/interact with the menu.

When I swap to my Scene 1, which is the game view, it is the exact opposite. This is what I see in Scene View while the game is playing:

Note the game running in the preview in the corner. Those tiny circles are the same circles on the main menu, how does the same asset fit in what appears to be two wildly different sizes?

So I ask, what is the different between the two scenes. One appears in the preview while one doesn't. One fills in the huge canvas while the other apparently fits in the tiny camera. What am I missing?

# Answer
This is the difference between the UI and the in world objects. Your main menu is a screen space UI, the rest of your objects are in world objects, likely sprites.

The reason they're vastly different sizes is just how the editor displays their size. The main menu (UI) has its size based on pixels. Maybe something like 1080x1920. The world objects have their size based on world units. Probably something like 1 unit across for those little circles (wild guess, impossible to tell with the information provided).

Now, in game, these will both look just fine. In the editor, it's going to display the UI using the UI size, except it's going to interpret those values as world units. In other words, it's going to convert pixel units into world units. That means your UI, which is 1080 pixels across, is now going to be 1080 world units across. That's more than 1000x bigger than your game objects.

So, what to do about it? You can change the scale of your main menu. This won't affect the on screen size, but it will change the in editor size. So, for example you could scale your main menu to .0075 on the X, Y and Z axes. It'll still be the same size in pixels, but will be scaled in the editor to be closer to the same size as your in world objects.
> 4 votes

---
Tags: unity, 2d, camera, scene
---


# Question
Title: Best approach to render text in OpenGL 4.5
I have tried to implement text rendering in OpenGL from several tutorials and guides but I am unable to implement any of them successfully.

The latest one I have attempted is \[Here\] but it seems to be incompatible with GL 4.5. My end goal is to implement the ability to load TTF files into OpenGL and render them. If someone could give me a hand with a sample code snippet of how to implement this myself, or even to reconfigure the free type library, that would be appreciated!

# Answer
> There are three approaches to rendering fonts in OpenGL: bitmap, outline (polygonal), and texture mapped. Each method has its own advantages and disadvantages.

Source: https://www.opengl.org/archives/resources/features/fontsurvey/

Choosing a method depends on how you want your text to be displayed. If you need your text to be easily scaled and rotated, and you care about performance, use bitmaps. If you want your text to be antialiased, without the hassle, use outlines. Basically, you're just drawing polygons with many points, so the resolution is fully customizable. You can also integrate texture mapping with this method.

If you would rather use a library, check out FreeType.
> 1 votes

# Answer
I'm afraid that using the FreeType is the only way to do what you want. Even DirectX needs font as a texture. Why do you want to 'reconfigure' the library, and what does it mean to you?
> 0 votes

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


title: glDrawElements not acting as expected

text:
# Question
Title: glDrawElements not acting as expected
code

Vertices are created by an .obj file. (`loading/OBJFile.java`)

I draw a cube perfectly fine with `glDrawArrays`. (`VertexModel.java`)
created like this:

```
new VertexModel(square.getIndexedVertexBuffer());

```

However, when I try to do the same with `glDrawElements` i get a distorted cube.. (`IndexedVertexModel.java`)
The IndexedVertexModel is created like this:

```
new IndexedVertexModel(square.getVertexBuffer(), square.getVertexIndecies());

```

The result can be seen here.
I've tried to figure out what's wrong, but i really have no idea what causes it to behave this way.

The OBJ file I'm using looks like this:

```
v -1.00000000000000 -1.00000000000000 -1.00000000000000
v -1.00000000000000 1.00000000000000 -1.00000000000000
v 1.00000000000000 -1.00000000000000 -1.00000000000000
v 1.00000000000000 1.00000000000000 -1.00000000000000
v 1.00000000000000 -1.00000000000000 1.00000000000000
v 1.00000000000000 1.00000000000000 1.00000000000000
v -1.00000000000000 -1.00000000000000 1.00000000000000
v -1.00000000000000 1.00000000000000 1.00000000000000

f 1/4/1 2/3/1 4/2/1
f 3/4/3 4/3/3 6/2/3
f 5/4/4 6/3/5 8/2/4
f 7/4/6 8/3/6 2/2/6
f 2/4/7 8/3/7 6/2/7
f 7/4/8 1/3/8 3/2/8
f 1/4/1 4/4/1 3/3/1
f 3/4/3 6/4/3 5/3/3
f 5/4/4 8/4/4 7/3/4
f 7/4/6 2/4/6 1/3/6
f 2/4/7 6/4/7 4/3/7
f 7/4/8 3/4/8 5/3/8

```

# Answer
> 0 votes
OBJ vertex index values starts at 1

OpenGL vertex index values starts at 0

Subtract 1 from your loaded indices:

```
vertexIndices.add(Integer.parseInt(innerpart[0])-1);
textureIndices.add(Integer.parseInt(innerpart[1])-1);
normalIndices.add(Integer.parseInt(innerpart[2])-1);

```

And remove the `-1` from your functions `getIndexedTextureBuffer` and the likes.

---
Tags: opengl, java, lwjgl
---


# Question
Title: Detecting internet Connection on Unity connection to serve ads
How can you detect someone's Internet connection in Unity? I see a lot of forums where people make a request to any site (mostly google.com) to check it, but it does not seem to be an elegant solution.

With 3G/4G connections to serve Unity ads or admob interstitial, it takes a lot of time and crashes the game.

Regards!

# Answer
> 1 votes
Unity or not, the principle is always the same: Do a (http) request to a well known server (or a few alternative ones) and conclude that "there is internet connection" only as the reply is safely back home and well grabbed.

The term "internet connection" can be interpreteted in different ways, but it always comes down to that *"almost internet connection"* or *"should be internet connection"* is worthless/irrelevant and hence equal to *"no internet connection"*. For example, it's worthless to know that the OS claims a connection is "up" - the connection must also be functional, and tested for that. It is also worthless to know that there is connection up to for example the 3rd hop, if that that hop still happens to reside in local, nearby infrastructure.

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


# Question
Title: Importing a File Containing Two Objects from Blender into Unity Leads to a Single GameObject Not Two
I have two separate objects in a Blender file (say a cube and a sphere). Unity import this file (OBJ type) as a single gameObject which is not want I want. I want cube and sphere to be two separate gameObjects.

# Answer
You must use separate OBJ files for this.

You could also import .blend files directly: https://docs.unity3d.com/Manual/HOWTO-ImportObjectBlender.html
> 1 votes

---
Tags: blender, obj, import
---


title: Check if two lists are the same

text:
# Question
Title: Check if two lists are the same
I'm currently trying to make a crafting system. For a little background I have a json file with crafting recipes. I check each of these recipes against the items I have in another list which holds the 4 items currently selected for crafting.

My current method is as follows:

```
private bool DoListsMatch(List<int> list1, List<int> list2)
{
    return list1.TrueForAll(list2.Contains) && list2.TrueForAll(list1.Contains);
}

```

At first this method looks like it's working. However, when I change the last item in the crafting window it still returns a result when it shouldn't. This suggests to me that the method is not working.

Is there any other ways of checking if lists match completely?

# Answer
The current solution works in a specific context, but there is further room for potential error. Without sorting the list, we should not *assume* a specific order; even if we have set it up in that way. Unaccounted logic or later changes may alter the order in *one* of the lists, which results in a false negative when comparing the elements of each list using a single index value.

The solution is fairly simple. Just sort the list, before you compare values in it. This is straight forward, if we are using `List<int>`; `int` values already know how to sort themselves, in a list. If we ever want the same functionality from a `List<t>` of custom types, we need to make use of the `System.IComparable<in t>` interface.

---

### Sorting a `List<t>`

We sort a `List<t>` with the method `List<t>.Sort()`. Sorting both lists before comparing values guarantees that *if* the lists both contain the same set of values, they will also be in the same order.

```
private bool DoListsMatch(List<int> list1, List<int> list2)
{
    var areListsEqual = true;

    if (list1.Count != list2.Count)
        return false;

    list1.Sort(); // Sort list one
    list2.Sort(); // Sort list two

    for (var i = 0; i < list1.Count; i++)
    {
        if (list2[i] != list1[i])
        {
            areListsEqual = false;
        }
    }

    return areListsEqual;
}

```

---

### Using `System.IComparable<in t>` to make custom types compatible with `List<t>.Sort()`

Should we want to perform the same function on a list that contains custom types, we need to add the `System.IComparable<in t>` interface to that type. This interface only contains one method that needs to be implemented in the class - `public int CompareTo(t other)`. This method compares the local type with the `other` type, and returns an `int` value representing the the placement of the local type in comparison to the `other` type.

For the example, I will simply use a custom class that stores an `int`. You can set this `CompareTo()` method up in any way you like, specific to the types you use inside that class. You may want to compare ID numbers, or compare distances to a particular position, or even a given name.

```
class MyInt : IComparable<MyInt>
{
    int value;

    public int CompareTo(MyInt other)
    {
        return value.CompareTo(other.value);
    }
}

private bool DoListsMatch(List<MyInt> list1, List<MyInt> list2)
{
    // ...
}

```

---

As a final note, with the use of a custom implementation of `int CompareTo(t other)`, it is worth considering the possibility of error if two unique `t` values can still compare with each-other as equal. If the same two values would not return a value of `true` when compared as `valueA == valueB`1, there is still a possibility of incorrect output, when comparing both lists. If `CompareTo()` returns a value of 0, the items will not sort in any particular order (in relation to eachother), in the list. As such, we can not guarantee the order of the list1.

1 If the two items *also* return `true` when compared using the `==` operator, the previous checks will still correctly identify the objects as equal, and this will be a non-event.

---
> 3 votes

# Answer
This worked for me:

```
private bool DoListsMatch(List<int> list1, List<int> list2)
{
    var areListsEqual = true;

    if (list1.Count != list2.Count)
        return false;

    for (var i = 0; i < list1.Count; i++)
    {
        if (list2[i] != list1[i])
        {
            areListsEqual = false;
        }
    }

    return areListsEqual;
}

```
> 1 votes

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


# Question
Title: Prevent perspective cameras from overlapping using multiple screens
I'm working on a shooting trainer project, where multiple cameras are placed beside each other to show a bigger range of environment. Each camera displays to a different screen. I find that the perspective cameras always show a part of each other, but I do not want those cameras to show part of each other's view.

How do I align my perspective cameras to show a unique view?

# Answer
To do this you will need to put each cameras in the exact same 3D location, write a custom projection matrix to each cameras so they render off-center (and set them to render to different screens if that's what you intend to achieve).

In your camera script:

```
void LateUpdate() {
    Camera cam = Camera.main;
    Matrix4x4 m =  Matrix4x4.Perspective(cam.fieldOfView, cam.aspect * 3.0f, cam.nearClipPlane, cam.farClipPlane);
    if(isLeftCamera){
        m[3, 0] = 2.0f;
    } else if(isRightCamera){
        m[3, 0] = -2.0f;
    } else {
        // middle camera, don't shift
    }
    cam.projectionMatrix = m;
}

```

This makes the camera render 3 times as wide `cam.aspect * 3.0f` and offsets the rendering to render the left, right or middle part `m[3, 0] = ...`
> 2 votes

---
Tags: unity, camera
---


title: How can I manage weapon recoil?

text:
# Question
Title: How can I manage weapon recoil?
I have some trouble to do a Recoil routine. I've a Tank, a turret cannon on it. I want that after shot, turret fast recoil back, than (slowly) get back to start position.

This is the code I've tought but obviously it not works.

```
Update () {
  if(shot) {
     Shot();
     TurretBackRecoil();
  }

}

private void TurretBackRecoil() {
   transform.Translate(new Vector3(0,-10,0) * Time.deltaTime * 3 );
}

private void TurretForwardRecoil () {
    transform.Translate(new Vector3(0,10,0) * Time.deltaTime);
}

```

# Answer
The way I have achieved this in the past is to track multiple different recoil variables. These can be changed on the fly, you could have one for visual kick back, one for a targeting offset.

Then, when before drawing the object, set its transformation matrix to be its default transformation plus offsets provided by those variables.

You can then animate those variables in any way you like, such as having it gradually return to 0.

(So if you set recoil=-10; on shoot, it will animate back).

The other benefit of this is that you can easily increase the effect of recoil, or stack the recoil intensity on top of each other by just increasing the variable more.
> 1 votes

---
Tags: unity, algorithm
---


# Question
Title: Movement-networking for a Worms-like game
I want to implement a strategy/artillery game, similar to Worms/Arcanists.

As game-development (and game-networking especially) is new to me, I was wondering whether this would be a good/performant way to do the movement-networking:

1. Server has all client's positions.
2. Moving-client to server:

Message: \[start-moving, moving-direction\]
3. Server now starts a simulation of the moving-client moving.
4. Server to all clients, except originating one, every 100ms(?):

Message: \[set-client-position: client-id, new-position\] ^ new-position calculated by the server's simulation
5. Clients lerp the moving-client's position.
6. Moving-client to server:

Message: \[stop-moving\] ^ server's simulation ends
7. Server to all clients, including originating one:

Message: \[set-client-position: client-id, final-position\] ^ all clients have the same position for the moving-client in the end

# Answer
> 1 votes
I would also have the client send its absolute position to the server as well. The server can still simulate the movement if you desire, however this is useful to prevent the two positions getting out of sync with each other due to subtle differences in the collisions at different locations.

What the server can do is trust where the client is telling it the worm is, unless it suddenly jumps too far, in which case, if the server disagrees with the clients position, it can send the expected client position back to the original client (as Steve suggested). This is why games often experience rubber banding.

I personally prefer trusting the clients position, as it leads to a higher degree of accuracy. You should still send the direction/velocity, for simulation purposes between frames.

---
Tags: networking, movement-prediction
---


# Question
Title: SDL2 sprite batching and texture atlases
I have been programming a 2D game in C++, using the SDL2 graphics API for rendering. My game concept currently features effects that could result in even tens of thousands of sprites being drawn simultaneously to the screen. I'd like to know what can be done for increasing rendering efficiency if the need arises, preferably using the SDL2 API only. I have previously given a quick look at OpenGL-based 2D rendering, and noticed that SDL2 lacks a command like

```
int SDL_RenderCopyMulti(SDL_Renderer* renderer,   SDL_Texture* texture,
                        const SDL_Rect* srcrects, SDL_Rect* dstrects,   int count)

```

Which would permit SDL to benefit from two common techniques used for efficient 2D graphics:

* **Texture batching:** Sorting sprites by the texture used, and then simultaneously rendering as many sprites that use the same texture as possible, changing only the source area on the texture and the destination area on the render target between sprites. This allows the encapsulation of the whole operation in a single GPU command, reducing the overhead drastically from multiple distinct calls.
* **Texture atlases:** Instead of creating one texture for each frame of each animation of each sprite, combining multiple animations and even multiple sprites into a single large texture. This lessens the impact of changing the current texture when switching between sprites, as the correct texture is often ready to be used from the previous draw call. Furthemore the GPU is optimized for handling large textures, in contrast to the many tiny textures typically used for sprites.

My question: Would SDL2 still get somewhat faster from any rudimentary sprite sorting or from combining multiple images into one texture thanks to automatic video driver optimizations? If I will encounter performance issues related to 2D rendering in the future, will I be forced to switch to OpenGL for lower level control over the GPU?

**Edit:** Are there any plans to include such functionality in the near future?

# Answer
SDL2 doesn't *need* any functionality to be added for either of those items.

**Texture batching**

You yourself can sort the sprites by texture used. The SDL backends can already do draw call batching if they wish to (nothing requires that the `Copy` command be executed immediately; the only requirement is that it be executed by the time any side effects are required, such as by the end of a `Present` or if you try to read from the destination or if render/blend state is changed).

In order to sort draw calls, a renderer needs a lot more additional information such as layering information, draw state (blending, etc.) and so on. SDL2 certainly *could* offer something similar to XNA's `SpriteBatch`. You can already do that today on your own, though, so it's hardly necessary for SDL2 to do it in order for you to obtain the best performance.

**Texture atlases**

Nothing in the world is making you put one frame of animation on distinct textures. The draw commands take a source rect. Use a different source rect (on the same texture) for each frame of your animation. You're already aware of the source rects so it's unclear to me why you would think something needs to change.

SDL2 doesn't itself offer a texture atlas abstraction layer which is perhaps what you meant. It's your job to know that a particular frame of a sprite animation is at a certain location within a texture. An abstraction can be built that lets you operate on a `SubTexture` that encodes its `SDL_Texture` and source rect and your `SpriteBatch` can work from there. My (non-SDL) sprite batching class has methods something like:

```
class SpriteBatch {
public:
  // when we know the specific texture and source rectangle
  void Draw(TextureHandle tex, Rect source, /*...*/);

  // helper for drawing a whole texture
  void Draw(TextureHandle tex, /*...*/) {
    Draw(tex, Texture_SizeOf(text), /*...*/);
  }

  // helper if we have an atlas and a specific index of a sub-texture therein
  void Draw(TextureAtlasHandle atlas, int index, /*...*/) {
    Draw(TextureAtlas_TextureOf(atlas), TextureAtlas_RectOf(atlas, index), /*...*/);
  }

  // helper if we have an abstract sprite handle without details about a specific atlas
  void Draw(SpriteFrameHandle sprite, /*...*/) {
    Draw(SpriteFrame_SheetOf(sprite), SpriteFrame_IndexOf(sprite), /*...*/);
  }
};

```

That's obviously "paraphrased" a bit, but you get the gist.

That `SpriteBatch` can handle your sorting requirements as well as making it trivial to deal with atlases and single-texture animations.

> Are there any plans to include such functionality in the near future?

This question is better suited for libsdl.org's SDL Development Forum which is frequented by many/most of the SDL developers.
> 10 votes

# Answer
SDL2 can handle these things. As previously stated you need to make a engine to load the image, the sprite rect or poly, and you could even tie into this a animation frame que to this. I pushed well into 1k sprites and collision detection between each of them and the system did not even blink. And AND that was with the basic software rendering SDL2 renderer setup under Windows 10. I since have changed it to accelerated graphics and regulated the frame rate and it isn't even pulling more than 2% of the processing. Memory allocation is very small from what I have seen with SDL2, the only obvious memory hog in this is the size of the sprite(s) sheet(s) which are loaded.

Another thing which helps with this greatly I have found. Make a camera class, have it control a source rect, destination rect, and also insert a SDL\_Texture into that and on object construction and deconstruct build the texture into a large view area. This not only works well for keeping track of what you are rendering and culling the non-visible but it also double buffers with the system. On the rendering segment of the game loop; change renderer to the camera, render the layers you need to it, swap back to the window renderer and render the full camera texture to the window, present and it is smooth and organized.

If you are making a 2d game using SDL2 sprites are the heart of the whole engine/game. All other things such as UI, events, physics, update (collision/states) are the fun parts to change after the sprite system is read to load on init or on the fly and able to call a fast sprite rect, modify flip/color blend/alpha and push quick to the double buff texture. If you focus on the sprites you can make a robust game which can be changed easily and have a whole different feel.
> 1 votes

# Answer
I'm also making a game, 2.5D, and I use texture atlases. Like OP said, creating a single large texture from individual sprites can speed up the process for each frame. The only flaw with this is that there **cannot be any moving parts in the larger texture.** This method is best used for static backgrounds/foregrounds or anything else that remains the same from level start to end.

I'm using the original SDL, not SDL2, and as far as I know, neither has a built-in implementation of this method. However, if you simply use:

```
SDL_Surface* static_background = SDL_CreateRGBSurface(Uint32 flags, int width, int height, int depth, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask);

```

(or set it to a NULL pointer and then blit some texture to it) you can create a surface of size width x height to use as your large image. You may want to set the default color to a colorkey and remove it later, unless you intend to make a wholly opaque image with no holes.
> 0 votes

---
Tags: textures, sprites, sdl, spritebatch, texture-atlas
---


# Question
Title: Why does the shader compiler reorganize my code in loops and branches?
I noticed something strange while inspecting my compiled shader assemblies, that if I put some buffer loads inside an if statement or a loop, then the resulting assembly will be organized much differently then if outside a branch or loop.

Consider this example:

```
StructuredBuffer someBuffer<Type>:register(t0);
// ...
float4 pos;
// ...
if (statementIsTrue)
{
  float4x4 world = someBuffer[index].matWorld;
  pos = mul(pos, world);
}

```

The mul gets compiled to something like this:

```
0x000000B8:   ld_structured_indexable(structured_buffer, stride=128)(mixed,mixed,mixed,mixed) r0.yzw, r0.x, l(4), t0.xxyz
0x000000E4:   ld_structured_indexable(structured_buffer, stride=128)(mixed,mixed,mixed,mixed) r1.xyz, r0.x, l(20), t0.xyzx
0x00000110:   ld_structured_indexable(structured_buffer, stride=128)(mixed,mixed,mixed,mixed) r2.xyz, r0.x, l(36), t0.xyzx
0x0000013C:   ld_structured_indexable(structured_buffer, stride=128)(mixed,mixed,mixed,mixed) r3.xyz, r0.x, l(52), t0.xyzx
0x00000168:   dp3 o0.x, v0.yzwy, r0.yzwy
0x00000184:   dp3 o0.y, v0.yzwy, r1.xyzx
0x000001A0:   dp3 o0.z, v0.yzwy, r2.xyzx
0x000001BC:   dp3 o0.w, v0.yzwy, r3.xyzx

```

Then when I leave the `if` branch, the whole thing just gets reorganized:

```
0x00000090: ld_structured_indexable(structured_buffer, stride=128)(mixed,mixed,mixed,mixed) r1.xyzw, r0.x, l(0), t0.xyzw
0x000000BC: dp4 o0.x, v0.xyzw, r1.xyzw
0x000000D8: ld_structured_indexable(structured_buffer, stride=128)(mixed,mixed,mixed,mixed) r1.xyzw, r0.x, l(16), t0.xyzw
0x00000104: dp4 o0.y, v0.xyzw, r1.xyzw
0x00000120: ld_structured_indexable(structured_buffer, stride=128)(mixed,mixed,mixed,mixed) r1.xyzw, r0.x, l(32), t0.xyzw
0x0000014C: ld_structured_indexable(structured_buffer, stride=128)(mixed,mixed,mixed,mixed) r0.xyzw, r0.x, l(48), t0.xyzw
0x00000178: dp4 o0.w, v0.xyzw, r0.xyzw
0x00000194: dp4 o0.z, v0.xyzw, r1.xyzw

```

Also notice how the dp3 instructions got changed to dp4s, which is also confusing to me.

This also happens with loops. Unrolled loops however act like the second case without the brach.

What could be the reason behind it all and does it matter?

# Answer
The HLSL compiler like any compiler tries to optimize code by applying various kinds of code analysis, peep hole optimization, etc. You can try playing around with optimization settings, but fundamentally the compiler is trying to make the best code it can.

Remember that branches can have a huge impact on the efficiency of shaders, particularly dynamic branching. HLSL has some attributes you can use to control how conditional branches are handled: `[branch] if` or `[flatten] if`. See MSDN.

In loops, you can use `[loop] for` or `[unroll] for`. See MSDN

When doing matrix multiplies, you can do them either with `dp3` or `dp4` depending on the memory layout. Generally for column-major (the default for HLSL), it can use fewer `dp4` instructions.

Code-generation will also depend on your target shader profile.

**In short, it does matter but you shouldn't worry about it.**

> If you really want to get into the nitty-gritty of the HLSL compiler, you might want to check out this GitHub project for the new LLVM/Clang-based Shader Model 6.1 HLSL compiler for DirectX 12.
> 2 votes

---
Tags: directx11, hlsl
---