# Question
Title: Send large amount of vertices to graphics card
I am programming at the moment a minecraft clone.

The advantage of this clone is that the whole world is handled as a model. That means: The whole world is represented by 2d flat tiles and is uploaded to ONE vertex buffer.( therefore ONE drawcall)

The indices are stored seperatly in the hard drive because to re generate them every time the game starts is a bit overkill.

The loading time for a 64x64 ( 16x16x256 á la chunk) lies between 3 to 5 seconds.

The problem ist following: I calculated the amount of vertices : One VertexPositionTexture has a size of 20 bytes. Multiplied by 8702348 ( because of 8702348 vertices ) the whole amount sent to the graphics card is over 160 MB !

It's no problem for the graphics card: Constant 60 FPS... but I am intended to _ implement infdev. This means the game has to upload frequently over 160 MB to the graphics card: Pure overkill.

I want to avoid using a vertex buffer for each chunk in order to have a single draw call.

Can you suggest a solution?

Thanks.

The project can be found on https://github.com/NET-D3v3l0p3r/XChunk/tree/master/Chunk

# Answer
I think you're operating under a false premise (namely, that the total draw call count is the ultimate arbiter of performance).

This isn't the case. Certainly, reducing draw calls is a good idea, but sacrificing everything *else* on that alter is going to lead you down a path where you eventually hurt performance instead.

For example, you're ignoring the costs of doing everything else with all of this extra geometry that, for the most part, probably isn't visible in the world. You may be paying a huge cost for overdraw or over-transformation of geometry, for example.

Chunking up the world is a classical divide-and-conquer strategy: reduce the instantaneous operable problem space by divvying up the total problem space into smaller parts that can be handled on their own (or most importantly, *ignored* on their own).

I think you will eventually simply hit a wall where you cannot solve performance issues if you remain adamant that you use only a single draw. That said, there are similar divide-and-conquer approaches you can try.

