# Question
Title: How to program an attack that I control with the arrow keys?
I'm making a 2D game prototype in Unity and I want to have the player attack be a sword that hovers around the player with its direction being fixed to the direction you indicate with the arrow keys. So if the sword is in the upward position and you press the left button, you can see the arc it takes and an enemy in the way of that arc takes damage.

The game is not a platformer. It's on a flat surface.

**edit:** I want to know how to have the sword hover in a radius to the player and point the direction i press the arrow keys. I want to get the action of moving the sword to these positions to do damage to an enemy. But if the sword is in a upwards position and the player presses down, I want it to do an action that attacks the whole radius around the player, on a cooldown.

How would I go about programming this? I'm new to programming so I would greatly appreciate some helpful pointers.

**Edit2:**

So this is how far I have gotten: public class SwordSwing : MonoBehaviour {

```
public Transform swordHolder;

// Update is called once per frame
void Update ()
{
    if (Input.GetKeyDown(KeyCode.LeftArrow))
    {
        swordHolder.transform.Rotate(0, 0, -90);
    }

    if (Input.GetKeyDown(KeyCode.RightArrow))
    {
        swordHolder.transform.Rotate(0, 0, 90);
    }

    if (Input.GetKeyDown(KeyCode.UpArrow))
    {
        swordHolder.transform.Rotate(0, 0, 90);
    }

    if (Input.GetKeyDown(KeyCode.DownArrow))
    {
        swordHolder.transform.Rotate(0, 0, -90);
    }

}

```

I don't know if this is right, because when I use the arrow keys it just turns the sword 90 degrees and not to the specified position I want it to move to.

So Candid Moon said that I have to use Mathf.Lerp() and StartCoroutine() but I have no idea how to use them. I'm not really sure how to animate this either, I have done some animations in Unity but have a hard time implementing them into anything.

The hierarchy is now:

Player \> SwordHolder \> Sword

Now I also have this script:

```
if (GetComponent<Rigidbody2D>().velocity.x > 0)
        transform.localScale = new Vector3(1f, 1f, 1f);
    else if (GetComponent<Rigidbody2D>().velocity.x < 0)
        transform.localScale = new Vector3(-1f,1f,1f);

```

That flips the player sprite when i move left. This also flips the sword, I don't really want this. How do I stop it?

Let me know if there is anything I missed, I'm trying to learn.

# Answer
You should calculate the projection of distance vector to your enemy onto `transform.forward` vector (Vector3, front of z axis). You just have to save players `transform.forward` before rotating player. After rotation use Physics.OverlapCircle with radius of your attack and check if projection of enemy distance vector onto both current `transform.forward` and the one you saved. Are separately greater than 0 for every enemy you are going to hit. You need both vectors because I understood that you need only 1/4 of the whole circle. And that means that if your player was looking at `Vector2(0, 1)` direction and turned left, it means it only affects that 1/4 part between `Vector2(0, 1)` and `Vector2(-1, 0)`. So if your enemy is standing for example on `Vector2(0.3, 1)`, the projection onto `Vector2(0, 1)` will be `proj > 0`, but it's projection onto `Vector2(1, 0)` will be `proj < 0`. Same for the other part, and the last part both will be `< 0`.

Here is the answer on how to calculate the projection to give you return values between -1 and 1: Projection

**@@@ Update @@@**

I update my answer due to your comment. So you actually want not to calculate the area of effect, but hit your enemies with the collision system and you don't know how to implement the swinging in the direction. Well in this case it's simple.

1) You can write the sword swinging in the script. Just make the sword to be a child object of your player, change it pivot to be further from sword if you don't see sword or better make another empty gameobject (from now I will call it **swordHolder**). **Sprite rotates around it's pivot.**

So now all you have to do is to rotate sword in the direction that your player pressed the button. Something like if he presses left - `swordHolder.transform.Rotate(0, 0, -90);`. Make some trail effect for your sword to have a good swing look. Then simply add some box collider if you want it to calculate everything physically accurate and use `OnCollisionEnter2D(Collision2D other)` \- call in this function methods that damage your enemies (not like in example I described above, there it affects every enemy immediately).

**Objects should have Rigidbody2D attached in order to check for collisions with them. You can make them Kinematic if you don't use gravity and other physical stuff.**

`public class Sword : MonoBehavior
{
void OnCollisionEnter2D(Collision theOneWhoTouchedTheSword)
{ Enemy enemy = theOneWhoTouchedTheSword.collider.GetComponent<MyEnemy>();
if(enemy != null) { enemy.TakeDamage(swordAttackDamage) } }
}`

2) You can make 4 animations of sword swinging and call the right one instead of rotating it in script, but the `OnCollisionEnter2D(Collision theOneWhoTouchedTheSword)` should be there anyway and it will check for collisions anyway.
> 0 votes

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


# Question
Title: How to calculate verticle normals of triangular mesh
I'm playing with some terrain generation. I have a triangular mesh that looks OK - that is if I hardcode verticles normals (on this image every single verticle has normal of (0,-1,0)

The situation is different when I try to calculate normals normally. I.E.

```
// for every vertex in triangle normal is
private Vector3D GetNormal(Vector3D a, Vector3D b, Vector3D c)
{
    //return new Vector3D(0, -1, 0);
    return (c - b).CrossProduct(a - b).Normalize();
}

```

In this case I end up with