* If it's possible that only certain *subsets* of the vertex attributes change when you need to reupload (for example, if it's only the texture coordinates that change to indicate that a block is now gone, or a new type of block, et cetera), you can put the dynamic aspects of that vertex data in its own vertex attribute stream. That way you have a static vertex buffer which never changes, and a dynamic one that uploads every frame. The size of the dynamic buffer will be drastically smaller (for example, around 60MB or so if all it contains are 2D texture coordinates). You can have multiple stream sources per draw call, so this still lets you use one draw call.
* If your actual GPU workload is small (that is, your shaders are super simple), you can potentially offload some of the world handling dynamic aspects of the world to the GPU itself, possibly storing any input you need for that handling in a texture that you update every frame. Similar to the multiple vertex stream source option above, the idea here is to confine the data you upload every frame to *only* data that is potentially changing every frame and leave the static stuff alone, so you only need to upload it once.
* Similar, it sounds like your world is essentially heightmap based (that's what I get from your statement that "the whole world is represented by 2d flat tiles;" thus there are no caves or anything like that. It's reasonable in such an implementation to represent each tile as a single vertex you *expand* to four in the shader pipeline, for example in a geometry shader. It's potentially possible to do this in a fully-3D (caves allowed) world as well, though harder. This can reduce the total data set (indices *and* vertices) significantly as well.
* You can try to update only a portion of the vertex buffer based on where the player actually is; if you can know that the player won't be able to see certain parts of the world that are very far away, you can use a buffer that doesn't discard completely when mapped to the CPU and write only a portion. This may be a performance win, although it may not. You'd have to profile and see.
> 1 votes

---
Tags: xna, monogame
---


# Question
Title: Determine where is player facing up, down or left right
I have a player object who can rotate(face using mouse) up, down left right and can face straight. I am willing to know that how to determine that where is camera facing? Either it is looking up or down?? while the player is continuously moving in a up/down surface.

# Answer
> 1 votes
Use dot products.

Assuming left, down, up, and right are global directions you dot the Camera fwd with each vector respectively (You actually only need to do two calculation because of how dot products work).

It would look something like this

```
//Will return between 1 and -1. 1 means left, -1 means right
float leftRight = Vector3.Dot(camFwd,Vector3.left);
//Will return between 1 and -1. 1 means up, -1 means down,
float upDown = Vector3.Dot(camFwd,Vector3.up);

```

Do whatever conditional checks you need to determine direction priority.

# Answer
> 0 votes
Have the game check the camera's rotation. If the camera's x rotation is around 90 degrees they are facing up. if the camera's x rotation is around -90 degrees they are facing down. if the camera's rotation x rotation is around 0 they are facing forward and if it is around 180 they are facing backwards. Then have the camera spawn a ray that is equal to the rotation of the camera and use mathf.aproxemetly to see which rotation is closest.

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


# Question
Title: Using max for entry time in swept collision
I was reading this tutorial on swept AABB collision detection, and I was confused by this piece of code:

```
// find the earliest/latest times of collision
float entryTime = std::max(xEntry, yEntry);
float exitTime = std::min(xExit, yExit);

```

The tutorial says this about this code:

> `entryTime` will tell use when the collision first occurred and `exitTime` will tell us when it exited the object from the other side. This can be useful for certain effects, but at the moment, we just need it to calculate if a collision occurred at all.

So if `entryTime` is supposed to be the first time a collision occured, then why is `max` being used to determine the first time of collision? Shouldn't `min` be used instead? If `max` is used, then the highest value will be returned. The highest value would be the time of the last collision. Obviously this must be the correct way of doing this, but I'm not understanding it. If you are trying to find the first axis to collide, it would seem intuitive that you use `min`.

# Answer
> 1 votes
The smaller of the times `xEntry` and `yEntry` will be when the blue box crosses the first of two edges of the green box ("first" in the image below). The greater of the two times is when the blue box crosses the second edge ("second", below). The blue box isn't touching the green one until it crosses that second edge.

In other words, the blue box touches the green one when it is between `xEntry` and `xExit` and also between `yEntry` and `yExit`. If it's between in x but not y, then it isn't touching, and vice-versa.

The reverse is true for the exit time: As soon as one edge is crossed, the boxes are no longer touching.

---
Tags: collision-detection
---


title: SDL2 Rendering based on frames

text:
# Question
Title: SDL2 Rendering based on frames
Is it possible to render a particular object on the screen for a certain number of frames without having to delay the rendering? Thanks

# Answer
Indeed it is.

Assuming that your object has a method such as `Update()` that gets called once per fame, you can simply count your frames and toggle a boolean that you use to determine the rendering.

```
class Object
{
public:
    bool visible = true;

    void Update()
    {
        frames++;

        visible = frames < 10;  // Or however many frames you want to display the object.
    }
private:
    int frames = 0;
};

// Main loop:
while (True)
{
    HandleEvents()()

    object.Update()

    ClearWindow()
    if (object.visible)
    {
        object.Render()
    }
    UpdateWindow()
}

```

That is a very basic example of what you might be looking for.
> 1 votes

---
Tags: rendering, sdl, sdl2
---


# Question
Title: Unity / NodeJS Projectile synchronization
I am working on a MOBA game similar to League of Legends. I am building the game server system in NodeJS/Socket.IO but I'm running into issues on figuring out the best way to handle projectiles (aka player skill-shot abilities) on the server-side. The Main goal is to be able to spawn a projectile (or projectiles) on the server-side and update the position in a certain direction (all on the server-side separate from Unity) until I specify the projectile to be destroyed. This way, each time the projectile moves I can check with every single players current position and see if the projectile hit (thus allowing me to damage the player on the server-side).

How could I achieve this effect, or something similar?

# Answer
As far as I know Pomelo has no way to do this internally. It is more of a message transport framework than an engine. So to answer your question you can do this in at least two different ways: you can implement an "update" method in your server that will run periodically and update the position/status of all your entities accordingly or you can have an update method for each projectile instance that will update the position of the projectile at every tick. The latter might be easier to implement but will make it more complex to manage and understand what code is running when. Keep in mind that the setTimeout function in javascript is not very precise. The intervals might be off by a few milliseconds so keep track of how much time has passed between updates independently, don't assume the delay was followed rigorously. Also remember that you may need to bind a context to the function being called. This is usually not recommended but there are node libraries that implement faster but more restrictive bind operations that should work.

Also note that, at least when I used the Unity client, there was no support for UDP packets on the client (although this is easy to implement). If you are going to use TCP, remember to disable Nagle's algorithm by passing setNoDelay as an option to the connector.

You are also using a asynchronous engine, and in order for users to not notice lag, you will have to implement some features client side to compensate for lag. In my experience player movement is critical and clicking on buttons to attack has a less noticeable lag, so start there. You will also have to implement some client side movement prediction for the other player characters or position will be way off.

You can also use a synchronous engine, there was a project to implement this in Unity. That way you can use Pomelo as more of a message relay and less as a game engine. Alternatively you can use Unity to setup a server and run all the code there and use Pomelo to create lobbies and direct players to the appropriate servers.
> 0 votes

# Answer
Fabio's answer is right. I wrote a multiplayer Command & Conquer: Red Alert 2 clone back in college, in Java using NIO for multiplayer. I came up with or read somewhere about the concept of "frames", which is basically the same as what Fabio refers to as "ticks." Frames or ticks should be controlled on the server in a timer. I think I spaced them 100ms apart, but I don't remember. The server should keep in memory (like a javascript object or array) the positions of all mutable/changeable objects (characters, tanks, buildings etc), on a given map. For development purposes or an alpha version (just to get a feel for how it works), the server should serialize the javascript object into JSON representing the assets on the map and send it to the clients on every frame (every 100ms or so). Each client should only update its view of the map when it receives the JSON from the server (again, about every 100ms it will receive a new JSON object). When the client wants to move a character, fire a bullet, etc, it should send a JSON request to the server describing the attempted action, but no change should happen on the client's view directly (except maybe a red x showing where a character is going to move). The server will then receive the JSON action and compute the movement or interaction, interacting with the timer so that the event happens over time. The client will see the action (along with other clients) because the server will be sending out the frames every tick.

To improve this as far as bandwidth concerns, you could only send out changes/updates (updates to the javascript object tracking game state) to the clients every frame. I would still send the entire javascript object every 5 minutes or so in case there are bugs in your changes/updates code or dropped packets if you're using UDP.

There are more advanced ways to deal with latency than this, which you may need to explore as you improve your game out of alpha version, but this should get you started.
> 0 votes

---
Tags: unity, multiplayer, node.js
---


title: Wrong UV calculation

text:
# Question
Title: Wrong UV calculation
For a personal project, I'm trying to implement a tilemap. My goal is to obtain this

But all I got is this

I am calculating the UV coordinates inside my shader, with this formula. 8 and 13 is the width and height of my tileset, in tile.

`vs_uv = (1.0 / vec2(8, 13)) * (vec2(tile / 8, tile % 13) + vertex);`

Where tile is one element of this array

```
GLint map[] = {
     0,  1,  2,  3,  4,  5,  6,  7,
     8,  9, 10, 11, 12, 13, 14, 15,
    16, 17, 18, 19, 20, 21, 22, 23,
};

```

and where vertex is line of this array

```
GLfloat vertices[] = {
    0.0f, 1.0f,
    1.0f, 0.0f,
    0.0f, 0.0f,

    0.0f, 1.0f,
    1.0f, 0.0f,
    1.0f, 1.0f
};

```

Here's the full code of the example :

```
#include <algorithm>
#include <memory>
#include <cstring>

#include <boost/filesystem.hpp>
#include <boost/multi_array.hpp>
#define GLEW_STATIC
#include <GL/glew.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <SDL2/SDL.h>

#include <pck/global.hpp>
#include <pck/program.hpp>
#include <pck/utils/stb_image.h>
#include <pck/window.hpp>

namespace fs = boost::filesystem;

const int WIDTH = 800, HEIGHT = 600;

GLint map[] = {
     0,  1,  2,  3,  4,  5,  6,  7,
     8,  9, 10, 11, 12, 13, 14, 15,
    16, 17, 18, 19, 20, 21, 22, 23,
};

GLuint map_w = 8;
GLuint map_h = 3;

int main()
{
    // Wrapper around SDL2 window, also initializing OpenGL
    pck::Global::window.reset(new pck::Window("Test_gl", WIDTH, HEIGHT));

    // Vertices buffer
    GLfloat vertices[] = {
        0.0f, 1.0f,
        1.0f, 0.0f,
        0.0f, 0.0f,

        0.0f, 1.0f,
        1.0f, 0.0f,
        1.0f, 1.0f
    };

    // Positions buffer
    glm::vec2 positions[24];

    int index = 0;
    for(size_t j = 0; j < map_h; ++j)
    {
        for(size_t i = 0; i < map_w; ++i)
        {
            positions[index++] = glm::vec2(i, j);
        }
    }

    // Texture declaration
    GLuint tex_ID;
    glGenTextures(1, &tex_ID);

    int w(0), h(0), c(0);
    unsigned char* data = stbi_load("tileset.png", &w, &h, &c, STBI_rgb_alpha);

    if(data == nullptr)
    {
        std::cout << "Failed to load texture\n";
        stbi_image_free(data);
        return 1;
    }

    glBindTexture(GL_TEXTURE_2D, tex_ID);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

        if(c == 3)
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
        else if(c == 4)
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);

        glGenerateMipmap(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, 0);

    stbi_image_free(data);

    GLuint VAO;
    glGenVertexArrays(1, &VAO);

    glBindVertexArray(VAO);
        GLuint vertex_VBO;
        glGenBuffers(1, &vertex_VBO);

        glBindBuffer(GL_ARRAY_BUFFER, vertex_VBO);
            glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
            glEnableVertexAttribArray(0);
            glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), (GLvoid*)0);
        glBindBuffer(GL_ARRAY_BUFFER, 0);

        // Also set instance data
        GLuint positions_VBO;
        glGenBuffers(1, &positions_VBO);

        glBindBuffer(GL_ARRAY_BUFFER, positions_VBO);
            glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec2) * 24, &positions[0], GL_STATIC_DRAW);
            glEnableVertexAttribArray(1);
            glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), (GLvoid*)0);
        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glVertexAttribDivisor(1, 1);

        GLuint tiles_VBO;
        glGenBuffers(1, &tiles_VBO);

        glBindBuffer(GL_ARRAY_BUFFER, tiles_VBO);
            glBufferData(GL_ARRAY_BUFFER, sizeof(map), map, GL_STATIC_DRAW);
            glEnableVertexAttribArray(2);
            glVertexAttribPointer(2, 1, GL_INT, GL_FALSE, sizeof(GLint), (GLvoid*)0);
        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glVertexAttribDivisor(2, 1);
    glBindVertexArray(0);

    // Shader for instanciated tiles
    pck::VertShader vs(std::string(R"(
        #version 330 core
        layout (location = 0) in vec2 vertex;
        layout (location = 1) in vec2 position;
        layout (location = 2) in int tile;

        uniform mat4 model;
        uniform mat4 projection;
        uniform ivec2 tileset_tile_size;

        out vec2 vs_uv;

        void main()
        {
            gl_Position = projection * model * vec4(vertex + position, 0.0f, 1.0f);

            vs_uv = (1.0 / vec2(8, 13)) * (vec2(tile / 8, tile % 13) + vertex);
        }
    )"));

    pck::FragShader fs(std::string(R"(
        #version 330 core

        uniform sampler2D image;

        in vec2 vs_uv;

        out vec4 fs_color;

        void main()
        {
            //fs_color = vec4(vs_uv, 0.0f, 1.0f);
            fs_color = texture(image, vs_uv);
        }
    )"));

    std::shared_ptr<pck::Program> program(new pck::Program(vs, fs));

    // Uniforms
    program->use();

    glm::mat4 model;
        model = glm::rotate(model, 0.0f, glm::vec3(0.0f, 0.0f, 1.0f));
        model = glm::scale(model, glm::vec3(16.0f, 16.0f, 1.0f));

    pck::Global::zoom = 2;
    glm::mat4 projection = glm::ortho(0.0f, static_cast<GLfloat>(pck::Global::width / pck::Global::zoom),
        static_cast<GLfloat>(pck::Global::height / pck::Global::zoom), 0.0f, -1.0f, 1.0f);

    glm::ivec2 tileset_tile_size(8, 13);

    glUniform2iv(glGetUniformLocation(program->ID(), "tileset_tile_size"), 1, glm::value_ptr(tileset_tile_size));

    glUniformMatrix4fv(glGetUniformLocation(program->ID(), "projection"), 1, GL_FALSE, glm::value_ptr(projection));
    glUniformMatrix4fv(glGetUniformLocation(program->ID(), "model"), 1, GL_FALSE, glm::value_ptr(model));

    //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

    while(pck::Global::window->is_closed())
    {
        while(pck::Global::window->poll_event() != 0)
        {
            if(pck::Global::event->type == SDL_QUIT)
            {
                pck::Global::window->close();
            }
            else if(pck::Global::event->type == SDL_KEYDOWN)
            {
                if(pck::Global::event->key.keysym.sym == SDLK_ESCAPE)
                    pck::Global::window->close();
            }
        }

        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        glBindTexture(GL_TEXTURE_2D, tex_ID);

        program->use();

        glBindVertexArray(VAO);
            glDrawArraysInstanced(GL_TRIANGLES, 0, 6, 24);
        glBindVertexArray(0);

        pck::Global::window->update();
    }

    return 0;
}

```

# Answer
I finally found the right formula, where (8.0, 13.0) is the number of tiles in my tileset, in width and height.

```
vs_uv = (1.0 / vec2(8.0, 13.0)) * vec2(mod(tile, 8.0), floor(tile / 8.0)) + (vertex / vec2(8.0, 13.0));

```

Giving me this
> 0 votes

# Answer
I think the line you've highlighted is the problem:

```
vs_uv = (1.0 / vec2(8, 13)) * (vec2(tile / 8, tile % 13) + vertex);

```

Your vertices have coordinates that are between 0 and 1. Because your using `GL_TEXTURE_2D`, your texture coordinates need to be between 0 and 1. So the above calculation will always give values greater than 1, except for the first tile.

I would think that you'd need the width and height of your texture atlas to calculate this properly. Without seeing your texture atlas, it's hard to tell you the right thing to do, but if your tiles are laid out in a single row in the texture atlas, it should be something like this:

```
vs_uv = tile * tileSize;

```

where `tileSize` is the width and height in normalized coordinates of 1 tile of the texture atlas. So if you have 5 tiles that are 8 x 13 pixels laid out in a single row, your texture atlas will be 40 x 13. Normalizing that, 1 tile is 1/5 width and 1 height, so `tileSize` would be `(0.2, 1.0)`.
> 2 votes

---
Tags: opengl, textures, tilemap, uv-mapping
---


# Question
Title: Dialogue Audio: Forming sentences using different recordings
I am working on a game where the exact dialogue to be spoken out depends on context. The most common use case is for scoring - The game keeps player score and I want the game to tell the player her current score using audio. For example, audio can be - "You've killed 10 enemies", or "You're score just crossed 100!". In both these sentences, the numbers 10 and 100 depend on the current game context.

What I would want to do is record the sentence "You've killed .... enemies", and then also record all the numbers separately, and then form a complete sentence when needed. Are there any solutions which can do this in a way that the dialogue sounds fairly natural?

# Answer
There is no technical solution to this. It is a matter of the dialog recording director and editing, and it is hard work. If you've ridden modern trains in Europe, you will find that they do this (with varying levels of success) for the announcements at stations and in trains.

The short answer is: You have to get the voice actor to read all numbers at the same pitch, ideally during the same recording session, and at the right pitch to fit into the flow of the sentence.

You then have to edit all recordings so they have the same amount of silence at the start and end, so that when plugged into the sentence there are no unnatural pauses around the insertion.

Given the people tend to bind words together ( e.g. You'd likely say "You hafive hundred points" and not actually fully enunciate the end of "have" and then pause), it would likely still sound a bit unnatural.

If you also take into account how much more work it is for a voice actor to repeatedly hit the same pitch (and energy level) and how much more likely they will have to re-do the line, and how much time it takes to edit the recorded bits together so they sound good, plus develop engine support for loading several phrase fragments and playing them back gaplessly, *and* taking into account how cheap disk space and bandwidth are these days, and how well voice audio compresses, it usually makes more sense to record the entire sentence repeatedly than try to cut it together from multiple parts.

This also means the voice actor can play with the voice lines a bit, e.g. Do special versions for higher numbers, and it will sound more human if the sentence melody, speed etc. vary a bit as the numbers rise.

In fact, many AAA games include several versions of the same phrase, or even slightly different phrasing to provide more variety.
> 1 votes

---
Tags: audio, sound
---


# Question
Title: How to make a bullet shoot in the direction of the gun in mobile?
I am working in unity with c#. I am working on a 2D platformer for mobile. The way I currently have it setup is one joystick that moves the charatcer makes the charatcer arm rotate and make the charatcer shoot the gun when pressed. Which all workd fine. But the problem I am having is the bullets from the gun are not going in the correct direction. Currently the bullets go to the rigtht no matter where I point the gun. I have tried in the raycats to use transform.right and transform.forward. All end up with the same result. the firepoint for the gun is an empty game object and the firepoint in the script is an tranfrom. It is an child of the gun so I thought it would use the same rotation but I am not sure of I need to say what rotation I need for the raycast. I tried changing it to an GameObject in the script but I got the same results. If someone could please help it would be grealty appreciated!!!

Here is the shoot function with the raycast.

```
public void Shoot ()
{
    Vector3 firePointPosition = new Vector3 (firePoint.position.x, firePoint.position.y, 0f);
    RaycastHit2D hit = Physics2D.Raycast (firePointPosition, firePoint.transform.right, 100, whatToHit, 0f);

    Debug.DrawLine(firePointPosition, (firePointPosition)*100, Color.cyan);
    if (hit.collider != null)
    {
        Debug.DrawLine(firePointPosition, hit.point, Color.red);
        Enemy enemy = hit.collider.GetComponent<Enemy>();
        if (enemy != null)
        {
            enemy.DamageEnemy(Damage);
            //Debug.Log("We hit " + hit.collider.name + "and did " + Damage + "damage");
        }
    }

    if (Time.time >= timeToSpawnEffect)
    {
        Vector3 hitPos;
        Vector3 hitNormal;

        if (hit.collider == null)
        {
            hitPos = (firePointPosition) * 30;
            hitNormal = new Vector3(9999, 9999, 9999);
        }
        else
        {
            hitPos = hit.point;
            hitNormal = hit.normal;
        }

        Effect(hitPos, hitNormal);
        timeToSpawnEffect = Time.time + 1 / effectSpawnRate;
    }
}

```

And here is the effect method

```
void Effect (Vector3 hitPos, Vector3 hitNormal)
{
    Transform trail = Instantiate (BulletTrailPrefab, firePoint.position, firePoint.rotation) as Transform;
    LineRenderer Lr = trail.GetComponent<LineRenderer>();

    if (Lr != null)
    {
        Lr.SetPosition(0, firePoint.position);
        Lr.SetPosition(1, hitPos);

    }

    Destroy(trail.gameObject, 0.04f);

    if (hitNormal != new Vector3(9999,9999,9999))
    {
        Transform hitParticle = Instantiate(HitPrefab, hitPos, Quaternion.FromToRotation (Vector3.right, hitNormal))as Transform;
        Destroy(hitParticle.gameObject, 1f);
    }

    Transform clone = Instantiate (MuzzleFlashPrefab, firePoint.position, firePoint.rotation) as Transform;
    clone.parent = firePoint;
    float size = Random.Range(0.6f, 0.9f);
    clone.localScale = new Vector3 (size, size, size);
    Destroy(clone.gameObject, 0.02f);

    //Shake the Camera
    camShake.Shake(camShakeAmt, camShakeLength);

    //Play shoot sound
    audioManger.PlaySound(weaponShootSound);
}

```

# Answer
> 1 votes
So, just to make sure we're on the same page. There are to "types" of vectors: Direction and Position.

Position vectors are really just a "direction from zero" but for out purposes they behave differently. You use these to **LOCATE** objects

Direction vectors indicate a displacement in xyz space. You use these to **MOVE** objects.

Just so we're clear, this line doesn't make much sense.

```
Debug.DrawLine(firePointPosition, (firePointPosition)*100, Color.cyan);

```

You're just scaling the vector in regards to the origin. Since you're debuging a raycast (position, direction) rather than a point to point (position, position), you should actually use:

```
Debug.DrawRay(firePointPosition,firePoint.right * 100);

```

---

In your situation, the fire point is a location vector, and you need a direction vector to determine the final location of your projectile.

You're using transform.right which should work as long as you are rotating the transform (it only changes when the transform rotates). If you never rotate the transform, the projectiles will *always* fire straight right.

So make sure that transform has actual rotation. In the inspector view, highlight the gameobject and view the axes to make sure things are rotating as they should be.

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


# Question
Title: Is it reasonable to ask for all rights for music when hiring a musician?
I've made a game and now I need to add real sounds and music to it. For the first time I've decided to hire a musician to make music for my games. Before I used to buy sound packs and licenses for tracks.

The negotiations didn't go well as the price was too high for me and the artist didn't like the idea of selling me the music and wanted to only license it to me.

I'd like to know if I've made a mistake or if I've been unreasonable.

Just to be specific, we're talking about 6 tracks, 90 seconds long each. The music is chip-tune done by one musician (that's important since I understand that hiring an orchestra would cost more than hiring just one person).

What I wanted was to get the tracks with all the rights, other than the authors rights - putting their name in the credits.

I've been told that nobody does this and the musician always keeps the rights to later sell OST etc. And if I want all the rights, one track would cost me $500. And even just getting a one-title license would cost me $200.

I have no idea if that's a standard market price, it seems high for me.

1. Is the price reasonable?
2. Is it unreasonable for me to ask for music with all the rights?

# Answer
> 23 votes
When you are asking for "all the rights", then you need to ask youself if you really need "*all* the rights". I don't know your long-term business plan, so I don't know which of these rights you actually need:

* Use the music for your current game (ok, that's obvious)
* Use the music for any future games
* Be **the only one** who is allowed to use the music for a game
* Be **the only one** who is allowed to use the music for **any** form of media
* Be allowed to resell the rights to the music to 3rd parties, in case you chang your mind about the previous two points
* Be allowed to make derivative works of the music (remix or reinterpret it)
* Be allowed to monetize the music by itself, for example in form of an OST album
* Have these rights for all eternity (and not just a few years)

All these points mean that the original musician loses a potential way of monetizing their work in the future. The creator seems to believe that the amount they lose out on seems to be around $500, so that's the reimbursement they demand from you in order to give up on those business opportunities. What you need to ask yourself is if these rights are also worth that much to *your* business interests.

So the reasonable thing to do would be to figure out together with the musician what business needs you have, what business needs the musician has, and where you can find common ground regarding what rights exactly you buy and what rights the musician retains.

Keep in mind that none of these points need to be binary. Deals like "you can do that, but only under *condition*" or "only when you pay *$x* each time you do it" are not uncommon.

You can also agree on some form of revenue splitting agreement in cases where you both benefit from cross-promotion. For example, the sales of the OST album will depend just as much on the quality of the music as on the popularity of your game, so a revenue sharing deal could make sense here.

By the way, the more complex your agreement will get, the more useful can it be to get professional legal advise on board to draft the exact wording of the contract to make sure it really says what you want it to say.

# Answer
> 3 votes
"All the rights" is rather vague. Many intellectual property rights are applicable and even though this subject is covered by widely adopted international treaties, laws vary around the world. Some rights are transfered automatically, some by contract. Some can only be transfered by notarial deed and some rights are not legally transferable at all. Even if they are, they may be of little value to anyone but the author. Examples include being credited and the ability to object to mutilation of a work.

Therefore, a licence is often used instead. The terms are of course subject to negotiation. You can expect a musician to push back on a clause that prevents him from selling the OST or using the tracks for promotional purposes, though exclusivity in the sense that the author cannot grant (or have granted) distribution rights to anyone else, is a fairly common condition.

Whether or not the price is reasonable, is harder to answer. There are musicians out there of all skill levels and the quality of their work is not a constant: you spend more to get more. You can hire a composer to play your game for a few hours, discuss some ideas with you in a musical brainstorm session, create several draft tracks, submit them for review and after the third revision, rent a studio, hire a sound engineer and some musicians to record and produce the track, but it might cost a lot more than $200. Then again, perhaps the same artist recorded a chip-tune at home the other week, unrelated to your game, just for fun, on consumer-grade equipment, and is willing to sell it to you for a few bucks.

Bottom line, $200 is not necessarily above or below the market price. Obviously, it seemed high to you, and that's what's relevant. You can definitely get the work done on a lower budget and end up with a high quality soundtrack for your game, but you may need to compromise. A professional should be able to explain to your satisfaction what you can expect from him at a certain price point.

---
Tags: sound, music, hiring
---


# Question
Title: How to get a 2D vectorial terrain from an image for Java collision detection?
I'm trying to make a 2D Java-only game with a terrain like the one shown below. In the previous games I made, I used tile based collsions, but now, I want to use vector based collsions, as an uneven terrain would require minuscule tiles.

What I'd like to know, is how I can get the vectors from the map above, and how I should use them.

For the first part, I could manually measure out each of the coordinates, as shown below, but especially for lager and more detailed maps, that would be a tremendous amount of work.

I was wondering if there is a way to do this easier. I've seen tools that let you draw the vectors over the image, but those export only to engines like Box2D and Unity, which are programmed in different code languages. As I stated before, I only want to use Java.

For the second part, if I have the coordinates of the vectors, what should I do with them? I previously used rectangles, but now I would need to use either lines or polygons that connect each coordinate.

Also, how do I check for collisions between the player's polygon or rectangle, and the polygons or lines that form the terrain? When using rectangles, I could use `playerR.Intersects(terrainR)`, but how can I do this with a terrain?

A link to an easy-to-understand tutorial would be a nice answer too, especially for the last part of my question.

Thanks in advance.

# Answer
> 1 votes
> I want to use vector based collsions, as an uneven terrain would require minuscule tiles

This is a good approach. Don't mix display and logic: keep a detailed map (pixel-based) for display, and a vector version for logic.

Most games, even 3d ones, have these two versions: a collision mesh, and a display mesh.

> What I'd like to know, is how I can get the vectors from the map above, and how I should use them. For the first part, I could manually measure out each of the coordinates, as shown below, but especially for lager and more detailed maps, that would be a tremendous amount of work.

You're correct. AAA games can pay their artists to make the collision mesh of all their assets, or pay to develop a tool to do this for them (mesh decimation). But those solutions are expensive/a waste of time for the hobbyist game developper.

> I was wondering if there is a way to do this easier.

There are image-analysis algorithms (skeletton extraction, etc). Those are fidgety, hard to control and hard to code. There would be few available, and fewer in Java. They are usually scientific-minded, I don't think it is very suitable for a game development.

---

I suggest you work the other way around: generate the vector level by hand and let the game display that with augmented precision by selecting tiles that agree with the vector logic. This has the following advantages:

* Less hand work. In design phase, you'll decide high-level object placement, not fiddle with low-level graphics. Easier to define a generic rectangle-shaped room than take the brush and draw it out.
* Easier automation. It's easier to complexify a geometry (introduce displacement, noise, tile variations) than to simplify it (in which case you'd have to be careful of not obstructing small passages, etc.)
* Easier maintenance. If you chose to change your aesthetics, no need to redefine the whole graphics--\>Vector process. You just swap the tileset, and regenerate.

> if I have the coordinates of the vectors, what should I do with them? I previously used rectangles, but now I would need to use either lines or polygons that connect each coordinate.
>
> Also, how do I check for collisions between the player's polygon or rectangle, and the polygons or lines that form the terrain? When using rectangles, I could use playerR.Intersects(terrainR), but how can I do this with a terrain?

In general, a lot of resources exist, even on SO, like this one.

If your characters follow gravity, a few raycasts downwards would do the job very nicely. You'll simply have to have a line-line intersection routine, and get the closest.

> A link to an easy-to-understand tutorial would be a nice answer

See this Gamasutra article for a full-fledged collision detection algo. There are no easy solutions to player-mesh collision in the general case.

---
Tags: java, 2d, collision-detection
---


# Question
Title: No more OpenGLES 2 UWP template in Visual Studio 2017?
In Visual Studio 2015, a convenient cross-platform C++ project template was available named "OpenGLES 2 Application (Android, iOS, Windows Universal)." I cannot find this template in Visual Studio 2017; only the Android + iOS template is present.

A response to this post on the VS dev community site suggests the template was removed by design. If so, are there any alternatives I might consider to give a similarly streamlined workflow?

# Answer
You can dig up the template from a prior VS version and move it forward; it might take a bit of tweaking, but it should work. The built-in templates are in the VS installation directory, for example, in `C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\ItemTemplates`

You could also use VS 2015 to create an instance of that template you want to use, and then manually turn that project into a custom template for your own use.

The new project dialog also has a place where you can search for templates in an online database of community contributions (kind of like the add-on community options), so you may be able to find yourself a suitable template there.

If none of the above are options, simply use VS to create a new instance of that template, save that created project structure off someplace, and copy or clone it when you want to make a new project. The poor man's template, as it were.
> 1 votes

---
Tags: cross-platform, visual-studio
---


# Question
Title: How to bounce the ball off a collider and destroying it using trigger?
I am making a Breakout game. I have bricks with box colliders and the ball is a rigidbody2d with circular collider. I have applied the PhysicsMaterial2D on the ball with bounciness set to 1 so the ball is bouncing off the bricks as intended. Now I want to detect this collision in C# so I could destroy the brick but I cannot enable the isTrigger property as it will disable the collisions in that brick. So, I am looking for a way to do that.

# Answer
Rather than using trigger, use OnCollisionEnter2D.

https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionEnter2D.html

This fires whenever a collision is detected, and should do exactly what you need.
> 0 votes

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


title: understanding image rotation XNA C#

text:
# Question
Title: understanding image rotation XNA C#
I do not understand how the rotation of the image i have works. Is it something to do with the ThumbSticks on the Xbox Pad? or properties of a float? if someone could explain to me what is actually happening here i would be very greatful.

The image is of a Gun. I would like to add in shooting guided by the thumbsticks for enemies above the player, so understanding this is crucial.

The image and coding has its own class. So in Game1.cs only initialised, WMpos set to the character and update and draw methods referenced, so does not affect rotation.

This is all the relevant code for it here:

```
public Texture2D WMtxr;
public Vector2 WMorigin;
public float WMrotation;

public void UpdateMe(GameTime gameTime)
    {
        WMorigin = new Vector2(WMtxr.Width - 100, WMtxr.Height - 36);
        if (GamePad.GetState(PlayerIndex.One).ThumbSticks.Right.Y < -0.1)
        {
            WMrotation += 0.03f;
        }
        if (GamePad.GetState(PlayerIndex.One).ThumbSticks.Right.Y > 0.1)
        {
            WMrotation -= 0.03f;
        }
    }

public void DrawMe(SpriteBatch sb)
    {
        sb.Draw(WMtxr, WMpos, null, Color.White, WMrotation, WMorigin, 1f, SpriteEffects.None, 0);
    }

```

# Answer
The WMRotation variable you have here is being used to drive the rotation.

The rotation is changing in response to the thumbsticks because you have some logic in your update that is modifying the WMRotation variable in response to thumbstick input.

If you were to remove this logic and just add a small amount to WMRotation every update, then the image would rotate at a constant rate.

e.g.

```
// Note this might not compile exactly as written, I haven't written XNA code
// in years, and I don't have it installed right now.
// This is the basic gist of it though
public void UpdateMe(GameTime gameTime)
{
    const float deltaTimeSeconds = gameTime.ElapsedGameTime.Seconds;

    WMorigin = new Vector2(WMtxr.Width - 100, WMtxr.Height - 36);

    // Rotate approximately 45 degrees per second
    // (0.785398 is approx 45 degrees in radians)
    WMrotation += 0.785398 * deltaTimeSeconds;
}

```

But why does WMRotation change the rotation? The sprite is drawn rotated here because WMRotation is being passed into SpriteBatch.Draw here in your draw function

```
public void DrawMe(SpriteBatch sb)
{
    //                                         | WMrotation passed in here
    //                                         v
    sb.Draw(WMtxr, WMpos, null, Color.White, WMrotation, WMorigin, 1f, SpriteEffects.None, 0);
}

```

See the documentation for SpriteBatch.Draw here (there are several versions of the function you can call) https://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritebatch.draw.aspx

Note: There are other versions of the function you can call, depending on which properties of the sprite you care about. https://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritebatch.draw.aspx

A simplified high-level explanation of what SpriteBatch.Draw is doing here, is drawing a square on the screen made out of four vertices. The vertex positions are rotated internally using the rotation value that you pass in. This explanation of SpriteBatch.Draw is skipping over a lot of implementation details, but you don't really need to care too much about the details at this point.
> 1 votes

---
Tags: c#, xna-4.0, rotation, gamepad
---


# Question
Title: How does ads actually make you money when you upload a Game?
I am an independent game developer and I have made my own game. I want to upload it on the Play store and I understand that you need to pay $25. But there's something I don't understand in terms earning money. I have look on websites and some websites say for every 1000 views on an ad, you get $0.10 but on another, it says every view you get $0.10.

I don't understand the system of earning money when it comes to putting ads in your game. I understand its a bit of a stupid question but it will help when i upload my game for real.

# Answer
Ad networks will generally pay you for one or both of

* ad views, where you load the ad and display it to a user
* ad clicks, where you do the above and then a user *actually clicks on* the ad

The actual rates of payment will depend on the specific ad provider and in some cases the deal you negotiate with that provider, but that's the gist of it. Clicks generally pay more than views, since they're more useful to whoever paid to put the ad on their network. But they also happen less often.

Generally you will only get a payout when you are owed above a certain threshold of money; they won't cut you a check for $0.20, for example, but will rather pay you by the Xth of the month when your account balance exceeds $Y (or similar).

Typically you are prohibited from doing "shady" things like displaying the ads too quickly, or loading the ads but hiding them, or other sorts of deceptive practices.

Consult the specific terms of your agreement with whatever providers you are choosing or evaluating for details.
> 6 votes

---
Tags: advertisements
---


title: Blending for multiple lighting passes

text:
# Question
Title: Blending for multiple lighting passes
I am attempting to perform shadow mapping with deferred shading, using the following code:

```
for (auto light : m_ShadowDirs)
{
    //render shadow map
    shadowDirPass(m_ShadowBuffer, light);
    glEnable(GL_BLEND);
    glBlendFunc(GL_ONE, GL_ONE);
    // activate shader for non shadow casting lights
    m_ShadowDirLightShader.activate();
    m_FrameBuffer.LightingPass(m_ShadowDirLightShader);
    m_ShadowDirLightShader.setUniform(("WSCamPos"), m_ActiveCamera->getPosition());
    m_ShadowDirLightShader.setDirLight(("dirLight"), static_cast<DirLightData&>(light->getLightData()));
    m_ShadowDirLightShader.setUniform(("ShadowTransform"), m_ShadowDirMatrix);
    //bind depth map
    m_ShadowDirLightShader.bindTexture(("shadowMap"),5, m_ShadowBuffer.getDepthTexture());
    //render
    renderQuad();
    glDisable(GL_BLEND);
}

```

`shadowDirPass(m_ShadowBuffer, light);` Simply renders the geometry to the shadow map. `m_FrameBuffer.LightingPass(m_ShadowDirLightShader);` Just binds the Gbuffer textures.

I have two directional lights in the scene, one with red colour (1,0,0), and one with blue colour (0,0,1)

One would think that the scene would be coloured purple, but no. Every time I render (for each) light, the image in the target framebuffer is overwritten completely, instead of blended together. To illustrate this, see the following images:

Above is the scene with a single red light.

Above is the same scene, with a single blue light, but from a different direction. (See shadows).

When I enable both lights, the result is as if the first light was never used, though by stepping through the code, I can confirm that it is definitely going through a render cycle.

I'm pretty sure than I've messed up the blending somehow, but I could use some guidance.

# Answer
As it turned out, I was calling `glClear(COLOR_BUFFER_BIT)`, between lighting passes, within the FrameBuffer class. Once I removed that call, it worked fine.
> 1 votes

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


# Question
Title: OpenGL drawing multiple polygons with different colors with VBOs
I'm trying to change my program to use VBOs instead of immediate rendering for performance reason. The rendering consists of thousands of hexagons, all of the same size/shape. Each hexagon has a different color, so I'm trying to figure out how to change the color of the VBO for each rendered hex. Here's the code I'm using right now:

```
private static final int NUM_VERTICES = 6;
private static final int VERTEX_SIZE = 2;
private static final int COLOR_SIZE = 3;

private int vboVertexHandle;
private int vboColorHandle;

// This is called once on initialization
private void initVbo() {
    DoubleBuffer vertexBuffer = BufferUtils.createDoubleBuffer(VERTEX_SIZE * NUM_VERTICES);
    FloatBuffer colorBuffer = BufferUtils.createFloatBuffer(COLOR_SIZE * NUM_VERTICES);
    for (Point vertex : WorldHandler.TILE_VERTICES) {
        vertexBuffer.put(new double[]{vertex.x(), vertex.y()});
        colorBuffer.put(new float[]{1f, 0f, 0f});
    }
    vertexBuffer.flip();
    colorBuffer.flip();

    vboVertexHandle = GL15.glGenBuffers();
    GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboVertexHandle);
    GL15.glBufferData(GL15.GL_ARRAY_BUFFER, vertexBuffer, GL15.GL_STATIC_DRAW);
    GL30.glBindVertexArray(0);

    vboColorHandle = GL15.glGenBuffers();
    GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboColorHandle);
    GL15.glBufferData(GL15.GL_ARRAY_BUFFER, colorBuffer, GL15.GL_STATIC_DRAW);
    GL30.glBindVertexArray(0);
}

// This is called thousands of times per frame
private void drawHex(Color color) {
    // Set up the vertex buffer
    GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboVertexHandle);
    GL11.glVertexPointer(VERTEX_SIZE, GL11.GL_DOUBLE, 0, 0L);

    // Set up the color buffer
    GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboColorHandle);
    GL11.glColorPointer(COLOR_SIZE, GL11.GL_FLOAT, 0, 0L);

    GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
    GL11.glEnableClientState(GL11.GL_COLOR_ARRAY);

    GL11.glDrawArrays(GL11.GL_POLYGON, 0, NUM_VERTICES);

    GL11.glDisableClientState(GL11.GL_COLOR_ARRAY);
    GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
}

```

Note that I'm using OpenGL in Java through LWJGL. One solution I found online is to create a color VBO at initialization for each tile, then access each one when rendering that tile. That would probably solve my problem, but it may be more expensive than I'd like considering the lookup time when there are potentially millions of hexes that are off-screen.

Is there anything else I'm doing that is glaringly wrong? Even with those solution I'm only getting ~20 fps which is obviously far lower than I'd like.

# Answer
Have you considered creating a single vertex buffer that contains all of your hexagons? (Or if you have too many hexagons for a single buffer, chunking a large number of hexagons into shared buffers)

Generally as a rule, creating vertex buffers with a small number of vertices and making tons of draw calls per frame, are things that you're going to want to avoid from a performance perspective. It's better to batch things together.

A similar example would be a particle system. Ideally you'd probably have a single vertex buffer per particle system (or perhaps multiple particle systems per buffer if the number of particles is small). Creating lots of small buffers and drawing them separately is very inefficient.

As a general rule, GPUs are very good at drawing large numbers of triangles fast, so ideally you want to feed them large batches to work with (within reason, obviously). When you make a draw call, you ideally want to give it something substantial to feed on.

As for colouring, personally my starting point would be just to have per-vertex colours in the same buffer as the vertices, and only have a seperate buffer if I encountered problems with that approach
> 0 votes

---
Tags: opengl, vbo, lwjgl3
---


# Question
Title: Move an object to a point relative to the second camera
I have two cameras, one for the UI, one for the 3d objects.

The `UI camera` is just a simple, perspective camera. The `3d objects camera` is rotated by `(30,45,0)` so it displays things with an isometric view. (It's parent it rotated).

On the UI camera's canvas I have two 2D objects (images or something) with a `RectTransform`. These are invisible here, but they're marked as `X`.

What I need to do is to move the 3d object on the X/Y axis. To be super clear, I need to move it towards one of these two X objects (left or right).

For now, the camera is rotated, so it doesn't look like it's moving left/right/up/down, but it's moving to the corners (cause of the camera's rotation).

At the start it looks like:

Now I do a `_3dObject.transform.DOMove(leftXObject, 3f); // DOTween lib, doesn't matter`

And it moves to:

Because of the angle of the 3d camera.

What to do?!

# Answer
> 0 votes
So, I figured this out. Instead of doing a projection, I've created the 3d camera the exact same size as the UI one. I've rotated it, so it views objects from the isometric perspective and...

Created a `Canvas` on the rotated camera, added a `3d cube` (with rotation `(0,0,0)`) as a parent of an empty gameobject with a `RectTransform`. Now it seems like it was the only isometric object visible (cause of the camera rotation). Next, I created two gameobjects, one on the left of the 3d one, one on the right and anchored them so it moves to the correct location on all resolutions.

The point here is to create an exact copy of the UI canvas, but for the 3d environment. If anchored correctly, they'll synchronize. Remember that you can anchor a `RectTransform`, not a classic `Transform`, so your cubes/spheres etc have to be childs of panels/buttons/empty GO's.

:)

---
Tags: unity, 2d, 3d, camera, projection
---


# Question
Title: Is it possible to write a game with a HTML5+REST service architecture?
As a side project I'd like to program a board game similar to Twilight Struggle. For this pet project I'd like to satisfy several non functional requirements:

1. The core logic must be written in Haskell
2. If I succeed, I'd like to sell it in platforms like Steam, Google Play and Apple Store.

The Haskell requirement limits me a bit about the range of frameworks to use and the Haskell+SDL2 route doesn't seem very mature when talking about porting to mobile platforms (maybe I'm wrong but I haven't found any easy tutorials on the topic).

So I've thought about an HTML5 Canvas talking to the Haskell core either through REST calls or websockets. The HTML5 canvas will be contained in a Cordova application or similar when in the mobile. What do you think about this approach in terms of:

* feasibility
* robustness
* portability
* software engineering
* whatever other concern you might have

# Answer
> 2 votes
The problem with REST is that it is based on HTTP, which is not a protocol designed for low latencies or minimizing traffic. When you just want to send a few bytes, the HTTP header will generate huge overhead. Keeping a websocket connection open is far better when it comes to overhead (although not as good as "naked" sockets), but they still have the weakness that they are still based on TCP. When you are developing an action-paced game, you should be using UDP.

So if you were writing an action-game, then your approach might not give you satisfying results.