Is something fundamentally wrong with my approach ? I've read that vertex normals should take into account adjected triangles (sum of adjected triangles normals normalized by area those triangles have), but I don't think my "simplistic" approach should create those weird holes. Sources (if anyone is interested: https://github.com/svejdo1/Delaunay)

# Answer
It looks like some normals are pointing the wrong way. This means that those triangles aren't wound correctly.

As a quick fix you can do:

```
Vec3 norm = (c - b).CrossProduct(a - b).Normalize();
if(norm.y < 0) //or whatever direction up is
    norm = -norm;
return norm;

```

A better fix would be to debug your triangulation code and make sure that the order of vertices are consistent.
> 3 votes

# Answer
There's an error in your maths. You should use the cross product between two vectors with the same start position, but one of your vectors goes from `b` to `c`, the other goes from `a` to `b`. You need to change the line to

```
return (c - b).CrossProduct(a - b).Normalize();

```

If you're still having trouble, then normalize the 2 vectors before using the cross product.
> 1 votes

---
Tags: c#, monogame, 3d-meshes, normals
---


title: RPG Chance to Dodge formula

text:
# Question
Title: RPG Chance to Dodge formula
A friend and I are trying to develop a “chance to dodge” formula that will scale from level 1-1000. I would like to see if one formula can be utilized, using a difference ratio between Character A’s level and Character B’s level. The factors involved in the equation are as follows:

Dexterity (Max 38)

Acrobatics Skill (up to 5 possible skill points)

The equation in theory:

`(Acrobatics Skill * 5) + ((Dex - 10) * 0.1) + ((CharacterB's Level - CharacterA's Level) * 0.1)`

The formula has been varied a little to make it work better in one regard which has the inverse effect of making it not work in another area. For example, the formula may work and scale well if a lvl 700 is striking at a lvl 1000. Let’s say that works out that Character B has a 65% to dodge. Sounds good…..except if the same formula is applied to a lvl 5 is striking a lvl 20 (low levels).

We don’t want there to be a 100% chance to block. Then again, I guess if a level 1 struck at a level 1000, that would be a little bit ridiculous that he would succeed. But once again, it would be nice if there was a way to scale the entire level spectrum by use of perhaps cosine and the difference-between-level’s ratio.

# Answer
> 1 votes
It all depends on how you want your function to scale:

Seems you need a function of `AttackerLvl/DefenderLvl` and something like `1/x` for scaling it, or maybe a function of `DefenderLvl/AttackerLvl` and scale it according to a `sqrt( x)` or `x^2` function. The only stuff you have to be cautios about is to make sure those functions intersects the starting and ending points that you desire:

**In example:**

* You may want to scale it so that at Maximum attacker level( 1000) minimum defender level(1) the dodge chance is minimal (5% / 0.5% / 0.1%)
* You may want to scale it so that at Minimum attacker level(1) and maximum defender level(1000) the dodge chance is maximal ( 95% / 99.5% / 99.9%)

So in example if you want to go with `sqrt(x)`

You have to solve the system first:

* **Equation1:** a\*sqrt( 1000+b) = 0.95
* **Equation2:** a\*sqrt( .001+b) = 0.05

and find out what "a" and "b" values are.

In this case:

```
// return a number between 0.05 and 0.95
double dodge_chance_on_level( double defender_level, double attacker_level)
{
    double x = defender_level/attacker_level;
    double a = 10.0/ sqrt( 111111.0);
    double b = 111071.0/ 40000.0;
    return a*sqrt( x+b);
}

```

Don't warry, you don't need to be profitable in math, you just need to copy paste those equations into a non-linear system solver.

The output for the function is:

```
dodge_chance_on_level(1000,1)=0.95
dodge_chance_on_level(100,5)=0.143175
dodge_chance_on_level(20,10)=0.0655675
dodge_chance_on_level(10,20)=0.0543056
dodge_chance_on_level(5,100)=0.0504391
dodge_chance_on_level(1,1000)=0.05

```

Seems not very clever, but you just have to use another function (probably a linear function will works better in your case: it all depends on what you want, I just showed how to develop your own function).

Then you want also to design a function that scale with Dexterity and add the result to dodge chance.

# Answer
> 1 votes
Have a look at the Logistic Function (family). It maps the entire number line into `[0, 1]`, which is exactly what you want for a probability.

Something like `1 / (1 + exp(M1 + M2 * (Defender's Level - Attacker's Level) - M3 *(Attacker's Accuracy) + M4 * (Defender's Dodge)))`, for some `M1`, `M2`, `M3`, `M4` such that the "Equal levels" hit chance is where you want it, and your other parameters are worth a sensible "level difference"

# Answer
> 0 votes
Try using speed too. Just a suggestion:

`(k1*attacker_speed + k2*attacker_dexterity)
/
(k3*target_acrobatics + k4*target_dexterity) * target_speed`

`k1`, `k2`, `k3` and `k4` are values based on how much you want these values to increase depending on character level. I suggest you to change probabilities by using attack speed and range, changing it to:

`(k1*attacker_speed + k2*attacker_dexterity) * attack_speed/attack_range
/
(k3*target_acrobatics + k4*target_dexterity) * target_speed`

# Answer
> 0 votes
there's easy formular, think easy :D

```
accurate = A.dex * 0.1;
evasion = B.dex * 0.05 - totalWeight(items)*0.5;
chance = ((accurate - evasion)/accurate)*100;
if(chance < 0)
     return miss;
else if(random(100) > chance)
     return miss;
else
     return hit;

```

---
Tags: rpg, mathematics
---


# Question
Title: How would you generate details like trees, water or caves in a 2D terrain?
Yesterday I made a post about generating a 2D planet, which resulted in this:

I did it by subtracting a radial gradient from simplex noise (explained in my other post).

Now of course thats a bit boring, what technique should I use to add details like trees, lakes or caves? Would be able to do something like this (but of course across the whole planet):

I know doing it on a planet would make it a bit harder, because you would have to know if f.E. the tree is on the north of the planet or the south. To make it easier, if you want, just assume a flat 2D surface like this:

# Answer
I think you can achieve water by creating a wave. Then take a radial sweep of the planet, following the wave linearly, and cutting out the land and replacing with water according to the height of the wave. The wave would need to be able to sample for the circumference of the planet and also need to be able to wrap to the beginning. I think trees can be done in a similar manner, ignoring the water, place trees according to some sort of wave that acts as a tree density. I'm unsure about caves specifically, but I suspect a similar solution may also be applied, but on a smaller scale. Simply choose a start, and create some sort of wave that determines whether or not you should move up/down during the generation of a single cave.

So you would start with angle = 0 and rotate around the planet. The wave to the left(backed by a 1D array or similar structure) would be used to determine whether or not you should place water at that location. Similarly, you can follow this convention to place trees. I think it would be more difficult to directly turn this into a cave system, but I think it may have some sort of application for doing such.
> 1 votes

# Answer
This isn't so much an answer as a potential idea, but I'll post it anyway. Keep in mind I'm not very experienced in actually implementing these things.

What you could do for the flat planet is make a list of all the surface pixels, and then allow a function such as a random number generator to choose from this list some pixels to be populated with trees. Lakes could be done in a similar fashion, choosing a pixel and then using some kind of algorithm to generate it. Not as sure about caves, sorry. As far as actually detecting surface pixels, you could do this most efficiently by detecting them at generation, although I'm not sure of what your algorithm is. I guess you could also potentially check if it's a ground pixel by looping through all pixels and finding whether or not there is a sky pixel above them. As a third suggestion, if the layer of grass is only ever going to be 1 pixel thick, you could simply fill the list with all grass pixels

Any feedback to this response would be appreciated, as as I said I'm not overly confident myself. Nonetheless, I hope this helped even slightly.

Good luck, and happy coding
> 0 votes

# Answer
I am assuming the world as flat.

Regarding water - you could decide on a sea level. When generating the terrain you place it on a distance from the center of the round world or from bottom of a flat world so that X % is above sea level and the rest below sea level. Then you fill all "air" spaces below sea level with water. With your current generation that would give a lot of tiny lakes, you probably want larger and smoother variations to get larger lakes (and hills).

If you want to have mountain lakes etc, you could try to randomly test blocks in the air and test to "flood fill" horizontally and downwards from that block and see if the size of the resulting lake would be of a good size (most attempts will result in flooding the earth).

For caves, you can: 1. Pick a random starting position (x, y). 2. "Dig" - replace that block with air 3. Generate a trajectory (dx, dy) and a delta trajectory (ddx, ddy). 4. Proceed in the trajectory (x = x + dx, y = y+dy). Have a small probability of changing the trajectory delta (ddx, ddy). Also have a small probability of stop digging, and a small probability of branching (MUST be smaller than the probability of stop digging). For branches, RECURSIVELT start from step 1 on the branched block. 5. If we decided to stopped dig, or if the block we end up on is air, we have reached the surface again or reached a different cave. Stop looping. Otherwise, start over from #2.

If you wanted the cave to start on top, let the starting block be at the surface. If you want a subterranean block, start anywhere and run the process twice for opposite directions of the starting point. If you want the block to be more than one block wide, "expand" it during or after the digging.

For trees, I guess you want them lumped in forests, you could do something like this: 1. Randomize a forest size (effectively length): l 2. Randomize a location: x 3. Check if the location x, x+1, x+2, ..., x+l is suitable for a forrest: are all ground pieces (not water), check other criteria (maybe not put forrest on a steep slope, or above tree level, etc). Start over from step 1 if the spot was not suitable for a forest. 4. Within the forest area, randomize the trees, for a certain probability of a tree on each ground block on the surface (but do not allow trees on adjacent surface blocks). Near the edges of the forest area, have a gradient probability of trees to hide the edge of the forest area.

In a flat world this should be fairly simple, question is how it translates to circular world. You may want to create many common functions so that you can get things like: * distance of block from center of earth * is the block a surface block * get adjacent surface block * get gravitationally adjacent surface block * get angle of block relative to north pole (needed to know in what angle to grow a tree, once you have picked a block suitable for a tree)

For the caves you should be able to disregard that the earth is round, except if you want to avoid having too steep caves etc in which case you need to account for angle of the block when determining angle.
> 0 votes

---
Tags: procedural-generation
---


# Question
Title: Unity - Setting a sprite animation idle to a specific frame and transition smoothly
I'm new to Unity. I have built an animation with a 2d spritesheet and now I want to transition between idle and walking.

Idle is my frame 1 (or any other frame) and the whole spritesheet animation is running.

When I create the animatorcontroller, I'd set idle as no animation and walking as the animation from the spritesheet, I then assign conditions as paramenter, but when a paramente change, the transition is not smooth, it skips back to the first frame.

How can I make a transition that would, when stopping, continue to animate until the idle frame has been reached, and then stop?

# Answer
> 1 votes
Make sure to use **Has Exit Time** on the transition and set the **Exit Time** to 1, and the **Transition Duration** to 0.

Please leave a comment and add some screenshots of your setup if it doesn't work for you :)

---
Tags: unity, animation
---


# Question
Title: How to access entites from scripts in an entity-framework?
I'm developing on a simple libGDX-based Game and im using the entity-component-system *ashley*.

For non-generic but custom behaviour (e.g. the Player Movement), I'm using **"scripts"** instead of reuseable and generic Entity-Systems. Therefore I've got an **ScriptComponent** and a **ScriptSystem** which runs `init()` and `update()` on all scripts related to an entity.

At some point I want to generate a map, counting game-related-properties etc. that brings me to the point where I'm confused about ***how to access those porperties from any script***.

In other Engines/Enviroments like Unity3D the GameObjects (the entities) brings functionality to find other entities like **FindGameObjectsWithTag(...)**.

But how can I realise that in ashley? Also should it be possible in an Entity-Framework to access specific entities in general?

## Edit: Additional information

Here comes a simple example-usecase. This is very notional example I've just created for that post. I just wanted to demonstrate, that I thing there is a need of an "main Game Object" in a game which also uses a entity-component-framework like ashley. So I thought a correct way is, to let this main-game-object be an entitiy too which holds the main script. But I'm not sure, if this is a good approach.

Here I demonstrate this with having a PlayerScript which just sets the lives for the player accordingly to the difficulty level of the game (maybe set by the player on the main-menu-screen). This PlayerScript is attached to the ScriptComponent of the player entity.

```
public class PlayerScript extends Script {

 int playerLives;

  public void init() {
     GameEntity entity = getTheEntityByName("game"); // this method doesn't exist
     GameScriptComponent gsc = scriptComponentMapper.get(entity);
     GameScript mainGameScript = gsc.getScriptByName("game");
     if(mainGameScript.getDifficulty == "easy")
     playerLives = 999;
  }
}

```

# Answer
In your given code example and goals, you want to load each system by a given script, because you are referencing or copying the pattern of unity 3d to achieve your goals, this is not possible for now. But I can give you an example or a pattern on how I create a system using your example code. In the mean time, I recommend you to read what is ECS and Ashley for a better understanding.

Why I used `PooledEngine`? because it allows the components and entities to be pooled automatically by retrieving them. Here is the basic usage, as you can you I created an entity using the engine. Now you just need to add it to the engine after entity components has been made.

```
// Assume this is your GameWorld class

PooledEngine engine = new PooledEngine();

Entity player = engine.createEntity();

Position position = engine.createComponent(Position.class);
player.add(position);

engine.addEntity(player);

```

Creating player components...

```
public class PlayerComponent implements Component {
     public final float SPEED = 6; // 6 meters / sec
}

```

Now who's gonna handle the player entity? we could create a `PlayerSystem` by extending `IteratingSystem` (read more about ashley why I use this to extend). Initialize its family, so that system will only handle which entity has that components, but still you can access its components without adding it on the family.

```
public class PlayerSystem extends IteratingSystem {
    public PlayerSystem() {
         super(Family.all(Player.class, Position.class).get());
    }

    public void processEntity(Entity entity, float deltaTime) {
        ... // You can now process each player entity here
    }
}

```

Now lets get back to our `GameWorld` class. Then add the player system to the engine.

```
PooledEngine engine = new PooledEngine();
engine.addSystem(PlayerSystem.class);

public Entity createPlayer(float x, float y) {
    Entity entity = engine.createEntity();

    PlayerComponent playerComponent = engine.createComponent(PlayerComponent.class);
    PositionComponent positionComponent = engine.createComponent(PositionComponent.class);

    entity.add(playerComponent);
    entity.add(positionComponent);

    engine.addEntity(entity);
    return player;
}

```

Now lets get back to your goals:

1.) Your first goal is to get the entity by name. You could just use `Entity` flags.

```
public class Flags {
    public static final int PLAYER = 0;
}

Entity entity = engine.createEntity();
entity.flags = Flags.PLAYER;

```

Then in the engine or in the player system iteration, you could just

```
// for engine
for(Entity entity : engine.getEntities()) {
    if(entity.flags == Flags.PLAYER) {...}
}
// or for player system
if (entity.flags == Flags.PLAYER) {
     // now you have an access to your custom player
}

```

2.) Globally access to your entity components. You should use `ComponentMapper.getFor(Position.class)` method. As the Ashley said it was fast.

```
ComponentMapper<PositionComponent> positionMap = ComponentMapper.getFor(PositionComponent.class);

PositionComponent position = positionMap.get(entity);

```

3.) On your third goal, you want to generate a system from a script? for now Ashley don't the support for that such a method. For now you could just use engine method to get the system. But if you want to load the system script, use libgdx json reader/writer, and read/write your system using json, here is the link for the documentation json.

```
engine.getSystem(PlayerSystem.class)

```
> 1 votes

# Answer
First off, it sounds like you're trying to shoehorn Unity3d concepts into LibGDX -- which is a completely natural tendency when trying to pick up a new system, but do realize that if you're not careful, you'll end up implementing things in a very non-LibGDX/Ashley way and just creating more work for yourself.