**But** your game is turn-based. (At least it looks like that. If it has some quick reaction mechanics, disregard this advise). In turn-based games, latency is usually not a problem. Players won't even notice when the move from the other player comes several hundred ms late. They will just assume the opponent needed a bit more time to think about their move. So in this case it is completely appropriate to use a REST-based webservice for communication between client and server.

Although I would still rather consider Websockets, because with REST the server can not notify the clients that something happened unless they ask. There are workarounds for that, but they are quite ugly (like delaying a response until something happens or bombarding the server with several update requests per second). With websockets, the server can push messages to clients whenever it needs to.

# Answer
> 1 votes
The first aspect I would consider is deployment. You need to check into how easy it is to deploy your end product to the platforms you list. As an example, Java is generally considered highly portable (write one, run anywhere!), but anecdotally, figuring out how to bundle up a game executable with a JRE for release on Steam is complex. Keep in mind any third party libraries you might need - if you're using anything that isn't stock, you may find that your base langague & libraries are portable, but get stuck because some game dev related library (sound, UI, graphics, AI, etc) isn't.

---
Tags: html5, mobile, sdl2, websocket
---


# Question
Title: How to set X and Z axis to 0 after transform.rotation in c#
Recently I start using C# instead of JAVA and I don't know how to set a value in a eulerangle only for one axis.

Maybe I don't need to do that, so better I explain what I'm doing:

I have a 3D object (player) that look at mouse pointer, but when the mouse pointer it's too close to the object, it's change his x and z axis, and I need to set it to 0 to keep standing the object.

In java I just write this after transform.rotation:

```
transform.eulerAngles.x = 0;
transform.eulerAngles.z = 0;

```

In C# I can't do that. Is there a simple way to do it? My code is:

```
Ray ray = Camera.main.GetComponent<Camera>().ScreenPointToRay (Input.mousePosition);
RaycastHit hit_A;
if (Physics.Raycast (ray, out hit_A, Mathf.Infinity, GroundMask)){
    Vector3 rotPoint = new Vector3 (hit_A.point.x - transform.position.x, transform.position.y, hit_A.point.z - transform.position.z);
    transform.rotation = Quaternion.LookRotation(rotPoint);
}

```

Maybe, as I said, there are an other way to fix this. I'm open to any solution. I searh it on google, but because at my english level I don't understand the results

Thanks you all.

# Answer
> 0 votes
`transform.eulerAngles` and `transform.rotation` are properties with pass-by-value semantics, not pass-by-reference. That means whenever you use them, a copy of that object is created and passed to the caller. When you make changes to that copy, they won't be applied to the object it came from until you explicitly write it back.

You can tell that because according to the documentation both `Vector3` and `Quaternion` are `struct`s, not `class`es. One subtle difference between Java and C# which can trip up someone who switches from one to the other is that in C#, classes are passed by reference just like in Java but C# struct's are passed by value.

Another thing you need to get used to as a Java programmer learning C# is that the syntax `object.identifier` can mean more than just directly accessing a public variable. That "public variable" can in fact be implemented as a Property, which means that getting and setting it invokes some hidden program logic.

So what happens in the line `transform.eulerAngles.x = 0;` is as follows:

1. The Quaternion which represents the rotation of the transform get converted to a `new Vector3` (Unity internally handles all rotations as quaternions. The Vector3 representation are just for your convenience)
2. That Vector3 is passed to the caller
3. The caller changes the x-member of the Vector3
4. The Vector3 gets discarded

So if you want to change the rotations, you need to copy them to a local variable, change that local variable, and then write that variable back:

```
Vector3 rotationAngles = Transform.eulerAngles;
rotationAngles.x = 0.0f;
rotationAngles.z = 0.0f;
transform.eulerAngles = rotationAngles;

```

By the way, if the Unity API would be in Java, the code might look something like this:

```
Vector3 rotationAngles = transform.createRotationEulerAngles();
rotationAngles.x = 0.0f;
rotationAngles.z = 0.0f;
transform.setRotation(rotationAngles);

```