If you have some initialization code that needs to happen once, don't put it in an EntitySystem, component, or anything -- don't even use Ashley for that. Just execute it in the startup part of your program, perhaps next to the section that initializes the Ashley `Engine` and all of the corresponding `EntitySystem`s. While Unity3d forces every piece of executable logic to be attached to an entity, LibGDX/Ashley doesn't.

While Ashley doesn't have (or need, IMO) "tags", it does have components and I just those instead (and you can use "marker", or stateless, components for that). If you *really* want tags, you could implement your own EntityListener that checks to see if a new entity has a `TagComponent` (which you'd make), and if it does, update a globally-reachable `Map<String, List<Entity>>` sort of thing. Just don't forget to also *remove* from the list when the entity is destroyed.

As for your specific PlayerScript example, I generally create an `EntityCreator` class with all sorts of `create*` methods in it, like `createPlayer`. This creates an entity, adds the required components to it, and returns it. The sort of initialization logic you're talking about would go here. The GameScript/GameScriptComponent you have would just be a regular object and probably passed in as a constructor argument for EntityCreator and saved as a field, where any of the `create*` methods can access it.
> 1 votes

---
Tags: libgdx, entity-system, entity-component
---


# Question
Title: How to spawn collectibles at random positions in Java
Please i need assistance, I made a game in Android Studio with Java. I am almost done with the game just that i'm having an issue where my collectible keeps re-spawning in the same position after the player has collected it. I would like for it to re-spawn at random positions on the screen, how can i do this?. The collectible is a fuel can.

Here is the fuel can collectible class

Fuel.java

```
public class Fuel extends GameObject {

 public Fuel(Bitmap res, int w, int h, int numFrames) {
        x = GamePanel.WIDTH + 5000;
        y = GamePanel.HEIGHT / 2;
        dy =(random.nextInt()*(GamePanel.HEIGHT - (maxBorderHeight* 2)+maxBorderHeight));
        dx = +GamePanel.MOVESPEED;
        height = h;
        width = w;

        Bitmap[] image = new Bitmap[numFrames];
        spritesheet = res;

        for (int i = 0; i < image.length; i++)
        {
            image[i] = Bitmap.createBitmap(spritesheet, 0, i*height, width, height);
        }
        animation.setFrames(image);
        animation.setDelay(100-dx);
        animation.update();
    }

    public void update()
    {
        if (x < 0) {
            reset();
        }
        x += dx;
        dx = dx- 1;

        if (dx <= -15) {
            dx = -15;
        }

    animation.update();
    }

    public void draw(Canvas canvas)
    {
        try {
            canvas.drawBitmap(animation.getImage(),x,y,null);
        }catch (Exception e){}
    }

    public void reset(){
        x = GamePanel.WIDTH + 5000;
        y = GamePanel.HEIGHT/2 ;
        dy = (random.nextInt()*(GamePanel.HEIGHT - (maxBorderHeight* 2)+maxBorderHeight));
        dx = +GamePanel.MOVESPEED;

    }

    public void fuelCollected(){
    reset();
    }

}

```

Here is my GamePanel.java class

```
public class GamePanel extends SurfaceView implements SurfaceHolder.Callback
{
  private Fuel fuel;

  @Override
  public void surfaceCreated(SurfaceHolder holder){
   fuel = new Fuel(BitmapFactory.decodeResource(getResources(), R.drawable.fuel),40,40,1);
  }

 public void update()
{
fuel.update();
        if(collectFuel(player,fuel)){
            distance +=100;
        }

public boolean collectFuel(GameObject player, GameObject fuel){
    if(Rect.intersects(player.getRectangle(),fuel.getRectangle()))
    {
        fuelCollected();
        return true;
    }
    return false;
}

public void fuelCollected(){fuel.fuelCollected();}
}
 @Override
public void draw(Canvas canvas){

// draw fuel can

        fuel.draw(canvas);
 }
}

```

# Answer
In your `fuel` constructor **and** `reset` method, change

```
y = GamePanel.HEIGHT / 2;

```

to

```
y = GamePanel.HEIGHT * Math.random();

```
> 1 votes

---
Tags: java
---


# Question
Title: Converting Euler rotation angles from Z up to Y up (Max to OpenGL)
I'm working on pulling geometry and it's transformation from a 3DS Max exported FBX (Z-up) to an OpenGL model format (Y-up). The main problem is I intend to keep the transformations as Translation and XYZ rotations.

Right now I pull all position transforms simply going from (x y z) to (x z -y) and everything looks good. However the geometry rotation comes in as Euler angle rotations ( X Y Z ). Rotating these has turned into a nightmare. I know I can get a matrix and just multiply it by the RotX-90 mat but pulling those Eulers back is not reliable.

What seems to almost work is this, and it's what seemed to give correct results most of the time. It jut seems bad for the case ( 92.83, -89.41, 53.53) for example when it looks like it's loosing a 90 deg rotation on X.

```
Matrix rot90 ( 1,  0, 0, 0,
               0,  0, 1, 0,
               0, -1, 0, 0,
               0,  0, 0, 1);

RotMat = RotX * RotY * RotZ
RotMat = Rot90X * RotMat
Quaternion = Convert from RotMat
NewX = Quaternion.Pitch
NewY = Quaternion.Yaw
NewZ = Quaternion.Roll

```

I know the god of bit shifting must have some civil way of doing this. Any tips/suggestions would be greatly appreciated.

ps. exporting the FBX with Y up won't work as it just seems to apply a transformation on the root node, not to actually swap vertices y-z positions.

# Answer
If you want to convert Z\_UP to Y\_UP, rotating around X by -90d will give you same look, but if you want to convert/change positions from Z\_UP to Y\_UP then:

Converting positions in Z\_UP (x y z) to (x z -y) will give you same look in Y\_UP if all transforms are IDENTITY. You also need to convert transforms, cameras and light orientations (because default is \[0 0 -1\] in RH):

* Convert all positions, normals... to Y\_UP
* Converting position of transform is very easy -\> (x y z) to (x z -y)
* You need to convert rotation to new coord sys with correct order:
    + First you can decompose affine matrix and get rotation matrix and scaling factors
    + Then extract euler angles using XYZ
    + Then convert XYZ sequence to new coord-sys (Y\_UP)
    + Apply new rotation
    + Convert scaling factors to Y\_UP
    + Combine Translate, Rotate and Scale as new Affine Transform Matrix
* You may need to add extra rotations to camera and lights to fix orientations. For instance if camera has idendity transform then it looks toward -Z but -Z is -Y in Y\_UP

I hope this will help!
> 0 votes

---
Tags: opengl, mathematics, 3dsmax, axis
---


# Question
Title: How to render sprites without using SpriteRenderers
I'm creating a component that lets you write text, like the UI Text component, but using sprites as letters.

I already have the mapping for characters-\>sprites, and now was going to draw the text using the sprites.

My first idea, was to just create one children for each letter, each child having a sprite renderer.

But it feels like a pretty poor approach, since a transform and a sprite renderer component have to created or destroyed, when the text changes size.

Then I thought about using a Mesh renderer and mesh filter, and define the mesh when the text changes, creating a quad for each letter. But what I don't like about this idea is having 2 extra components in my gameObject, as I would like to keep it as clean as possible.

Is there a way to achieve this keeping all the necessary components inside my own class? Defining my own quads, UVs and such is just fine, but I just don't know how to render them through script. Is it even possible without adding more components to the gameObject?

Don't know if its relevant, but I want to use World Coordinates, not screen coordinates.

# Answer
Your first approach was an effective way! Though I can't show code right now, you need to change the sprite for each space(in your code) to form your words. Also, if you can figure out how to do it right, you could make a font and use text instead.
> -1 votes

---
Tags: unity, rendering, sprites, spritefont
---


title: Can I place 3D objects on a 2D sprite?

text:
# Question
Title: Can I place 3D objects on a 2D sprite?
I am creating a circular island for my game. I will be doing it in Photoshop, and importing it to Unity as a .PNG. Will I be able to place grids and buildings on top of it, like in RTS games, or must my island be a 3D model to do so?

# Answer
Unity allows you to work with both 3D and 2D elements.

To answer your question, yes. You can place a 3D object on top of a 2D sprite. Simply dragging the two objects into a scene, together, will show you this. As per the grid, Unity does not have any such feature built in. We see a grid in the editor, but this grid is not visible in-game. As such, you will be creating the grid, yourself. Assuming you set it up to work, it will work. How you go about doing so is an entirely different question.

Alternatively, you could simply use the Terrain tool to make your island, and use the original image as it's texture.
> 1 votes

---
Tags: unity, 2d, 3d-meshes
---


# Question
Title: Best way to manage thousands of objects in an multiplayer online game?
I'm currently planning to develop a real-time multiplayer online game, using the Google Maps API on Android. I thought about having survival-like game play, where you collect resources to build yourself up :)

---

The players should be able to build structures (houses, shelters, walls, etc.). There should also be random spawned objects, like trees or caverns. There will be many players in a multiplayer game, so there will be many of these objects. I thought about storing all of these objects in a server-based database. Every entity will get an ID and coordinates for their position.

Every player should be able to access and see those buildings, but I can't draw them all at once; I can't even calculate the distance for every structure or object - that just would make the game really slow. At some point, it would crash.

---

I need a way to manage, draw and calculate all of the structures and objects (which will be stored in my database), when the player is near their saved position. I googled a bit and asked some nice guys in the game development chat; they told me about some methods, like spatial mapping and quad trees. Those would be easy to implement, and the Google Maps API already supports quad trees with coordinates and latitude/longitude markers.

Is this the best way to achieve what I want, or is there a better way to manage, draw and calculate thousands of objects?

# Answer
> 0 votes
As far as I can think this through ... You have to store the Data for a area like 2 by 2 KM. Load for every Player individualiy an Square area like 5 by 5 Areas. In this way you get a Field of 10 by 10 KM.

Sure it's not perfect but the solution I would get for ...

---
Tags: android, game-design, architecture
---


# Question
Title: Moving an object extremely close to the camera at a constant speed makes it visually speed up
I have a quad in 3D space (a billboard in the real-world sense) that I want to move close to the camera so the user can inspect it. The quad is defined by the 3D coordinates of its four corners.

To accomplish this I compute target points very close to the camera for each of the corners.