# Answer
> 0 votes
Oh, thanks Philipp for your explanation. I did what you said but it didn't work. I don't know why, but using your answer I found a way to do it. It's the same, but write like this it works, and, like I said, I don't know why (i'm so newbie scripting).

```
Vector3 rotationAngles = new Vector3 (0, transform.eulerAngles.y, 0);
transform.eulerAngles = rotationAngles;

```

Now the player looks to the pointer. Thank you so much!!

---
Tags: c#, 3d
---


# Question
Title: How to draw a character behind and in front of a building? (isometric map)
how is it possible to draw the player behind and in front of some building in an isometric map : should I slice them, replace the number in the map (one number for a tile usually) by an array of number (each being a piece of a bigger tile), and somehow add a Z-order related to each small number (the pieces of building), something like this?

```
//replace :
var map = [
    [1,0,1],
    [0,1,1],
    [0,0,1],
    [0,0,1]
];

//by :
var map = [
    [["2-zOrder/1","3-zOrder/1"],0,1],
    [1,1,1],
    [1,0,1],
    [0,0,1]
];

```

# Answer
I used a straight forward approach for this.

My map (not the end result!) is set up us horizontal lines, where i go from top to bottom, blitting everything from left to right. That way I automatically place everything in the correct order. My tiles (not walking sprites, they have their origin at (0,y) !) all have their origin in the left-middle, or (0,y/2) assuming (0,0) is in the top left.

If you struggle with height, then just blit the ground layers first, then add the top layers, also from top to bottom.

Did this make sense?
> 1 votes

---
Tags: tilemap, isometric, draw-order
---


# Question
Title: How to blend the surface with HTML5 canvas?
I can simply blend the surface in GameMaker using these codes:

```
//colour with which to blend the surface.
draw_surface_ext(index, x, y, xscale, yscale, rot, colour, alpha);

```

or set "the Fade to a Color" property, it will looks like this:

For now I want to do the same thing with HTML5 canvas, but I don't know where to start, is there any canvas API that could do that?

# Answer
> 1 votes
This answer assumes you are using the 2d context for the canvas, not the 3d context (aka WebGL).

The 2d context for HTML5 canvas doesn't come with such neat image filtering algorithms out-of-the-box, so you have to implement them yourself.

Use context.getImageData to get an array of RGBA values, change them, and write them back with context.putImageData. Here is an example which recolors a canvas based on its greyscale values. I tried to keep this example as simple as possible. You might have to tweak this algorithm a bit to get the results which work best for you.

```
// "red", "green" and "blue" are expected to be in range 0.0 - 1.0
function recolorCanvas(ctx, red, green, blue) {

    var imgData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
    for (var i = 0; i < imgData.data.length; i += 4) {
        var brightness = (imgData.data[i] + imgData.data[i+1] + imgData.data[i+2]) / 3;
        imgData.data[i] = brightness * red;
        imgData.data[i+1] = brightness * green;
        imgData.data[i+2] = brightness * blue;
    }
    ctx.putImageData(imgData, 0, 0);

}

```

Keep in mind that this is a quite slow operation, because it's done entirely on the CPU. So if you can, you should avoid doing it every frame. You can do this on an invisible background canvas to keep the result in memory.

---

If you use the 3d context (webGL) you have the full power of pixel shaders at your disposal. That means you can program such algorithms to run on the graphics chip, which will be far faster. But that would look completely different code-wise. Shader programming is not my area of expertise. Maybe someone else would like to write a separate answer explaining how to write a simple recoloring pixel shader for unlit sprites.

---
Tags: html-canvas, game-maker, alpha-blending
---


# Question
Title: Why does my Java game loop randomly jump to 62 FPS and crash?
I've been working on a Java game, but I couldn't keep it from stuttering. I did some research, and found out that I was using a bad game loop. I've been working on a new game loop, which works a little better, but my framerate often jumps from 60 FPS to 62 FPS, and sometimes even crashes. This is the loop I'm using;

```
import java.applet.Applet;
import java.awt.Color;
import java.awt.Frame;

@SuppressWarnings("serial")
public class GameLoop extends Applet implements Runnable {

    final int FRAMERATE = 60;

    @Override
    public void init() {
        setSize(1280, 720);
        setBackground(Color.WHITE);
        setFocusable(true);
        Frame frame = (Frame) this.getParent().getParent();
        frame.setTitle("Game Loop");
    }

    @Override
    public void start() {
        Thread thread = new Thread(this);
        thread.start();
    }

    @Override
    public void stop() {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void run() {
        int framerate = 0;
        long counter = 0;

        long lastTime = System.nanoTime();
        long frameTime = 1000000000 / FRAMERATE;

        while (true) {
            long currentTime = System.nanoTime();
            long updateTime = currentTime - lastTime;
            lastTime = currentTime;

            counter += updateTime;
            framerate++;

            if (counter >= 1000000000) {
                System.out.println(framerate + " fps");
                counter = 0;
                framerate = 0;
            }

            try {
                Thread.sleep((frameTime * 2 - updateTime) / 1000000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

```

I've walked it through a couple of times, but I can't find out what's wrong. This is the console output I get;

```
60 fps
60 fps
60 fps
60 fps
62 fps
60 fps
62 fps
60 fps
60 fps
60 fps
...
Exception in thread "Thread-3" java.lang.IllegalArgumentException: timeout value is negative
    at java.lang.Thread.sleep(Native Method)
    at GameLoop.run(GameLoop.java:58)
    at java.lang.Thread.run(Unknown Source)

```

As far as I can understand, the loop crashes because `Thread.sleep((frameTime * 2 - updateTime) / 1000000);` has a negative input, but I don't know why it is negative.

I've added;

```
if (updateTime < 0)
    updateTime = 0;

```

After;

```
long currentTime = System.nanoTime();
long updateTime = currentTime - lastTime;
lastTime = currentTime;

```

To prevent getting a negative input, but the problem still occurs. Also, I've tried to implement the loop into my game, but it's even laggier than before. The player seems to be shaking back and forth while moving.

Could anyone tell me what I'm doing wrong and how I can fix this?

# Answer
> 1 votes
You get that error because `frameTime * 2 - updateTime` is negative. This happens whenever the previous update took longer than 1/30 seconds. This can happen for all kinds of reasons. Maybe your game mechanics were a bit more computationally complex in that tick than you expected. Or maybe the operating system decided to idle your game thread because it wanted to execute some other task. This just happens and your render loop needs to be able to deal with it.

Try this instead:

```
long sleepDuration = (frameTime - updateTime) / 1000000;
if (sleepDuration > 0) {
    Thread.sleep(sleepDuration);
}

```

An even better solution might be to decouple your render-framerate from your game update-framerate. This means that your game won't run slower when the user's machine isn't powerful enough to render at 60 fps. You can do that by keeping track of game-time and render-time separately. Pseudocode:

```
realTime = 0;
updatedTime = 0;
while (game is running) {
     realTime += time the last loop took;
     while (updatedTime < realTime) {
         updateGameMechanics();
         updateTime += time one tick is supposed to take
     }
     renderGraphics();
     sleep if necessary
}

```

A different method is to use a variable lockstep. Instead of performing multiple updates, pass the time since the last update to `updateGameMechanics` and keep that time into account for all game calculations. I personally prefer a fixed lockstep because that way you don't need to take the deltaTime into account for absolutely everything in your game mechanics, but this is more of a religious question.

---
Tags: java, game-loop
---


# Question
Title: Monogame/XNA Hardware Instancing problem
Here's a youtube video of my problem.

https://youtu.be/1zB4q9\_sNQI

Look at how the hideous cube kinda slides into the terrain and rotates weirdly with the world and from above its vanished into the terrain. None of the other models (not instanced) have that problem.

I'm having trouble getting hardware instancing to work as I need it to. For some reason my instanced models appear to vanish from above.

I thought I was doing something wrong with the instance transforms (which maybe I am). So i ripped out all but the scale and translation for those... same problem.

I thought it might be a depth problem so I just set the depth at 0 and STILL i have the same problem.

I made the simplest model I could with 1 bone and 1 texture. Same problem.

Maybe i'm missing something obvious.

Here's the vertex shader:

```
VertexShaderOutput VertexShaderCommon(VertexShaderInput input, float4x4 instanceTransform)
{
    VertexShaderOutput output;

    // Apply the world and camera matrices to compute the output position.
    float4 worldPosition = mul(input.Position, instanceTransform);
    float4 viewPosition = mul(worldPosition, View);
    output.Position = mul(viewPosition, Projection);

    // Compute lighting, using a simple Lambert model.
    float3 worldNormal = mul(input.Normal, instanceTransform);

    float diffuseAmount = max(-dot(worldNormal, LightDirection), 0);

    float3 lightingResult = saturate(diffuseAmount * DiffuseLight + AmbientLight);

    output.Color = float4(lightingResult, 1);

    // Copy across the input texture coordinate.
    output.TextureCoordinate = input.TextureCoordinate;

    return output;
}

```

Please help. I've been stuck on this for a day or two now annoyingly.

If you need an more code you might think relevant let me know.

Thanks in advance!

# Answer
It was something stupid in the end. In between drawing my non-instanced models and instanced models I had some effects and other stuff rendered, one of which changed the projection matrix. Therefore the Instanced geometry was being rendered with a different projection. One of the guys on GameDev spotted it.
> 0 votes

---
Tags: xna, monogame, instancing
---


# Question
Title: How do I keep Text[] values alive and reuse in the script
I'm building a bowling game in which I am trying to save the number of pins fallen on every turn to a UI text box, taken as an array (`public Text[] Count`). I'm able to get the first score in the text box, but unable to save it while switching to other scenes.

There are two scenes; one has the ball, pins and alley, and the other scene has the score card, which is displayed in additive mode. The UI text is a child of the canvas. I've used `DontDestroyOnLoad` for the canvas, but it doesn't work at all. I'm actually trying to reuse these values to display the score in the series.

Below is the code

```
public GameObject rootCanvas;
    public Text[] Count;
    public static int counter=0;
    public static int i;
    public static int co = 0;

    MovingBall ball = new MovingBall();

    public void Start()
    {
        ball.countText = GameObject.FindWithTag("Counttext").GetComponent<Text>();

        for (i=co;i<=29;i++)
        {
            if (counter < 1)
                {
                    Count[i].text = ball.countText.text;
                }
                else if (counter == 1)
                {
                    Count[i].text = ball.countText.text;
                    Count[i+1].text = (Convert.ToInt16(Count[i-1].text) + Convert.ToInt16(Count[i].text)).ToString();
                }

            counter++;

            co++;

            DontDestroyOnLoad(gameObject.transform);

            return;

        }

    }

    void Awake()
    {

        rootCanvas = GetComponent<GameObject>();

    }

```

# Answer
> -1 votes
You need to call DontDestroyOnLoad()

That will keep your "score" tracking object alive as Unity switches scenes.

Be aware that when you go to switch *back* you'll now have two of these objects! You'll need to either destroy the original (before switching scenes again) or detect and destroy the duplicate (by using a singleton structure).

---
Tags: unity, data
---


# Question
Title: How much matrices should I use for OpenGL transformation?
As I start to get some deeper(or at least a little bit better) understanding on how camera transformations works, I am curious about one thing: How much matrices should I use ?

I mean, until now I have been working with simple 2d ortho projection and I was using world positions (not in range -1.0 to 1.0 ) so I just created a matrix at the start of the program and that was it but when I wanted to get more to 3D(to get same effect of not using NDC) I noticed (in tutorials) that they use **a lot** of matrices(for example : they create matrix for every object ingame for translation and then send it to the GPU). This confuses me because I thought that I will use only 3 matrices (for every transform step). Can you explain me how is this done in professional games? Do I need to load new model matrix for every object(send it to vertex) ? Or change the whole MVP matrix in shader with every object being rendered? Is it still sufficient? Thanks

**Edit** About efficiency : Is it efficient to change the shader variable that often ? I mean, I want use my batch system from my old code and it looks like this now:

```
1. Bind texture + VAO
2. Render object.1+object.n via glDrawArrays/Elements/Instanced

```

But what about now it would be :

```
1. Bind texture + VAO
2. Load model matrix of object.1(via glUniformMat4fv) and render it, then load another model matrix for object2 and same for every object in batch

```

Isn´t it inefficient to change shader variable that much ?

# Answer
> 5 votes
Your object is transformed in multiple steps, and for each step, you usually use a matrix.

* You can rotate, scale and translate every model. This can be done with three separate matrices, but usually those three operations are combined into one big transformation/model matrix, which does everything together. Every model has it's own transformation matrix.
* The object is now in the correct "world space". The next step is the camera transformation. When you move your camera, the whole world is transformed, and this is a single matrix that gets applied to every object you want to render. ("*You position the object according to your camera*")
* The last matrix you need is a projection matrix. This takes your 3D model, and creates a "depth", i.e. projecting the 3 dimensions to a 2 dimensional screen. You can think of it as scaling all the x,y coordinates according to the z coordinate to appear nearer/further.

In general, you create your matrix, and send it to your shader, where all the matrices are applied to the vertices. The GPU is very good at parallelising the work, so you don't spend precious CPU cycles doing the matrix multiplications yourself.

For more information and an actual implementation Another tutorial about a simple ray picker, which describes the transformations in openGL.

# Answer
> 4 votes
In professional games every object in the world will have its own world matrix. This is usually stored in some structure that represents your entity in the world, or some component hanging off that entity (A class, struct, etc).

The world matrix isn't just used for graphics, a lot of gameplay logic will rely on it too. This matrix will ultimately get passed through to the rendering API in some form.

I'm very out of touch on the graphics side, but I think typically, matrices for rendering get passed through as parameters to the vertex shader, and the matrices that get passed through will typically depend on the needs of the vertex shader. If the logic in the vertex shader needs access to the world, view and projection matrices separately, then they'll be passed in separately. If the logic in the shader really only needs the combined Model * View * Projection matrix, then it might get passed in that way to cut down on computation in the shader and the number of constants that need to be set.

Some graphics techniques may even pass in vertices in world-space or camera space, if that makes sense. That would be more unusual though, for one-shot effects rather than objects that want to share the same vertex buffer. Dynamic effects like particle systems are a good example here.

Typically in a professional quality engine, the way the data is passed through to the graphics API will often vary based on object/material type. Terrain for example, or other types of static world geometry will be very different to dynamic entities, skinned characters, etc. Unlit geometry might require less information than geometry that's affected by lighting, etc.

---
Tags: opengl, 3d, matrix
---


title: Cubemap texturing issue D3D11 (C++)

text:
# Question
Title: Cubemap texturing issue D3D11 (C++)
I have a texture problem with the cubemap I'm rendering and can't seem to figure it out. I've generated a cube map with direct x's texture tools and then read it using

```
D3DX11CreateShaderResourceViewFromFile(device, L"cubemap.dds", 0, 0, &fullcubemap, 0);

```

The cubemap texture is not high quality at all and it looks really stretched/distorted. I can definitely tell that the images used for the cubemap match correctly, but it's not great at all at the moment

I'm not sure why this is happening. Is it because my textures are too large/small or is it something else? If it's due to the size of the textures, what is a recommended texture size? I am using a sphere for the cubemap not a cube.

Edit:

Shader:

```
cbuffer SkyboxConstantBuffer {
    float4x4 world;
    float4x4 view;
    float4x4 projection;
};

TextureCube gCubeMap;

SamplerState samTriLinearSam {
    Filter = MIN_MAG_MIP_LINEAR;
    AddressU = Wrap;
    AddressV = Wrap;
};

struct VertexIn {
    float4 position : POSITION;
};

struct VertexOut {
    float4 position : SV_POSITION;
    float4 spherePosition : POSITION;
};

VertexOut VS(VertexIn vin) {
    VertexOut vout = (VertexOut)0;

    vin.position.w = 1.0f;

    vout.position = mul(vin.position, world);
    vout.position = mul(vout.position, view);
    vout.position = mul(vout.position, projection);

    vout.spherePosition = vin.position;

    return vout;
}

float4 PS(VertexOut pin) : SV_Target {
    return gCubeMap.Sample(samTriLinearSam, pin.spherePosition);//float4(1.0, 0.5, 0.5, 1.0);
}

RasterizerState NoCull {
    CullMode = None;
};

DepthStencilState LessEqualDSS {
    DepthFunc = LESS_EQUAL;
};

technique11 SkyTech {
    pass p0 {
        SetVertexShader(CompileShader(vs_4_0, VS()));
        SetGeometryShader(NULL);
        SetPixelShader(CompileShader(ps_4_0, PS()));

        SetRasterizerState(NoCull);
        SetDepthStencilState(LessEqualDSS, 0);
    }
}

```

Draw:

```
immediateContext->OMSetRenderTargets(1, &renderTarget, nullptr);

XMMATRIX sworld, sview, sprojection;
SkyboxConstantBuffer scb;
sview = XMLoadFloat4x4(&_view);
sprojection = XMLoadFloat4x4(&_projection);
sworld = XMLoadFloat4x4(&_world);

scb.world = sworld;
scb.view = sview;
scb.projection = sprojection;

immediateContext->IASetIndexBuffer(cubeMapSphere->getIndexBuffer(), DXGI_FORMAT_R32_UINT, 0);
ID3D11Buffer*  vertexBuffer = cubeMapSphere->getVertexBuffer();
//ID3DX11EffectShaderResourceVariable * cMap;
////cMap = skyboxShader->GetVariableByName("gCubeMap")->AsShaderResource();
immediateContext->PSSetShaderResources(0, 1, &fullcubemap);//textures
//cMap->SetResource(fullcubemap);
immediateContext->IASetVertexBuffers(0, 1, &vertexBuffer, &stride, &offset);
immediateContext->VSSetShader(skyboxVertexShader, nullptr, 0);
immediateContext->VSSetConstantBuffers(0, 1, &skyboxConstantBuffer);
immediateContext->PSSetConstantBuffers(0, 1, &skyboxConstantBuffer);
immediateContext->PSSetShader(skyboxPixelShader, nullptr, 0);

immediateContext->UpdateSubresource(skyboxConstantBuffer, 0, nullptr, &scb, 0, 0);
immediateContext->DrawIndexed(cubeMapSphere->getIndexBufferSize(), 0, 0);

```

Initially I was planning to use this snippet to update the TextureCube variable in the shader

```
ID3DX11EffectShaderResourceVariable * cMap;
cMap = skyboxShader->GetVariableByName("gCubeMap")->AsShaderResource();
cMap->SetResource(fullcubemap);

```

But it seems that has no effect, and in fact, without the following line, the sphere I'm using for the cubemap textures with a texture used with another object in the scene, so perhaps there's something going on here? I'm not sure what though.

```
immediateContext->PSSetShaderResources(0, 1, &fullcubemap);//textures

```

Edit: Probably not the above, realised that if this wasn't updated, the old texture would be applied as it's never wiped after each draw.

Edit: Tried the cubemap with both a sphere and a cube, still the same texture issue.

Edit: Tried loading the shader resource view differently

```
D3DX11_IMAGE_LOAD_INFO loadSMInfo;
loadSMInfo.MiscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE;

ID3D11Texture2D* SMTexture = 0;
hr = D3DX11CreateTextureFromFile(device, L"cubemap.dds",
    &loadSMInfo, 0, (ID3D11Resource**)&SMTexture, 0);

D3D11_TEXTURE2D_DESC SMTextureDesc;
SMTexture->GetDesc(&SMTextureDesc);

D3D11_SHADER_RESOURCE_VIEW_DESC SMViewDesc;
SMViewDesc.Format = SMTextureDesc.Format;
SMViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
SMViewDesc.TextureCube.MipLevels = SMTextureDesc.MipLevels;
SMViewDesc.TextureCube.MostDetailedMip = 0;

hr = device->CreateShaderResourceView(SMTexture, &SMViewDesc, &fullcubemap);

```

Still produces the same output, any ideas?

Edit: Tried increasing the zfar distance and the texture remains the exact same no matter what value I put.

Example with second texture with increased view distance.

This texture is used on another object in my scene and comes out fine.

# Answer
It turned out to be that I needed to use XMMatrixTranspose
> 0 votes

---
Tags: c++, textures, directx
---


# Question
Title: How do I calculate normals correctly for dynamic terrain (DX11, C++)?
I am currently looking for some guidance on how to correctly calculate my normals on the CPU for my terrain as the results I'm getting seem to be incorrect. Eventually I will attempting to calculate them on the GPU as I'm aiming for terrain deformation in real-time.

These are the results

The different colours on the image represent different normal values.

Here is the code I'm using to generate them.

```
for (int i = 0; i < width; i++) {

    for (int j = 0; j < height; j++) {
        int index1 = (j * width) + i;
        int index2 = (j * width) + (i + 1);
        int index3 = ((j + 1) * width) + i;

        int index4 = ((j + 1) * width + i);
        int index5 = ((j * width + (i + 1)));
        int index6 = ((j + 1) * width + (i + 1));

        //vertices of triangle
        Vertex vertex1 = vertices->at(index1);
        Vertex vertex2 = vertices->at(index2);
        Vertex vertex3 = vertices->at(index3);

        Vertex vertex4 = vertices->at(index4);
        Vertex vertex5 = vertices->at(index5);
        Vertex vertex6 = vertices->at(index6);

        //each vertex as XMVECTOR
        XMVECTOR point1 = XMVectorSet(vertex1.Pos.x, vertex1.Pos.y, vertex1.Pos.z, 0.0f);
        XMVECTOR point2 = XMVectorSet(vertex2.Pos.x, vertex2.Pos.y, vertex2.Pos.z, 0.0f);
        XMVECTOR point3 = XMVectorSet(vertex3.Pos.x, vertex3.Pos.y, vertex3.Pos.z, 0.0f);

        XMVECTOR point4 = XMVectorSet(vertex4.Pos.x, vertex4.Pos.y, vertex4.Pos.z, 0.0f);
        XMVECTOR point5 = XMVectorSet(vertex5.Pos.x, vertex5.Pos.y, vertex5.Pos.z, 0.0f);
        XMVECTOR point6 = XMVectorSet(vertex6.Pos.x, vertex6.Pos.y, vertex6.Pos.z, 0.0f);

        //lines to compute the cross product
        XMVECTOR line1 = XMVectorSubtract(point2, point1);
        XMVECTOR line2 = XMVectorSubtract(point3, point1);

        XMVECTOR line3 = XMVectorSubtract(point5, point4);
        XMVECTOR line4 = XMVectorSubtract(point6, point4);

        //cross product to get our unnormalized normal
        XMVECTOR cross = XMVector3Cross(line1, line2);

        XMVECTOR cross2 = XMVector3Cross(line3, line4);

        //normalize to get our normal value
        cross = XMVector3Normalize(cross);
        cross2 = XMVector3Normalize(cross2);

        vertices->at(index1).Normal = Operations::vectorToXMFLOAT3(cross);
        vertices->at(index2).Normal = Operations::vectorToXMFLOAT3(cross);
        vertices->at(index3).Normal = Operations::vectorToXMFLOAT3(cross);

        vertices->at(index4).Normal = Operations::vectorToXMFLOAT3(cross2);
        vertices->at(index5).Normal = Operations::vectorToXMFLOAT3(cross2);
        vertices->at(index6).Normal = Operations::vectorToXMFLOAT3(cross2);
    }

}

```

**Edit**: I have made some changes to the code to account for the second triangle in the triangle pair but still produces similar results. The green (grass) represents a normal value of 0. The pink represents a normal value of 1. The red represents a normal value of -1

Why is the majority of the mesh 0, and where the normals are calculated, they are incorrect?

**Edit 2**

I have removed the use of the indices array in this loop and now the whole plane is processed, but results are still incorrect.

**Edit 3**

I did not realise I was referencing the indices array in more than one place. When I corrected this, I am now seeing better results. Although there is a slight problem of the normal that is being calculated is -1 instead of the expected +1

**Edit 4**:

Normals are calculated per vertex and don't take other touching faces into account, that is the next step. I'm guessing some parts of the texturing/terrain look a little weird due to this.

---

At the moment my terrain is just a flat plane, so all of the normals should be the same, right? However the values seem to be different when rendering/printing out.

There are some values that are 0, some are -1 and the rest are +1. Does anyone know where I'm going wrong?

# Answer
> 2 votes
I see several bugs, if I understand the structure of your mesh correctly. I think it's a grid of triangles, arranged so pairs of triangles form squares.

First, when calculating `index1`, `index2`, and `index3`, you should multiply the `j` factor with `width` and not `height`.

Next, for a smooth mesh (later, when you are deforming it) you'll need to give each vertex the average of all the normals of faces touching that vertex. Right now, only last triangle that you visit which touches a vertex is going to have any influence on its normal.

Last, you're only visiting the "lower left" triangle in each pair. You need to visit all of them to get correct normals. Also, this means that you'll never touch the last vertex (at index `width * height - 1`) in this loop. The greatest index you'll reach (after fixing the first bug) is `width * height - 2`.

---
Tags: directx11, terrain, normals
---


# Question
Title: Player appears in front of objects even if it's in the background
I have a player in `Z=0` and a fence object that I want it to be in from of the player so I set it to `Z=1`, it's a 2D game but in the 3D view I can see that the fence is actually in front of the player but in the 2D view the player is displayed in front.

Here are a couple of screenshots.

3D view, fence in front of player:

2D view, player in front of fence:

Any idea how to fix this?

# Answer
> 2 votes
In 2D, a sprites Z coordinates mean almost nothing. They have what's called a layer and an order in said layer, see:

You need to set the fence's `Order in Layer` parameter value higher than the player. If the player is still rendered above the fence, their layers and render queues might be the problem.

---
Tags: unity
---


# Question
Title: Libgdx Application terminate in an unusual way
I am developing simple multiplayer game using libgdx and box2D. And Im getting error below.

```
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
AL lib: (EE) alc_cleanup: 1 device not closed
Assertion failed!

Program: C:\Program Files\Java\jre7\bin\javaw.exe
File: /var/lib/jenkins/workspace/libgdx/gdx/jni/Box2D/Dynamics/b2Body.cpp, Line 419

Expression: m_world->IsLocked() == false

```

I checked similar issue in SO which suggest that I may cause if we destroy Body before our World Stepping but its not case here. While trying to debug this error I found that following code is causing error:

```
public void updateScene(PlayerStatus playerStatus){
    Vector2 pos = playerStatus.getPosition();
    Player coopPlayer = coopPlayers.get(playerStatus.getId());
    if (coopPlayer !=null){
          coopPlayer.b2body.setTransform(pos, 0);     //Main cause of error
          coopPlayer.setPosition(pos.x - coopPlayer.getWidth() / 2, pos.y - coopPlayer.getHeight() / 2);
    }
}

```

Any help is greatly appreciated.

# Answer
According to the code of Box2D, the `setTransform` method shouldn't be called when the world is locked. Box2D hasn't finished it simulation stage and so don't accept new changes.

You can fix this issue by calling this method only when the world isn't locked :

```
 if(coopPlayer != null && !yourWorld.isLocked()) {
        coopPlayer.b2body.setTransform(pos, 0);
 }

```
> 1 votes

# Answer
I agree with dwursteisen's analysis of the problem and that you'll need to call `setTransform` while the world **is not** locked. You'll seemingly need to solve the problem differently however since you still need the `setTransform` to get called. I say seemingly, because you'd written in the comments that "it doesn't solve the issue" presumably because you're not getting the transform to happen all though you're not getting the error anymore either. If you are getting the same error, then you'll need to find where else in your code (in addition to `updateScene`) that you could be calling `setTransform`.

Assuming that you're no longer getting the error though...

Instead of simply checking in `updateScene` whether the world is unlocked and only then calling the `setTransform` method, you'll need to add an else clause for when `coopPlayer != null` and the world is locked. In this else clause, you'll need to effectively enqueue the body and new position information such that it can be later dequeued in your main loop, after the world step has been performed, and call `setTransform` with those queued up positions for the bodies then.

The `updateScene` code then might look like:

```
public void updateScene(PlayerStatus playerStatus){
    Vector2 pos = playerStatus.getPosition();
    Player coopPlayer = coopPlayers.get(playerStatus.getId());
    if (coopPlayer !=null){
        if (yourWorld.isLocked()) {
            yourWorldState.enqueueTransform(playerStatus.getId(), pos);
        }
        else {
            coopPlayer.b2body.setTransform(pos, 0);     //Main cause of error
            coopPlayer.setPosition(pos.x - coopPlayer.getWidth() / 2, pos.y - coopPlayer.getHeight() / 2);
        }
    }
}

```

And your main loop code would look like:

```
while (gameShouldRun) {
    world.step(...);
    while (!transformQueue.empty()) {
        Data data = transformQueue.dequeue();
        Player coopPlayer = coopPlayers.get(data.getId());
        Vector2 pos = data.getPos();
        coopPlayer.b2body.setTransform(pos, 0);
        coopPlayer.setPosition(pos.x - coopPlayer.getWidth() / 2, pos.y - coopPlayer.getHeight() / 2);
    }
}

```

Of course if you know things like that only one transform will need to be done for only one body, the whole queuing concept simplifies down. Perhaps to something like just a variable to save the single new position (instead of more complex structures like an actual multi-element queue).

Hope this solves the issue entirely now.
> 0 votes

---
Tags: libgdx, box2d, multiplayer
---


# Question
Title: Spawning random objects within certain boundaries in Unity
I know questions like these are asked a lot however non of the previously answered ones have helped me. I'm creating a game that spawns a specified number of different objects randomly on a plane. I have each object arranged according to priority that if there isn't enough room for a lower priority object, it just spawns any amount spawn able for that object.

The way I implemented this is that before each object of type is spawned, the maximum amount of the object that can be spawned on the plane is calculated and it keeps within that limit. Then the next calculates the number of objects spawn able after the first object of type has been spawned and keeps within that limit and so on and so on.

However when I the numbers for each objects, if the numbers go above a certain amount the editor stops responding. I've tried multiple ways of changing this but I can't seem to figure it out. Here's my code for the spawner:

```
 void Spawn( GameObject obj, float height, int num, int max){

    currentObjectsOnBoard = 0;//number of specified objects spawned
    for (int i = 0; true; i++) {
        float x = Random.Range (startX, (startX + boardW));
        float y = height;
        float z = Random.Range (startZ, (startZ - boardH));
        Vector3 temp = new Vector3 (x, y, z);

        Collider[] hitColliders = Physics.OverlapSphere(temp, spacer);
        int a = 0;
        bool free = true;

        while (a < hitColliders.Length)
        {
            if ((hitColliders [a].CompareTag ("Collectable")) || (hitColliders [a].CompareTag ("Obstacle")) || (hitColliders [a].CompareTag ("Hole")) || (hitColliders [a].CompareTag ("Player"))  || (hitColliders [a].CompareTag ("Coin")))  {
                free=false;
                //check if spot is occupied by any of the above, within a radius specified by spacer
            }
            a++;
        }

        if (free) {
            Instantiate (obj, temp, Quaternion.identity);
            currentObjectsOnBoard++;
        } else {
            continue;
        }

        if ((currentObjectsOnBoard == num) || (currentObjectsOnBoard== max-1)) {
            break;
            //if object reaches number specified or if no more can be spawned.
        }

    }

```

And here's is how I implemented it:

```
    boardArea = Mathf.Abs (boardW * boardH);
    collectArea = (spacer+1) * (Mathf.PI * collectRad * collectRad);
    playerArea = (spacer+1) * (Mathf.PI * playerRad * playerRad);

    holeArea = (spacer+1) * (Mathf.PI * holeRad * holeRad);
    coinArea = (spacer+1) * (Mathf.PI * coinRad * coinRad);
    obstacleArea = (spacer+1) * (obstacles.transform.localScale.x * obstacles.transform.localScale.z);

    maxCollectablesOnBoard = (int) (((boardArea- (playerArea)) / (collectArea)));
    Spawn (collectable, collectAndCoinHeight, collectNum, maxCollectablesOnBoard);

    tempcollect = currentObjectsOnBoard;//number of collectables spawned if different from numer requested
    maxHolesOnBoard = (int) (((boardArea  - (playerArea) - (tempcollect * collectArea)) / (holeArea)));
    Spawn (hole, holeHeight, holeNum, maxHolesOnBoard);

    temphole = currentObjectsOnBoard;//number of holes spawned if different from numer requested
    maxCoinsOnBoard = (int) (((boardArea  - (playerArea) - (temphole * holeArea) - (tempcollect * collectArea)) / (coinArea)));
    Spawn (coin, collectAndCoinHeight, coinNum, maxCoinsOnBoard);

    tempcoin = currentObjectsOnBoard;//number of coins spawned if different from numer requested
    maxObstaclesOnBoard = (int) (((boardArea  - (playerArea) - (temphole * holeArea) - (tempcollect * collectArea)  - (tempcoin * coinArea)) / (obstacleArea)));
    Spawn (obstacles, obstacleHeight, obstacleNum, maxObstaclesOnBoard);

    tempob = currentObjectsOnBoard;//number of obstacles spawned if different from numer requested
    maxObjectsOnBoard = (int)(((boardArea) / ((temphole * holeArea) + (tempcollect * collectArea)  + (tempcoin * coinArea) + (tempob * obstacleArea) + playerArea)));

```

I know the code is wrong but I'd really appreciate some help with this. To recap, I'm trying to spawn 4 different types of objects ordered in priority of

collectables

holes

coins

obstacles

An I'm trying to make it such that if one of lower priority has no more room to spawn the number requested, it just spawns the maximum it can spawn. Thank you!

# Answer
```
for (int i = 0; true; i++)

```

This is dangerous, because you risk looping in that piece of code forever, and thus freezing the game/editor.

I am not sure how to change your code to make it fit within your game, but I would definitely put a limit to it like this:

```
for (int i = 0; i < 100; i++)

```
> 1 votes

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


# Question
Title: Is this possible to edit the Unity app through inspector while running on Android device?
When on PC, I can run the app and edit things temporarily through the `inspector`.

I know that I can attach the `Android ADB` and the profiler, but is there any option to edit objects through the inspector while running on the emulator/physical device?

# Answer
No.

And it is doubtful it ever will be supported. You need to rebuild to put it on the physical device, and you cannot realistically rebuild after every time you change a variable.

Try using Unity Remote, an app for running directly on your device without building. They might support it.
> 1 votes

---
Tags: unity, android, debugging
---