*(I use XNA's Viewport.Unproject() method which does something similar to this)*

```
// Top left corner of the screen,
// Z=0.1f means very close to the camera's near plane
var screenPoint = new Vector4(0,0,0.1f,1);
var worldPoint = Vector4.Transform(screenPoint, Matrix.Inverse(ViewMatrix * ProjectionMatrix));
var worldPoint /= worldPoint.W;

```

These world points that are close to the camera produce a very small quad: which is understandable if we look at this picture:

Here the initial position of the quad is depicted in red and the end position of the quad is depicted in blue.

For each of the corners of the quad I linearly interpolate between the original position and the position near the camera.

```
this.timer += deltaTime;
var progress = this.timer / 10.0f;
var currentTopLeft = Vector3.Lerp(initialTopLeft, nearTopLeft, progress);

```

Since I linearly interpolate the quad moves to its new position at a constant speed. I've verified this by ouputting the speed and distance to the console. However, the visual effect is that the quad first hardly moves and then all of a sudden moves very fast to its destination.

I think this is because the quad is being scaled down while moving closer (to fit the near plane) so it will stay relatively the same size on screen for a long time. Only once it comes very close it seems to move. (For example see this answer).

**The question I have is:** what can I do to make it look like the quad is moving closer at a constant speed?

I was thinking about not interpolating linearly but first move progress very fast and then very slow (Ive tried `progress = sqrt(progress)` which helped a little). But I'm not sure how I can compute the exact (or near enough) formulate to make this work.

Another idea I had was to bring the quad not so extremely close, but then there is the danger of it clipping with objects in the world.

# Answer
The problem is that your constant movement speed - after perspective projection - creates non-constant perceived resize speed.

Let's assume the quad is moving 1 unit per second to the camera and this is the constant speed. What you need is the constant *percentage* change per second. Right now, when your quad is 10 units from the camera, then after a second it's 9 units from the camera, so it changed by 1/10. After few frames, when the distance get from 2 to 1 you have a 1/2 change per second, which causes visual speedup.

Instead of this you should move the quad by 1/X of the actual distance, picking the X for your needs. This way you'll never get to the camera position, but you can stop moving at some fixed distance.

Besides of any scaling that you may need you can use an Exponential function to make it independent of fps, or you may use one of the few Easing functions.
> 1 votes

---
Tags: mathematics, camera, perspective
---


# Question
Title: How to report bugs found on procedurally generated levels?
There is many topics on how procedural generating works but I couldn't find any info on how to test and - what's more important - how to report bugs that may occur on procedurally generated levels. What is the best way to describe a bug, for example related to level design, on a map that will look different each time you play new game? **What information should be included in bug report** so reproducing it would be easier for level designer, level artist, etc. and then also during regression process?

EDIT: It is worth mentioning that the game, I am preparing to test, is in very early phase of developing and is constantly changing along with the systems responsible for generating levels. The purpose of this research is to learn how to describe bugs (what info to include in report) so the regression in a changing environment would be as less time consuming and as effective as possible.

# Answer
> 18 votes
It can also be very useful when your map generation algorithm is deterministic and repeatable based on an initial seed value. So when you enter the same seed value, you get the same map. This might be easier to implement than you think. Most random number generation APIs can be initialized with a seed value and then always generate the same sequence of random numbers for the same seed. If you are using one of the few platforms where this is not the case (like browser-based JavaScript), you could implement your own random number generator. There are plenty of algorithms around which are not very difficult to implement and usually always require a seed value.

Your testers can then mention the map seed in their bug reports. A bug reports like "Trees grow in the middle of a lake" can have a reproduction instruction "Generate a map with seed a4f6dd32 and go to position 4321500:1269100". After you verified this, you can set a conditional debugger breakpoint in your map generation algorithm which triggers on the affected map chunk and check out exactly what's going on.

A deterministic map generation algorithm also allows you to implement automated test. You can have various test seeds with known outputs and then have your automated tests check if that output is still the same after you made some performance improvements in your generation algorithm.

---
Tags: procedural-generation, debugging, testing
---


# Question
Title: GameObject that should have a fixed speed keeps accelerating
I'm using a coroutine to make a GameObject move from a random point A to a random point B. The GameObject should move along this trajectory at fixed intervals and at a constant speed.

However, each time my coroutine that executes the movement is called, the GameObject is a little bit faster.

```
private IEnumerator movement () {

        // Initialize position and rotation
        float distanceX = endTransform.position.x - startTransform.position.x;
        float distanceZ = endTransform.position.z - startTransform.position.z;
        float angleAroundY = 90.0f - Mathf.Rad2Deg*(Mathf.Atan2 (distanceZ, distanceX));

        this.gameObject.transform.position = startTransform.position;
        this.gameObject.transform.rotation = startTransform.rotation * Quaternion.Euler (90.0f, angleAroundY, 0.0f);

        // Move from point A to point B
        while (this.gameObject.transform != endTransform.transform) {
            float step = speed * Time.fixedDeltaTime;
            this.gameObject.transform.position = Vector3.MoveTowards (this.gameObject.transform.position, endTransform.transform.position, step);
            yield return null;
        }
        yield return null;
    }

```

I checked and the `step` variable is constant.

# Answer
> 2 votes
Turned my comment into answer, to make the question answered.

The problem lies in the `while` loop never actually reaching it's condition.

Only the position is being manipulated but whole transform equality is being tested and the rotations do not match, obviously.

That in return never stops the coroutine and whenever the coroutine is called again, the position is going to be reset and now both of the coroutines are going to execute their `MoveTowards` code. Order to move once more, and it's happening thrice... On and on and on..

The movement seemingly stops, because MoveTowards will equal the target if it was going to overshoot. This can make one think, that the coroutine has finished.

It's a simple fix - check explicitly for positions:

```
while (this.gameObject.transform.position != endTransform.position)
{
    // MoveTowards
}

```

---
Tags: unity, coroutines
---


title: Mining procedural caves in Unity

text:
# Question
Title: Mining procedural caves in Unity
I am using cellular automata to randomly generate caves in Unity. Attached is a screenshot:

The black area represents walls. Walls can contain resources that can be mined.

Walls are made of blocks. A block should be destroyed when it is mined.

The naive approach would be to render a cube for each wall block. This won't work though because it will require too many objects to be on screen at once, even if the wall blocks are clipped to the viewport.

So how should I go about this? I was considering grouping sections of wall blocks together in a single mesh. When a block is destroyed, the mesh would be re-rendered with vertices for the block removed.

Or is there a better way?

# Answer
> 1 votes
A group of cubes are often called chunks. A voxel engine is the name of engines that generate meshes for this type of data.

However, if your world is flat and your camera close you might be able to get away with approximately drawing what is on the screen. Use a pool of GameObjects to be used for drawing what's on the screen. Unload blocks or chunks when moving away and load blocks or chunks when you get near them.

# Answer
> 1 votes
I would divide map onto different parts of some area. For example if you have 1000 units = 100 y units and 100 x units you divide generated area to 1000/100 = 10 parts that have area 100, 10 y, 10 x.

Before that you generate black part as a 1 mesh and then generate other things inside that mesh if you need it, but then I would suggest to cutout space for these objects as probably they will have some scripts attached to them and they can't be part of the mesh.

And then while you divide your mesh into chunks with 100 area you divide the mesh too, add to those chunks some script that it's x, y position in jagged array of all chunks. Raycast from camera to enable current chunk neighbour chunks((x;y) +(0;1), +(0;-1), +(-1, -1).....). And if the chunk you were raycasting changes find the difference in x, y in array. Then you have all you need to find chunks that need to be disabled in array.

As for the mesh. You can raycast it and rebuild mesh on point where it was raycasted, but that is complicated and somehow inefficient and for example if you want to have blocks that change texture or crack it would be pain to do that. So what I suggest is those blocks that are near white area should be just normal blocks not attached to the whole mesh. And also for optimization those blocks could consist of group of 4 blocks, so if one block from the group gets destructed, mesh that is near those group should rebuild and on it's place should appear new group of 4 blocks. So now if player made a tunnel between mesh, the whole mesh would not rebuild, but just a part that was divided and also if he decides to just dig 3 blocks and go on it's better when he doesn't rebuild the whole mesh.

Also I would just made it not a mesh, but just a bigger cube, that gets replaced with 4 smaller and so on.

---
Tags: unity, procedural-generation, graphics-programming
---


# Question
Title: Make a person walk faster when standing on plane/panel in Unity?
Is it possible to make a person walk faster when standing on plane/panel in Unity without writing a lot of code? If so how?

I am using the standard asset first person movement prefab.

# Answer
> 1 votes
You could add a trigger to the plane and then write a script to check, if an object with a tag "Player" is inside it (don't forget to set the players tag to "Player") . Make the speed variable in the player movement script to public so that other scripts can access it. Then when the player is in trigger set the speed variable higher, and when ever the player leaves the trigger set the speed back to normal. To check if player is in trigger use this:

```
void OnTriggerStay(Collider col){
    if(col.tag == "Player"){
        col.GetComponent<YOUR MOVE SCRIPT NAME>().SPEED_VARIABLE += SPEED BOOST VALUE;}}

```

To check if the player exits the trigger use this:

```
void OnTriggerExit(Collider col){
    if(col.tag == "Player"){
        col.GetComponent<YOUR MOVE SCRIPT NAME>().SPEED_VARIABLE -= SPEED BOOST VALUE;}}

```

Then make sure the increment and decrement of the speed is only called once or else the speed will be constantly incremented and will not fully return back when the player exits the trigger. Hope this helps.

# Answer
> 1 votes
The first person prefab should have public walking and running speed properties. You should create another script attached to the player. You need the OnCollisionEnter and OnCOllisionExit methods in the class. When OnCollisionEnter is triggered, You should check if the tag for the collider is something like "move\_quick". If so, the script should turn up the values and when OnCollisionExit is triggered, you should reset those values.

# Answer
> 0 votes
Well, when `OnTriggerEnter(Collider other)` is good for some purposes, here I would recommend you to use `Physics.Raycast()` you can easily set layers that you can hit by specifying the `LayerMask`. And the raycast to the ground will require very small distance to detect the collision, so it would be very good from performance point of view.

Also it will give you more accurate movement speed detection. Imagine that you have some puddle, you can attach to it mesh collider of any form and the speed will be decreased(increased) if you stand right on that puddle.

You can do this easily by:

```
_playerCurrentSpeed = Speed;
if(Physics.Raycast(....., BadGroundLayerMask)) {
    _playerCurrentSpeed -= 10;
}
Move(_playerCurrentSpeed);

```

Edit: Also you don't care about using `GetComponent<>();` or comparing `tag`. Comparing tag for example is very performance heavy.

# Answer
> -1 votes
You can do this pretty simply, I believe.

Like others have said, use the collider to determine if you are on the plane. If you are, then multiply the walk speed or call a different method, like `run ()`.

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


# Question
Title: Matrix operations to flip 3d models front to back, without changing position
Multiple 3D objects look to be in the correct screen position, and I can move around them and this continues to be true, but each one looks like it is flipped back to front (I can see the backside of the object as if the camera were on the other side of it).

Any clues to why this may be happening in addition to correcting it would be welcome also- I'm getting a transform matrix from one api what is documented as OpenGL 4x4 matrix format, but my underlying api (bgfx) is wrapping opengl so may be assuming another format. I can probably go get the transform in different format, but now I'd really like to know how to correct this also if there was no option but to start with the opengl matrix.

# Answer
> 1 votes
Sounds like a wrong face culling mode, change either to

BGFX\_STATE\_CULL\_CW

or to

BGFX\_STATE\_CULL\_CCW

using

bgfx::setState

---
Tags: opengl, matrix
---


title: How to create a searchlight in Unity ?

text:
# Question
Title: How to create a searchlight in Unity ?
I'm trying to create a WW2 simple game and I'm experience issue creating the light emitted from a Flak Searchlight.

The final lighting effect will be something like this:

http://s1115.photobucket.com/user/k4kittycrew/media/K4KITTY3/Slide2\_zpsfccf1590.jpg.html

I know that it is called "volumetric light" and this is not supported by Unity.

Thanks

# Answer
Depending on exactly what you're trying to achieve (eg. will the player see it up close or only in the distance like that?) it may be best to fake it by having a stretched quad shooting out from the light, with a semi-transparent texture of the light glow.
> 2 votes

---
Tags: unity, lighting
---


# Question
Title: How to set up and use a development environment for games with graphics on a public computer?
We don't really have any IDEs or development environments with which we could develop games with graphics on school computers. We're on a network run by the school, and can't get technicians to install them, because they're a 'security nightmare' (even though quite a few students can easily circumvent them).

So, what could we do? We'd like to program games in c++ or Java.

# Answer
> -1 votes
You don't need IDEs to develop java or c++, you can even write the programs notepad if you're a masochist, but most people use notepad++ as a fallback.

If you want to program in c++, then the only thing you'll need is a compiler (mingw for example). Java however requires the Java enviroment and the Java developement kit (JDK).

None of these can actually cause a security problem though (expect maybe java, if you get a java-based virus, but believe me, you won't). They don't connect to the internet, and what could a virus do with the C++ compiler or the JDK?

---
Tags: c++, java
---


# Question
Title: Console (CMD like) in a DirectX application
I really need a console for the game i'm making. I am programming a first person camera right now and i want to see what is going on with the variables (to be more specific i need to know if i'm getting the mouse input as i want or no) and i don't know how to see it. I searched online A LOT and i found tons of scripts with no explanation so i don't know what to do. What i need is the "noob" line of command you get when you don't use WINAPI. The one you have from just writing your code into the dev c++. I know it sounds like i have no idea of what i'm saying but i don't know how to ekplain it better.

# Answer
> 1 votes
One option would be to just use `OutputDebugString` which outputs to Visual Studio's Output-window.

If you want a Windows-style CMD instead, this SO-answer seems to create one for you.

# Answer
> 1 votes
I want to provide an alternative way to achieve both a console and a Window to draw your graphics to. Configure your project to be a default console project and create the window manually through the WinAPI. This way you have both a console and a window to draw your graphics to. If you later decide you do not need the console anymore you can do

```
ShowWindow(GetConsoleWindow(), SW_HIDE);

```

at the beginning of your program and the console wont show up anymore.

There are many Window libraries for C++ on Windows, but it is also easy to roll your own Window class, which supports all the features you need.

# Answer
> 0 votes
There's no easy way to do this. You could have a class like...

```
class Console
{
private:
    /*
     * Stores each line inputted to render later.
     */
    std::list<std::string> lines;
public:
    /*
     * Check the syntax of the inputted line, execute if valid, and add it to the list of lines.
     * Return true if the syntax was valid.
     */
    bool processCmd(const std::string& line);
}

```

But that example is very elementary. Check out the Quake source, that may be a good learning point.

On the rendering end, you need to temporarily render in 2d, so you can draw the console, then switch back to 3d.

**EDIT 1:**

For parsing you could use `boost::program_options`. There are some other libraries too, for example (quick Googpe search): http://optionparser.sourceforge.net/ https://github.com/FlorianRappl/CmdParser https://github.com/jarro2783/cxxopts

These are designed to parse the CLI, but can be used for your task.

---
Tags: 3d, directx11, c++, winapi
---


# Question
Title: Balancing players between air/land fields in a PvP match
### Background:

In my game there are two teams per PvP match, and those two teams are further divided into air/land fields. Each team has 12 players on the ground and 6 patrolling the sky. The goal of the game is for the air/land units to work together to win the match. Players are matchmade into games randomly, without taking into account skill/field preference/etc (the short explanation is that we don't have control over this).

### The problem:

If I allow complete freedom in choosing fields, I might end up with no players in the sky or vice versa on one or both teams. If I don't give players a choice, they won't be happy when they aren't assigned to the field of their preference. Overall I imagine the fields would balance out on their own if they're equally enjoyable, but there's little room for error there -- if either field gets a bad first impression, it'll be difficult to recover from. I want to ensure there are some constraints in place to prevent death by conjecture.

I thought of adding 1 or 2 landing pads at either team's base, and that way players who wanted to play the land field could land, and players who wanted to play the air field could take a parked aircraft on the landing pad. This could breed tension between players where more than 2 players are competing for landing pads though.

What are some approaches I can take to resolve this, which avoid forcing player behavior as much as possible, but still ensure gameplay is predictable and reliable? Specifically I'm looking for what key issues an answer takes into account and how it resolves them. If you're drawing experience from something that's already been put into practice and already has tangible results, those results would be a wonderful addition to your answer.

# Answer
> 2 votes
Is it *absolutely essential* for your game concept that there are *exactly* 6 air-players and 12 land-players per team? Or is that just the best combination to win the game?

If the latter, you should just allow players to switch roles whenever they want. Players want to win, so they will do what it takes. Many players will be willing to play the role they like less if that will contribute to them winning the game. I would even recommend you to not limit the number-ratio. If everyone wants to play air, they can do that, but then they will likely lose the game against a more balanced team.

But in order for that to work out you need to properly balance air-gameplay and land-gameplay. Make sure that:

* Both roles are equally fun to play, equally powerful and equally useful in every phase of the game. Otherwise the community will prefer one role over the other and argue about who has to play the less interesting role.
* You have similar controls and mechanics between both, so that most gameplay skill is transferable. That way players don't get too focused on one role and become more flexible.
* You encourage players to switch between both roles often, so they train them equally. A good way to do that is:
    + Make switching during the game cheap and convenient
    + Give the player progression goals which require them to play both roles
    + If you have progression rewards, make these useful in both roles. Or even better, have one class unlock progression rewards for the other. Like if you kill 100 enemies as air, you get a new weapon for land.

Another thing you can do to motivate players to balance their teams is directly reward and punish them for their team balance. For example, if a game has only 8 land players but 10 air players, the land players get a bonus and the air players get a penalty. A more careful bonus/penalty would be to the score rewards they gain when they accomplish things. A more courageous but likely far more effective method might be to directly reward or punish them mechanically by making those who are too many weaker and those who are too few stronger. You can explain that plausibly through logistics: When there are twice as many aircraft as expected by your supply and maintenance personnel, they will have to cut some corners, which will result in less ammo being available and parts breaking earlier (represented by having less hit points). Don't over do this, though, because role ration does not matter anymore when 8 land with their bonuses are just as effective as 12 land without.

# Answer
> 1 votes
You could introduce a first-come, first-serve option so that the first players to join a random match get their favorite spots. (This also compensates those who are waiting longest if matchmaking times are long.) Players can pick an air/ground slot so long as one is available.

If you make it clear to players (such as a mention in the tutorial/loading screen tips) that a 6 and 12 breakup of the team is recommended, and also let them see which roles the rest of the team has chosen, (some) players will choose/switch roles in order to have a better chance of winning. The incentive of winning is strong, and could work even without a hard constraint. This also gives players the options to diversify their strategies, if you want to allow that. (This does loose some game-play predictability of course)

An optional addition is to have a mechanism for players to switch roles during the game, such as the landing pads you suggested. Making the air/ground ratio visible is important here.

With 18 players per game, you are not going to have team-wide coordination for maneuvers in the match, but you also have enough players to have a good probability that someone fills in needed positions. If there are support/tank/sniper/ect. roles among the air and ground players, you will likely have some trouble encouraging players to coordinate, but if the choice is just between two fields, they should be able to work it out using only a few (soft) pointers from you.

---
Tags: game-design, multiplayer, balance
---


# Question
Title: How to achieve an GPS-Based game like "Parallel Kingdom"
I'd like to use Google Maps, in my game, much like *"Ingress"*, "*Pokémon GO*" and *"Parallel Kingdom"*.

When I take a deeper look into the Android API/Google Maps API, and dozens of forums, I noticed that it's very hard to display sprites or even animations using the Google Maps API. Someone said that you need to layer stuff. Someone else said it's better to use game engines for that. No one tells me how to begin. I opened Android Studios and made a new Google Maps project. I compiled and ran the app. There is the map, so I guess I have completed the first step.

How do I combine the Google Map with an extra view or LibGDX layer for displaying sprites? How manage this with a multiplayer server?

I am wanting to set my map up like *"Parallel Kingdom"*, which you can see, below.

>

# Answer
If you use OpenGL or a game engine that uses OpenGL, then you can make a canvas that's transparent. Then you put the map under the surface view and you draw the sprites on the view.

Calculating the position of the sprites is a bit harder, but luckily Google maps provides the current gps location, so you can figure out how to place them.

You should store the gls location of the entites on ths server and send this to the client (preferably only the stuff around it). On client-side you subtract the current GPS location from the enemy's location and based on the zoom you make it lay between the clipping plane's of the camera.
> 0 votes

---
Tags: game-design, architecture, networking, mmo
---


# Question
Title: How do MMO servers handle a large concentrated number of players?
I have a pretty good understanding of how to scale servers but there's one thing I can't quite be sure about is how to manage a lot of players in a concentrated area.

If I have a server which is using multiple threads and processes as long as you limit the amount of players that can join a single game instance then this can scale indefinitely by adding more servers and placing it behind a load balancer.

But MMO games don't work that way because it's broken down into zones that anyone can connect to. So if a massive amount of players all decided to connect to the same zone it would put all of the stress on 1 server.

If you tried to spread the load across multiple servers then you'd run into problems of having to share information between the servers (Such as if player X was connected to sever 1 then all of his movements would also have to be passed on to the players connected to server 2 since server 1 and 2 are managing the load for the same zone).

So I was wondering how do you go about solving this problem? Do you just keep on ramping up the specs for the server on heavily populated zones? Or is there a fast and efficient way for multiple servers to manage the load for the same zone and efficiently share data between the two servers?

# Answer
> 4 votes
Are you already familiar with technologies that exist like redis? Server architecture is definitely a complicated subject and it's good that you're planning it out now, but you might be worrying without cause and underestimating the amount of throughput possible with a well-written scalable backend.

In my experience, it's better to have servers set up to handle their own zones, but written in a way so that in the future, it's easy to modify a particularly busy zone to run multiple load-balanced servers. At that point, each server on the zone should be handling around 1000-2000 concurrent connections, and propagating player data using something like redis between the nodes.

Another common solution I've seen (particularly on popular minecraft servers) is to tweak the actual game design to limit the amount of players on a single server. To do this, have multiple load-balanced servers for the same zone, but allow the player to see what server they're connected to, and only render player data within that server. The result is multiple "realities", where each server independently has a different crowd of players in the same apparent area, but this reduces server stress and gives the flexibility of allowing the player to switch freely between servers if they want. If you do allow them to switch (in order to meet with a friend or something), impose a maximum player count per server, and you'll have a hard limit of how much each server should ever have to handle.

You should at least get a working game and run some simulation tests with a few hundred or thousand client connections to get actual performance specs before worrying where you should go from there. It's possible that there might not be an issue at all.

Also, before you concern yourself with the massive numbers of players you're asking about, consider that your game might not ever be *that* popular. I mean no offense, it's just relatively rare to develop a "hit." So instead, focus on more important issues like good game design, so that you'll be able to worry about this later on.

---
Tags: networking, mmo, server
---


# Question
Title: In theory, would an erosion algorithm compute faster on a GPU than CPU?
I'm planning to port an erosion algorithm from CPU to GPU, in theory, will it be faster or would it be better to multi-thread it on the CPU? The algorithm has quite a lot of if statements and loops with non-constant amount of iterations so it's going to be a lot of branching.

# Answer
> 2 votes
That depends on the algorithm.

Algorithms which perform the same operation on a large amount of data-points without any of these operations being dependent on the other data-points, or in other words, operations which are trivially parallelizable, are great for porting to GPUs.

But algorithms which have lots of branching and looping or which require to allocate large amounts of memory are usually more efficient to implement on the CPU.

Your algorithm *sounds* like something which would work better on CPU, but without actually seeing the algorithm in detail it is hard to tell.

---
Tags: performance, compute-shader
---


# Question
Title: Sorting sprites above the surface of 3D mesh?
I'm having trouble getting sprites to display on top of a 3D mesh. My requirements are as follows:

1. Sprite should billboard
2. Sprite should not clip into the mesh
3. Sprite should be hidden when on the other side of the mesh, or blocked by a piece of the mesh that's "large/substantial"
4. Sprite should be not rely on placement above mesh to fix clipping
5. No raycasting should be used

4.Is needed as the sprite grows when zooming out whereas the mesh doesn't. Sprites can get pretty large. 5. Raycasting in this application is really expensive on the target platform so not really usable when considering 1000's of sprites.

It's a bit hard to explain so let me give an example. There's a bit of setup so ignore the first 100 lines or so. The shader code and other stuff is in the second section.

```
//=====================================
//=== SKIP DOWN TO THE NEXT SECTION ===
//=====================================
//This is just default THREE.js stuff
var getObjects = function(jCanvas){
  var ret = {};
 ret.renderer = new THREE.WebGLRenderer({canvas : jCanvas[0]});
  ret.renderer.setSize(jCanvas.width(), jCanvas.height());
  ret.renderer.context.getExtension("EXT_frag_depth");

  ret.cam = new THREE.PerspectiveCamera(45, jCanvas.width() / jCanvas.height(), 0.1, 100);
  ret.cam.position.set(0,2,6);
  ret.cam.quaternion.multiply(new THREE.Quaternion().setFromAxisAngle( new THREE.Vector3( 1, 0, 0 ), -Math.PI/8 ));

  ret.camControls = new THREE.TrackballControls(ret.cam, ret.renderer.domElement);
  ret.camControls.target.set(0, 0, 0);

  return ret;
};

var defaultScene = function(objs){
  objs.scene = new THREE.Scene();
  var geo = new THREE.BoxGeometry(1,1,1);
  var mat = new THREE.MeshLambertMaterial({color : 0xff0000});
  var msh = new THREE.Mesh(geo,mat);
  objs.scene.add(msh);
  var light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  objs.scene.add( light );
  var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  directionalLight.position.set( -2, 1, -1 );
  objs.scene.add( directionalLight );

  var lastTime = Date.now();
  objs.renderFunc = function() {
    requestAnimationFrame( this.renderFunc.bind(this) );

    var delta = Date.now() - lastTime;
    this.camControls.update(delta);

    this.renderer.render( this.scene, this.cam );
  };

  return objs;
};

var objs = getObjects($("#can"));
defaultScene(objs);

//=====================================
//=== THE CODE WE'RE INSTERESTED IN ===
//=====================================
var mat = new THREE.ShaderMaterial( {
  transparent : true,
  uniforms: {
   depthPos: {
    value : new THREE.Vector3()
   }
  },
  extensions : {
   fragDepth : true
  },
  vertexShader: `
   uniform vec3 depthPos;
   varying vec2 vUV;
   varying float depthVal;
   void main()
   {
    vUV = uv; //Output UV to fragment
    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
    //Model maxtix not needed as depthPos is positioned in world coordinates already
    depthVal = clamp((projectionMatrix * viewMatrix * vec4(depthPos, 1.0)).z, 0.0, 1.0);//Use depth pos to set depth
   }`
   ,
  fragmentShader: `
   varying vec2 vUV;
   varying float depthVal;

   void main() {
    //Simply sample the passed UV and get the texture color
    float depthVal2 = depthVal;// - 20.0;
    gl_FragColor = vec4(depthVal2, depthVal2, depthVal2, 1.0);
    gl_FragDepthEXT = depthVal2;
   }`
 });

  //
  var thisPos = new THREE.Vector3(0.5,0.45,0.45);
  var thisCam = objs.cam;
  var thisNrm = new THREE.Vector3(1,0,0);

 //Add a defect sprite object
 var geo = new THREE.PlaneGeometry(1, 1); //1 by 1 plane
 var baseScale = 1/16;
 var defectSprite = new THREE.Mesh(geo, mat);
 defectSprite.scale.set(baseScale, baseScale, baseScale);
 defectSprite.position.copy(thisPos);
 objs.scene.add(defectSprite);

 //Add a defect object
 geo = new THREE.SphereBufferGeometry(1,6,6);
 mat = new THREE.MeshBasicMaterial({color : 0xFFFF00});
 var defectBall = new THREE.Mesh(geo, mat);
 defectBall.scale.set(1/64, 1/64, 1/64);
 defectBall.position.copy(thisPos);
 objs.scene.add(defectBall);

 var clamp = function(a,b,c){ return Math.min(Math.max(a,b),c); }

 var doDepthValue= function(){
  window.requestAnimationFrame(doDepthValue);
  var d = thisPos.distanceTo(thisCam.position);

  //DefectSprite
  //Set rotation
  var r = thisCam.quaternion;
  defectSprite.quaternion.copy(r);
  //Set pos to depth test from
  var depthNrm = new THREE.Vector3().copy(thisNrm).multiplyScalar(1/4);
  var depthPos = new THREE.Vector3().copy(thisPos).add(depthNrm);
  defectSprite.material.uniforms.depthPos.value = depthPos; //Gets transforms applied to it so no further work need be done
 };

doDepthValue();
objs.renderFunc();
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/mrdoob/three.js/dev/build/three.js"></script>
<script src="https://cdn.rawgit.com/mrdoob/three.js/dev/examples/js/controls/TrackballControls.js"></script>

<canvas id="can" width="400" height="300"></canvas>
```

Use left mouse drag to orbit, right mouse to pan, middle mouse/wheel to zoom. The sprite appears near the yellow ball as a white to black square representing the depth assigned to the sprite. The desired effect is that it appears on top of the cube unless it's turned around.

---

The most important parts are `doDepthValue()` along with the `ShaderMaterial` explained below.

* `doDepthValue()` will set the sprites rotation and calculate a position above the mesh using the normal and current sprite position to use in determining the final depth value (called `depthPos`). This is passed to through the uniforms of the shader.
* `ShaderMaterial` takes the `depthPos` and transforms it with the view and projection matrix (only those two because it's a world position already). After this is should be in clip space. If I take the z coordinate and then pass this to the fragment shader, applying it to the depth value (using `gl_FragDepthEXT`) should give a depth value for a position just a small amount above the normal of the original mesh.

However in the example this is not what happens. The sprite is draw above the mesh if you zoom in close enough but past a certain distance it is draw behind everything.

How do I accomplish what I want? What am I doing wrong?

# Answer
> 1 votes
It seems I was just doing the transformation wrong and missed some steps in the transformation pipeline.

Here is my final transformation in ES6 javascript

```
let depthOffsetMagnitude = util.math.clamp(distToCam - 0.05, 0, 0.2);
let spriteDepthPos3 = new THREE.Vector3()
    .copy(depthOffsetDir)
    //Dynamically adjust offset with cam distance so that depth
    //value doesn't get lost outside/behind cam otherwise the sprite
    //will disappear.
    .multiplyScalar(depthOffsetMagnitude)
    .add(this.componentObject.position); //OFFSET ==> MODEL SPACE
//Now that it's in model space, do all the other transforms to get it to window space for the final depth value
let spriteDepthPos = new THREE.Vector4().set(spriteDepthPos3.x, spriteDepthPos3.y, spriteDepthPos3.z, 1.0)
    .applyMatrix4(cam.matrixWorldInverse) //MODEL SPACE ==> VIEW/WORLD SPACE
    .applyMatrix4(cam.projectionMatrix); //VIEW/WORLDSPACE ==> CLIP SPACE
let depthVal = spriteDepthPos.z / spriteDepthPos.w; //CLIP SPACE ==> NORMALIZED DEVICE COORDS
depthVal = depthVal / 2 + 0.5; //NDC ==> WINDOW SPACE (uses the glDepthRange equation, wnd_z = ndc_z * (dfar-dnear)/2 + (dfar+dnear)/2)
depthVal = util.math.clamp(depthVal, 0, 1); //Clamp for funsies

```

After doing this I found out about `THREE.Vector3.project` which I probably could have used from the start.

---
Tags: javascript, sprites, three.js
---


# Question
Title: Retrieving DirectX9 Shader Input Parameters (vertex Input Layout)
Is it possible to retrieve the vertex input layout from an effect file in Direct3D9?

In Direct3D11 I can achieve this by using

```
D3D11_SIGNATURE_PARAMETER_DESC paramDesc;
ID3D11ShaderReflection* pRefector->GetInputParameterDesc(paramIndex, &paramDesc);

```

to get info about the input parameters.

I wish there was a way in Direct3D9 to do the same.

# Answer
> 1 votes
**There doesn't appear to be any way to do this in Direct3D 9**.

In theory the D3D11 shader reflection API looks as though it *should* work, since there's nothing in (at least this part of) it that actually requires Direct3D 11 (it doesn't even require a device to be created). In my own tests the D3DReflect call fails.

If you think about it this makes sense. Direct3D 9 is still very much built around the old fixed-function vertex inputs, and it's legal for a vertex declaration to provide input that the vertex shader doesn't consume, similarly legal for a vertex shader to consume input that a vertex declaration doesn't provide. The tighter coupling of input layouts with vertex shaders only came about in Direct3D 10:

> The Input Assembler (IA) replaces the Direct3D 9 style Vertex Stream Declaration and it's description structure is very similar in form. The main difference that the IA brings is that the IA layout object created must directly map to a specific format of shader input signature.

There are also possible historical reasons for this. In a similar way to the evolution of Direct3D 11 from Direct3D 10, Direct3D 9 was evolved from Direct3D 8, and in Direct3D 8 the vertex format and vertex shader were actually the same object. Unfortunately the old online documentation is now gone, but references to it may be found in the guidance for converting from Direct3D 8 to 9 (the text actually states "call IDirect3DDevice9::SetVertexShader" but this is clearly a typo and I've silently corrected it):

> For DirectX 8.x, vertex declarations are tied to vertex shaders ..... For vertex shaders, call IDirect3DDevice8::SetVertexShader with a handle to a previously create vertex shader. The shader includes a vertex declaration.

Ultimately the Direct3D 9 Effect interface is just a bunch of text parsing and wrappers around the actual real API (which is just a handful of Set\*Shader and Set\*ShaderConstant calls), so you could create the desired outcome yourself by doing the necessary text parsing yourself.

---
Tags: shaders, input, directx9
---


# Question
Title: How can I make Maya or Blender model work with mecanim?
I'm working on a simple game project, where I need a stick figure. Due to being stubborn and the desire to learn a new skill, I want to make the stick figure myself! I have followed several tutorials in both Maya and blender. For Maya, I'm using the student version. I have my stick figure rigged within Maya and blender, both utilizing their respective bone tools. I can manipulate their limbs well, enough. However, I can't seem to get the models to work with Mecanim.

I have the Kinect adapter for the PC and would like to be able to use it to create the animations utilizing a tool such as the Kinect v2 mocap animator.

How I can get my model to work with Kinect based mocap?

# Answer
> 2 votes
For the first question, read the documentation on preparing your model for mecanim: Preparing your own character and watch the introduction videos for mecanim on Unity's website Unity Animation Tutorials.

I'm not sure how to make it work with Kinect, but probably something along the lines of remapping the values you get from Kinect onto the skeletal bones of your character.

---
Tags: unity, blender, maya, mecanim
---


# Question
Title: Will an optional bad words censoring system affects the age rating as well?
My game project is a 2D top down RPG with dating simulator & visual novel elements in it, and I have a few parts of dialogue in my game that have bad words and used often by a character.

However, I'm afraid those bad words will affect the age rating up to 17+, so I decided to censor bad words optionally. This means player can enable bad words after confirming legal disclaimers.

Will this feature results more friendly age rating? I'm targeting for 15+ age rating.

# Answer
Different rating agencies have different criteria by which they rate games. But usually they rate the games by everything that's available in them (and sometimes even things which can only be enabled by mods). So if you have a censorship function which the player can turn off, many rating agencies will rate the game under the assumption that the player *will* turn it off.

So adding an optional censorship feature might have value for some of your players who don't like such content, but it will likely not have value for most rating boards.

Optionally, you could publish two editions of your game, a "dirty" one and a "clean" one. This is actually quite common in the visual novel genre. *Kanon* and *Air* exist in two versions, one adults-only version with explicit sex scenes and one without. But that means that you need to obtain separate ratings for both, submit both to different platforms, etc, etc. To avoid another "hot coffee" situation, you should actually **delete** all objectionable content from the clean version and not just dummy it out. That means you should actually change any objectionable strings in the clean version at compile-time and not just run a filter over them at runtime.
> 28 votes

# Answer
It's actually quite an interesting question, especially given the genres you're looking at. These are the bigs ones you have to worry about:

ESRB (North & Central America): The ESRB has a strange system that jumps straight from *T for Teen* (13) to *M for Mature* (17), so no matter what you do, unless you take out all the bad language and any and all suggestive content in the dating sim side of things, you're looking at a big ol' *M* on your game.

PEGI (Europe excluding the UK and Germany, though PEGI also covers India, Israel, Pakistan & Quebec): Similarly, you'll probably get a 16 from these guys whatever you do, because you're not getting a 12. 18 is generally reserved for stuff like excessive language, extreme violence and nudity. Having the option to disable these things does not affect their opinion.

VSC (UK): Video Games are no longer governed by the BBFC, who were nice enough to give Brütal Legend a 15 rating simply *because* you could disable the language and gore. Unfortunately, the VSC uses the same rating system as PEGI, so while they can have different opinions to PEGI, you're still gonna end up with the same rating.

USK (Germany): These guys are a bit peculiar, prioritising violence as the main point for rating games. However, that's not to say that you can get away with absolutely anything, just that they're more lenient when it comes to suggestive content and bad language. Good ol' Germany.

CB (Asutralia): List of banned video games in Australia. These guys have got to be the pickiest, most sensitive bunch who've ever rated anything ever. I'm not saying your game is going to be banned, I'm just saying that you're wayyy more likely to get a higher rating from this particular board. Honestly, the fact that it's part dating sim will make them think twice. And the worst part is, I'm not even exaggerating. I really wish I was.

Japan: Here's where things get really interesting. Note how I didn't put a specific board name for the Japanese. That's because they, naturally, have 3 different ratings boards, 2 of which are specifically tasked with rating PC Games of the Dating Sim, Visual Novel and Eroge genres. If your game is being released for PC, your game will be rated by the CSA and EOCS, simply because it has Dating Sim and Visual Novel content. However, if your game is for console or mobile, then it will be rated by the CERO instead, because they deal with any and all video games not on PC, as well as any PC Games not of the aforementioned genres.

What's also interesting is the criteria the CERO gives for it's *B* (12+) rating:

> Contains some content parents may not like for children under the age of 12. May contain mild sexual content, some violence, mild horror content or infrequent use of profanity.

From what I can tell, mild sexual content and infrequent use of profanity fit your game pretty well. So where you'd likely get a 16 in Europe, a 17 in North America and an 18 in Australia, you'll probably get more like a 15 in the UK and Germany, and a 12 in Japan.

I swear, in terms of what they prioritise as acceptable in modern society, Japan and Australia are real polar opposites.
> 19 votes

---
Tags: content-rating
---


# Question
Title: Not see through models without adjusting clipping panels
I'm making a FPS game in Unity3d with a lot of weapons, but when I'm aiming I can see through the weapon. I know I can adjust the near clipping panel, but when I do that, my terrain starts flickering. Is there some solution?

# Answer
A common solution to this problem is to create a second camera that only renders a specific custom layer. Then, you simply put the weapon in that same layer. The environment and UI are drawn by the first camera, with its ordinary clipping planes, and the second one can be set up to correctly display the weapon without affecting any other parts of your scene.

Of course, the fact that your terrain is flickering when you adjust your camera's clipping planes might also point to another problem that might need looking into.
> 0 votes

# Answer
You could render the weapon in a separate pass/camera, and just overlay the weapon onto the other view. In Unity this is pretty easy to do by adjusting stuff like the Clipping Mask and Clear Flags of the Camera.
> 3 votes

---
Tags: unity, first-person-shooter
---


title: Midpoint Algorithm - Error C++

text:
# Question
Title: Midpoint Algorithm - Error C++
I am currently finding an issue with my midpoint algorithm, I have been given a formula to work out the midpoint algorithm, but it seems to not correctly orbit. The aim is to get a more accurate version of the EulerMethod to create an more approximate orbit across all frame times. As the EulerMethod will cause a bit of an inaccurate orbit based on different frame-rates.

```
1st use Euler’s method to approximate half - way position / velocity :
position after half frame = current position +
half frame time * current velocity
velocity after half frame = current velocity +
half frame time * current acceleration

Calculate forces at half - way position to get half - way acceleration
Then use Euler’s method again with updated info :
position next frame = current position + frame time * halfway velocity
velocity next frame = current velocity + frame time * halfway acceleration

```

The method causes the 2nd sphere to move diagonally infinitely to the bottom right.

The Algorithm

```
void midpointmethod(CVector3& position, CVector3& velocity, CVector3& centre, float updateTime)
{
    CVector3 accel = OrbitAcceleration(position, Length(velocity), centre);
    //position = position + updateTime / 2 * velocity * updateTime;
    //velocity = velocity * updateTime / 2 * accel.Length() * updateTime;

    CVector3 halfpos = position + (updateTime / 2) * velocity;
    CVector3 halfveloc = velocity + (updateTime / 2) * accel;

    // calculate forces ?
    CVector3 halfwayaccel = accel / 2;

    CVector3 posnexf = position + updateTime * halfveloc;
    CVector3 velosnexf = velocity + updateTime * halfwayaccel;

    position = posnexf;
    velocity = velosnexf;

}

```

# Answer
I'm glad you could fix your issue. The midpoint algorithm is more accurate than standard Euler for orbits, being a second-order algorithm, but it still has the problem of gaining energy over time (meaning that your orbiting object will move closer or farther from the planet due to numerical innacuracy, though it may take a while depending on your time step). I think a better algorithm to look at would be "semi-implicit" Euler, which will preserve the energy in your system and allow for a better orbit. Here is a great resource: https://www.youtube.com/watch?v=kxWBXd7ujx0. Or, if you can afford to ignore velocity, the Verlet algorithm also works great for orbits. Cheers :)

*I wanted this to be a comment, but I don't have enough rep ...*
> 1 votes

# Answer
Figured the issue, It was rather trivial, I misunderstood the halfwayacceleration value, and wasn't actually getting the halfwayacceleration between the two points, but rather a different point which was not drawing it back into the sphere.

```
CVector3 halfpos = position + (updateTime / 2) * velocity;
CVector3 halfveloc = velocity + (updateTime / 2) * accel;

// calculate forces ?
CVector3 halfwayaccel = OrbitAcceleration(halfpos, Length(halfveloc), centre);

CVector3 posnexf = position + updateTime * halfveloc;
CVector3 velosnexf = velocity + updateTime * halfwayaccel;

position = posnexf;
velocity = velosnexf;

```
> 0 votes

---
Tags: c++
---


# Question
Title: DX11: Drawing with index buffer not working?
For our student project I've been tinkering with an OBJ-loader in order to import models into our application. It loads without issues, and drawing it *kind of* works without index (the model is obviously not represented correctly because I'm not using an index buffer) However, drawing with `DeviceContext->DrawIndexed` shows nothing on screen.

Without indexed drawing

With indexed drawing

Buffer creation method:

```
void ObjectLoader::CreateBuffers()
{
    //Index buffer
    D3D11_BUFFER_DESC iBufferDesc;
    memset(&iBufferDesc, 0, sizeof(iBufferDesc));
    iBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
    iBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    iBufferDesc.ByteWidth = sizeof(DWORD);

    D3D11_SUBRESOURCE_DATA indexData;
    indexData.pSysMem = &ind;
    pDevice->CreateBuffer(&iBufferDesc, &indexData, &pIndexBuffer);

    //Vertex buffer
    D3D11_BUFFER_DESC bufferDesc;
    memset(&bufferDesc, 0, sizeof(bufferDesc));
    bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    bufferDesc.Usage = D3D11_USAGE_DEFAULT;
    bufferDesc.ByteWidth = sizeof(TriangleVertex) * this->NumberOfVerts();

    D3D11_SUBRESOURCE_DATA data;
    data.pSysMem = tva;
    pDevice->CreateBuffer(&bufferDesc, &data, &pVertexBuffer);
}

```

Draw method:

```
void ObjectLoader::Draw()
{
    if (pDevice == nullptr)
        return;

    UINT32 vertexSize = sizeof(float) * 5;
    UINT32 offset = 0;

    pDeviceContext->IASetVertexBuffers(0, 1, &pVertexBuffer, &vertexSize, &offset);
    pDeviceContext->IASetIndexBuffer(this->pIndexBuffer, DXGI_FORMAT_R32_UINT, 0);
    pDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    pDeviceContext->DrawIndexed(vIndex.size(),0 , 0);

    //pDeviceContext->Draw(this->NumberOfVerts(), 0);

}

```

Index data is initially stored in an unsigned integer array before being passed to `D3DD11_SUBRESOURCE_DATA`

```
//index array
UINT* ind;

```

What the hell am I missing? I've looked at several books on indexed drawing and it seems pretty straight-forward. At first I thought the winding order was reversed but I checked this by simply reversing the index array; same result.

If you need more code let me know, but I feel this should suffice.

Thanks in advance!

# Answer
```
iBufferDesc.ByteWidth = sizeof(DWORD);

```

This is only storing a single index.
> 0 votes

---
Tags: c++, directx, directx11, index-buffer
---


# Question
Title: Loading player position from file but player object not at right position sometimes
In my current project I am developing a game saving system and I have encountered a problem where in some cases when I save the game and re-load it the player will not be loaded in at the correct position.

I've printed the position that is loaded in from file to the console to see if it's being changed and it's not.

Is there anything i'm not seeing?

For reference here's the two methods I use when loading the game:

```
    public void LoadData() {
    if (File.Exists(filename)) {
        byte[] soupBackIn = File.ReadAllBytes(filename);
        string jsonFromFile = encryption.Decrypt(soupBackIn, JSON_ENCRYPTION_KEY);
        copy = JsonUtility.FromJson<SaveData>(jsonFromFile);
        print(copy.playerPosition);
        DataToLoad();
    }
}

private void DataToLoad() {
    player.transform.position = copy.playerPosition;
    player.transform.rotation = copy.playerRot;
    player.playerHealth = copy.playerHealth;
    player.agility = copy.agility;
    player.attack = copy.attack;
    player.defense = copy.defense;
    player.strength = copy.strength;

    for (int i = 0; i < copy.inventory.Count; i++) {
        inv.AddItem(copy.inventory[i].id);
    }
}

```

# Answer
> 1 votes
I had a NavMeshAgent attached to my player from a previous prototype of a movement type for the game and it was interfering with where the player was positioned.

---
Tags: unity, json
---


title: How to get SDL2 to play 32bit WAV files

text:
# Question
Title: How to get SDL2 to play 32bit WAV files
I have WAV files of this format:

```
Opening audio decoder: [pcm] Uncompressed PCM audio decoder
AUDIO: 48000 Hz, 2 ch, s24le, 2304.0 kbit/100.00% (ratio: 288000->288000)
ID_AUDIO_BITRATE=2304000
ID_AUDIO_RATE=48000
ID_AUDIO_NCH=2
Selected audio codec: [pcm] afm: pcm (Uncompressed PCM)

```

`mplayer` plays them at 16bit, and I can convert them to `pcm_s16le` with ffmpeg very easily, and they **do** play in SDL2 fine.

**The Problem**

These files are 24bit, so we lose some audio converting them to 16bit I'd assume. Since SDL2 only supports 16bit (signed, unsigned, float) and 32bit, I figured I'd convert up to 32bit if that's possible, using this:

`ffmpeg -i input.wav -filter:a asetrate="48k" -ac 2 -c:a pcm_s32le output.wav`

If I try to use `pcm_s32be` I get: `pcm_s32be codec not supported in WAVE format` so I have to use little endian with Float, signed or unsigned...

FFmpeg converts it correctly, but SDL2 won't play the 32bit audio, it gives: `Unknown WAVE data format: 0xfffe`

---

Here are the valid SDL2 audio formats: https://wiki.libsdl.org/SDL\_AudioFormat we're looking at `AUDIO_S32LSB` specifically, and yes I am using SDL2 2.0.X

Note this error message comes from https://github.com/spurious/SDL-mirror/blob/13666b37a08a78bb209b5c584f74846f7e7b5cf2/src/audio/SDL\_wave.c#L473 Where it seems to be comparing to Swap16LE? and notices it's not pcm\_16 and dies.

Here is the definition for the constant we're using: https://github.com/spurious/SDL-mirror/blob/e04f23c7eaa7da672a8904b59001eff09da8db92/include/SDL\_audio.h#L103 note that the number given is not 0xfffe

Note: This is related to SDL2 specifically, so I believe it fits gamedev, I don't think posting to an audio related SA would garner as much intimate knowledge on the subject.

**TL;DR Question**

Does anyone have any insight on how I can get SDL2 to play my 24bit WAV, possibly by converting them to 32bit and getting them to play in SDL2

---

**EDIT #2:** Forget the last Edit (I removed).

I've implemented the LoadWav functionality locally and am getting the 0x0001 vs 0xfffe between 32bit wav and 16bit, so we're getting closer...

I'm inspecting how SDL2 is reading the WAV Header, and the difference between 32bit vs 16bit header is and why it's dying.

**EDIT #3:**

Here are some values from the two files:

```
32BIT WAVE:
RIFF: 1179011410, WAVELEN: 52043438
WAVE Magic: 1163280727
headerDiff: 4
Start of Chunk Loop:
Chunk Data: 254
headerDiff: 52
Chunk Magic: 544501094
0x000000000000fffe

16BIT WAVE:
RIFF: 1179011410, WAVELEN: 99312
WAVE Magic: 1163280727
headerDiff: 4
Start of Chunk Loop:
Chunk Data: 1
headerDiff: 28
Chunk Magic: 544501094
0x0000000000000001

```

So it seems the issue is when reading the chunks, note how the Header is double the size and returns the non-0x0001 value...

---

**Edit #4:**

Here are the two files each printed 1 byte at a time, and diffed (0-248 bits) 160-168 are where we're having issues. I need to learn the WAV format header information to proceed past this part.

```
@@ -2,10 +2,10 @@
   8 SRC Bytes: 0x49
  16 SRC Bytes: 0x46
  24 SRC Bytes: 0x46
- 32 SRC Bytes: 0xf0
- 40 SRC Bytes: 0x83
- 48 SRC Bytes: 0x1
- 56 SRC Bytes: 0x0
+ 32 SRC Bytes: 0xae
+ 40 SRC Bytes: 0x1e
+ 48 SRC Bytes: 0x1a
+ 56 SRC Bytes: 0x3
  64 SRC Bytes: 0x57
  72 SRC Bytes: 0x41
  80 SRC Bytes: 0x56
@@ -14,12 +14,12 @@
 104 SRC Bytes: 0x6d
 112 SRC Bytes: 0x74
 120 SRC Bytes: 0x20
-128 SRC Bytes: 0x10
+128 SRC Bytes: 0x28
 136 SRC Bytes: 0x0
 144 SRC Bytes: 0x0
 152 SRC Bytes: 0x0
-160 SRC Bytes: 0x1
-168 SRC Bytes: 0x0
+160 SRC Bytes: 0xfe
+168 SRC Bytes: 0xff
 176 SRC Bytes: 0x2
 184 SRC Bytes: 0x0
 192 SRC Bytes: 0x80
@@ -27,6 +27,6 @@
 208 SRC Bytes: 0x0
 216 SRC Bytes: 0x0
 224 SRC Bytes: 0x0
-232 SRC Bytes: 0xee
-240 SRC Bytes: 0x2
+232 SRC Bytes: 0xdc
+240 SRC Bytes: 0x5
 248 SRC Bytes: 0x0

```

**EDIT #5:**

Going off of this: http://soundfile.sapp.org/doc/WaveFormat/

We have

Subchunk1Size 16 for PCM. This is the size of the rest of the Subchunk which follows this number.

AudioFormat PCM = 1 (i.e. Linear quantization) Values other than 1 indicate some form of compression.

**So Clearly there's some issue with how I'm converting it to 32bit, as it has a 40 chunk size, rather than 16, and 0xfffe rather than 1.**

# Answer
> 0 votes
As of **EDIT #5**, we can conclude that the Audio Format section of the header is 0xfffe and SDL2 only allows 0x0001 (as of PCM standard).

With this post: https://stackoverflow.com/a/42048916/5698848

It's come to understand that ffmpeg (and sox apparently) add a "wave format extensible" flag which is 0xfffe but **is not needed and can be replaced manually with 0x0001**

With this replacement, SDL2 will play the audio file flawlessly, assuming one uses the proper flag (AUDIO\_S32LSB in my case)

# Answer
> 1 votes
Just as a heads up, this was just fixed in SDL: https://hg.libsdl.org/SDL/rev/748bedefb03f

---
Tags: sdl2, audio
---