# Question
Title: Bullet Physics / OpenGL Meshes Not Colliding
This is for a school project, and I'm having a bit of trouble with Bullet acting strangely.

I have an OpenGL project with Bullet Physics library working with Assimp model loaders and Magick++ texture loading. I load the triangulated faces of a walled table into the btTriangle mesh and load this into a btBvhTriangleMeshShape in the main program. This works fine when a sphere object is loaded into the program and constrained to the x-z axes, but when I allow the ball to roll around in all three dimensions, the ball simply goes through the mesh or pops underneath it. I've tried raising and lowering the ball and base table meshes, but at best, I get a weird orbiting movement around the walls that I can't quite figure out. My group tried asking the teaching assistants, but this is beyond their experience.

I make the models in Blender and checked that the faces are triangulated and normals are pointing outward, but nothing seems to help. As another attempt, I pulled out the floor of the model and just use the walls as btBvhTriangleMeshShapes with the floor acting as a btStaticPlaneShape. Both are set with collision flags as static objects and have their collision flags facing each other (ball to floor and floor to ball, etc), but nothing is helping. I would deeply appreciate any insight into this or if anyone has a great tutorial for this situation to help me understand it better.

```
///Initialize all of our resources(shaders, geometry)
bool init = initialize(FileName);

btBvhTriangleMeshShape *table = new btBvhTriangleMeshShape(tableMesh, false);

//new btBvhTriangleMeshShape(tableMesh, true);
//
btScalar sphereDim(0.25);
btScalar baseDim(5.0);
btVector3 baseNorm(0, -1, 0);
btCollisionShape *ball = new btSphereShape(sphereDim);
btCollisionShape *base = new btStaticPlaneShape(baseNorm, baseDim);

//new

//Bullet
//Tells Bullet how to check for collisions between objects
btBroadphaseInterface *broadphase = new btDbvtBroadphase;
//collision algorithm: used to register a callback that filters overlapping broadphase proxies
btDefaultCollisionConfiguration *collisionConfiguration = new btDefaultCollisionConfiguration();
//Sends events to objects
btCollisionDispatcher *dispatcher = new btCollisionDispatcher(collisionConfiguration);
//causes objects to interact properly
btSequentialImpulseConstraintSolver *solver = new btSequentialImpulseConstraintSolver;
//Create a Physical world
dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
//sets gravity
dynamicsWorld->setGravity(btVector3(0, -9.81, 0));
dynamicsWorld->setInternalTickCallback(myTickCallback);

// Table
btScalar groundMass(0);
btVector3 groundInertia(0,0,0);
btDefaultMotionState  *tableMotion = NULL;
tableMotion = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1), btVector3(0, 0, 0)));
table->calculateLocalInertia(groundMass, groundInertia);
btRigidBody::btRigidBodyConstructionInfo tableRigidBodyCI(groundMass, tableMotion, table, groundInertia);
tableRigidBody = new btRigidBody(tableRigidBodyCI);
tableRigidBody->setFriction(1.0);
tableRigidBody->setRestitution(0.975);
tableRigidBody->setCollisionFlags(tableRigidBody->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
tableRigidBody->setActivationState(DISABLE_DEACTIVATION);
dynamicsWorld-> addRigidBody(tableRigidBody, COL_TABLE, tableCollidesWith);

// Base
btScalar baseMass(0);
btVector3 baseInertia(0,0,0);
btDefaultMotionState  *baseMotion = NULL;
baseMotion = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1), btVector3(0, 0, 0)));
base->calculateLocalInertia(baseMass, baseInertia);
btRigidBody::btRigidBodyConstructionInfo baseRigidBodyCI(baseMass, baseMotion, base, baseInertia);
baseRigidBody = new btRigidBody(baseRigidBodyCI);
baseRigidBody->setFriction(1.0);
baseRigidBody->setRestitution(0.975);
baseRigidBody->setCollisionFlags(baseRigidBody->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
baseRigidBody->setActivationState(DISABLE_DEACTIVATION);
dynamicsWorld-> addRigidBody(baseRigidBody, COL_BASE, baseCollidesWith);

// Ball
btScalar sphereMass(0.5);
btVector3 sphereInertia(0.0, 0.0, 0.0);
btDefaultMotionState *ballMotion = NULL;
ballMotion = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1), btVector3(0, 1, 0)));
ball->calculateLocalInertia(sphereMass, sphereInertia);
btRigidBody::btRigidBodyConstructionInfo ballRigidBodyCI(sphereMass, ballMotion, ball, sphereInertia);
ballRigidBody = new btRigidBody(ballRigidBodyCI);
ballRigidBody->setActivationState(DISABLE_DEACTIVATION);
ballRigidBody->setFriction(1.0);
ballRigidBody->setRestitution(0.975);
ballRigidBody->setLinearFactor(btVector3(1, 1, 1));
ballRigidBody->setAngularFactor(btVector3(1, 1, 1));
dynamicsWorld->addRigidBody(ballRigidBody, COL_BALL, ballCollidesWith);

```

# Answer
You should make your bodies static instead of kinematic. Basically remove lines like this:

```
tableRigidBody->setCollisionFlags(
            tableRigidBody->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);

```

For kinematic bodies you need to supply the transforms via a btMotionState.
> 2 votes

---
Tags: opengl, c++, physics, bullet-physics
---


# Question
Title: How can I turn off the sound from another scene?
I attached music file to my first scene and thanks to following javascipt code, sound continues without stopping in other scenes.

```
public static var object : SingletonMusic = null;

function Awake()
{

    if( object == null )
    {
        object = this;
        DontDestroyOnLoad(this);
    }
    else if( this != object )
    {
        Destroy( gameObject );
    }
}

```

My problem is that I want to turn off the sound from the button in the another scene (setting scene) so that I added a new button to my setting scene and attached the following javascript code to the button that I have created.

Javascript code:

```
var objects: AudioSource = SingletonMusic.object.GetComponent(AudioSource);
if( objects.isPlaying )
objects.Pause();
else
objects.Play();

```

However, it gives following errors:

If I start the game from Setting scene; I get this error:

If I start the game from first scene and then, go to Setting scene; I get this error:

# Answer
> 1 votes
It says that you are calling a gmeobject in a field initializator or constructor. Instead try adding initialization to Start or Awake method.

This is probably what you do:

```
public go = gameObject;

```

Try doing this instead:

```
public go;

void Start()
{
    go = gameObject;
}

```

---
Tags: unity, javascript, sound, audio
---


# Question
Title: What is causing my default libraries to conflict with OpenGL extensions?
So I'm currently following the tutorial for creating OpenGL programs on learnopengl.com,so I'm using GLFW, GLEW and the base library for OpenGL. However, when I go to build my code, I get a warning about how some of my default libraries "conflict with use of other libs; use /NODEFAULTLIB:library". So I went and disabled the appropriate defaults, and I get even more errors.

I'm trying to figure out, what other reason would there be that this error might be caused? From what I can tell, GLFW and GLEW should not experience this warning in the first place. I wouldn't have been too upset, since it compiles properly, however, when I add a third library in (one called soil, for adding images as textures), I get errors straight off the bat.

The libraries I used were from the official websites:

www.glfw.org/download.html (windows 32 bit binaries)

sourceforge.net/projects/glew/files/glew/1.13.0/ (the win32 .zip file)

I've seen people asking about this particular warning before, but the methods given to fixing it don't seem to apply to me :L

Edit: Here's the list of errors

# Answer
Okay guys, I messed up. I went back and checked to find that I had made a console application rather than an empty project, as was specified by the tutorial. Mostly likely the reason for it, or at least the first of many problems. Thanks for the help.
> 1 votes

---
Tags: opengl, glfw, glew
---


# Question
Title: Is there ever a time when creating a level/world editor with your game is a bad idea?
I have created a few smaller games on my own in the past. My approach has always been to create a completed editor where it has all the functionality needed to save a level file and load it into the game.

This has always made most sense to me but I keep hearing from people that a game is never fully done in the editor. I have never worked in a game development team and so I don't have first hand experience, but not adding everything needed to make the game to the editor just seams wrong.

Am I missing something? Is there ever a reason not to add a tool to the editor?

# Answer
The game editor is for editing the properties of your game-specific entities, together with their specific actions, ai, triggers, etc. But you also need a scripting language binding such as Lua, Python, Unreal script, your own scripting language.. to pass level-design specifics easier. You'll find out that for a strategy game, it's impossible to do complicated things such as assigning different strategies to the same units based on complicated triggers and analyzers and not hardcoding a bunch of that business.

Scripts are good because they are easier for people to work with and aid in customizing the "story" for a certain map/level. Game designers don't need to know heavy programming to see how things evolve if they want to change the logic. This might be just one of the things you can do in a scripting language without hardcoding a plethora of options in the editor alone.
> 4 votes

# Answer
Time spent making your editor is taken away from the team programming the game.

So you really want to make the simplest editor you can.

Ideally, in order of preference:

* Use an existing editor application unmodified (maybe not a game-specific one) and write conversion / import tools to build the level based on its output
* Use an existing game editor (perhaps from a library or toolkit you use), adapt it to your needs
* Build the simplest editor you can, ideally reusing as much of the game-code as you can

Of course you need good tools so your content team can make the content efficiently. But consider what the best tool is?

Suppose you have a seemingly simple feature such as "undo" - developing this feature is extremely nontrivial, and it would be better to use an existing tool (which already has such a feature) than to try to implement it.

I cannot stress enough, how much better the first two approaches are!
> 3 votes

# Answer
There is quite a bit of scope to this question.

Games made for profit

Triple A titles are often/usually produced under a time constraint set by financial backers that don't care about the quality of the game, but the profits it generates. Thus the editor is predominately a short cut and will do "80%" of the work, the other "20%" is things specific to the game being made, fine tuning, and rare/one-off objects/events (thus not worth investing time to create a tool and then the object, event, etc.). It can also be damaging if the game feels too similar to the the previous one or another title already out there. Basically is it financially worth the time to develop the tool especially if you are going to tweak what it produces anyway.

Games made for other reasons

Games are works of art, and so is the way in which you make games thus there is no right or wrong way. It all comes down to what you enjoy making. If you enjoy tool development then make all the tools you like. If you enjoy turning out lots of games then making generic tools can expedite this, but can end up making them feel too similar thus the time spent out of the editor to tweak them to their own style. You might also want to test out an concept, but not want to invest a lot of time developing an editor.

In game level editor's Editor's in games can cause issues; being buggy or make too much of a demand on the system (especially for hand held and mobile platforms) and thus are best avoided as not to tarnish the polished product.

**This answer is currently incomplete**
> 0 votes

# Answer
My answer is "it depends". My current phone game project at home would totally not benefit from a level editor. This is because my levels are a set of very simple parameters that are used to procedurally generate the grids. That's on one end.

On the other end, there are high-level AAA games which are so large and complex, you really, really need quality editor. One reason Unity and Unreal Engine are useful is because the include an editor.

So where you are on this scale determines how much time should go into your editor. If your game is simple enough so that you'd spend 5 times as long making the editor as the game without the editor, then it's not worth the trouble. But if making the editor was say 50% of your dev time, but your total dev time would triple if you didn't make the editor, then it's definitely worth making.
> 0 votes

---
Tags: game-industry, level-design
---


title: Unity3D Pathfinder with Crossings

text:
# Question
Title: Unity3D Pathfinder with Crossings
I'm trying to bring traffic on my street system. The main problem for me are the different lanes and crossings and to make it complete the different types of paths.

I've tried a bit with the NavMeshes, the different types I've solved with costs, so cars prefer greater streets and ignore pavements. But there is the problem how to tell pedestrians to prefer pavements and ignore streets?

And the main problem for me are crossings cause they start to switch the lanes and drive in the wrong side, turn around and so on.

I'm thinking about that NavMeshes aren't the right thing but doesn't get any better idea!?

My usecase is that I want to tell the police Car to drive from the police Station to a bank robbery (fixed coordinates) or the Bus to drive on a fixed route. So I want to have the Option to define multiple points and let them drive/walk to this (or the nearest) point - respecting the lanes and not do a U-Turn (not prefer this).

I don't want ready to use code, just an explained idea how to go.

# Answer
Without knowing how your structure is setup, I'll pose to you some general considerations with regards to setting up your pathing.

**Solving The Carmageddon Issue (people in the streets!).** Your sidewalk nodes and edges should be given a discount cost when a pedestrian AI does it's pathing calculation. This would make sidewalks inherently 'cheaper' to use than streets naturally.

**This Isn't London, Mr. American. (or solving the lane issue)** To discourage U-Turns you'll want to do the same thing as the above issue. Add an extra cost to calculating a U-Turn. If the edge/node it's calculating will be considered a 'U-Turn' double it's cost (or whatever value you deem fit). This again naturally helps to determine the best path given the current conditions.

When spearheading these types of path solving issues. Think about it from the perspective of the object in question. Your lane switching, crosswalks, etc, can all be solved using some type of variant of the solutions above. Of course this all varies depending on the amount of data you have to use to calculate the paths.

* Number of people on a sidewalk.
* Number of cars on a street.
* The speed of traffic on the current edge.
* The weighting of a particular crosswalk due to red/green light situations.

Hopefully some of these suggestions help you!
> 1 votes

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


title: How to check if renderer is not empty?

text:
# Question
Title: How to check if renderer is not empty?
I have a `SDL_Renderer` in SDL2 that I use both to render textures on screen and to render textures on textures, my problem is that when I render to texture the renderer may have some content in it which needs to be drawn, but if it's empty and I call `SDL_RenderPresent()` on it the screen flickers. So how can I check if there's something drawn inside the renderer?

# Answer
Ok, so from what I understood, when you are rendering to a texture there's no need to flush the renderer before, not even after; that's why there isn't such function to check if the renderer is empty or not.

So the steps are these:

```
// This draws inside the renderer's buffer
SDL_RenderCopy(renderer, texture, source, bounds);
// This switches to rendering on texture
SDL_SetRenderTarget(renderer, target_texture);
// Apparently this is enough to draw on the texture (so there's no buffer I guess?)
SDL_RenderCopy(renderer, texture2, source, bounds);
// This switches to rendering on renderer buffer
SDL_SetRenderTarget(renderer, NULL);
// This flushes the renderer buffer (so only the SDL_RenderCopy() before rendering on texture)
SDL_RenderPresent(renderer);

```

See my other question for this.
> 1 votes

---
Tags: sdl2
---


# Question
Title: Why this if logic isnot short circuiting?
I've this script in **UNITY** to check if the `hit` RayCastHid2D variable has some gameobject with `hole` tag or a parent gameobject with `hole` tag when I Raycast...

```
if (hit.collider != null && (hit.collider.gameObject.tag == "hole" || (hit.collider.gameObject.transform.parent.gameObject != null && hit.collider.gameObject.transform.parent.tag == "hole")))

```

Everything is fine until `if (hit.collider != null && (hit.collider.gameObject.tag == "hole" ||`

but when I enter `(hit.collider.gameObject.transform.parent.gameObject != null && hit.collider.gameObject.transform.parent.tag == "hole")` it throws a `NullReferenceException`....

**But why?**

It supposed to short circuit here `hit.collider.gameObject.transform.parent.gameObject != null &&` if there's no parent gameobject!

# Answer
> 1 votes
I found an answer :D

It'll be `hit.collider.gameObject.transform.parent != null`

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


# Question
Title: A method to create and assign a name to a GameObject (Unity)
I'm trying to create a function that takes in a name of an object in the editor and assigns this accordingly as well as the name of a sprite, rigidbody, etc.

Basically what I have so far is-

```
    public void thing_maker(string gameobject_name, string sprite_name, string rg_body_name)

```

which is apparently impossible to implement...

Basically my question is how can I convert a string to a GameObject name (I guess)?

EDIT:

Or, rather, is there any actually (developmentally) time saving way to use a method to create a gameobject with a specific name, then assign components with respective, specific names?

# Answer
> 0 votes
I don't believe there is any way to name the Sprite Renderer or Rigid body component. You can set the GameObject's name, which appears in the editor's hierarchy, by setting the gameobject.name to your desired value.

So my advice would be to do something like this:

```
public static class ObjectCreator
{
    public static GameObject NewObject(GameObject prefab, Vector3 position, Quaternion rotation, string name)
    {
        GameObject newObj = Object.Instantiate (prefab, position, rotation) as GameObject;
        newObj.name = name;
        return newObj;
    }
}

```

EDIT: I just reread your question and considered that you might be talking about object creation before runtime (i.e. editor scripting), in which case I'm not in a position to advise since I've never delved into that myself

# Answer
> 0 votes
If I understand correctly, what you want is, you want to create a `GameObject` with a specific sprite image, and `Rigidbody`.

This is called Instantiating a prefab. The steps are as follows:

1. Drag and drop your sprite into the hierarchy. Name it whatever you wish.
2. Add a `Rigidbody2D` component to it.
3. Drag and drop that object into your assets.
4. Now you have a prefab. This prefab can be instantiated in many ways. Irrespective of which method you use to instantiate it, what happens is, you create an object that is exactly like the prefab you just created. Complete with attached scripts (if any).

# Answer
> 0 votes
You can't name components in Unity; they are named with their Type automatically. But you can name a GameObject with following code piece:

```
GameObject.name = "Name";

```

---

**Edit:** I just realised you are talking about storing components. Well, this is an "expensive" way, but here you go:

```
public Rigidbody rb;

void Start ()
{
    rb.angularDrag = ...;
    rb.centerOfMass = ...;
    rb.collisionDetectionMode = ...;
    rb.drag = ...;
    .
    .
    .
}

public void SomeMethod()
{
    Rigidbody added = GameObject.AddComponent<Rigidbody>() as Rigidbody;

    added.angularDrag = rb.angularDrag;
    added.centerOfMass = rb.centerOfMass;
    added.drag = rb.drag;
    .
    .
    .
}

```

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


# Question
Title: Vector out of range (Batch rendering & opengl)
So ive (tried to) implement a batch rendering system, and at the for loop the error pops up and I'm not shure what ive done wrong. Any suggestions to improve the system would be much appreciated. (It's my first time trying to implement this)

```
#include "masterRenderer.h"

masterRenderer::masterRenderer() {
    quad = vector<Quad>(1000);
    numOf = 0;
}

void masterRenderer::addQuad(Quad quad) {
    masterRenderer::quad[numOf] = quad;
    numOf++;
}

void masterRenderer::init(GLuint shader, string texPath) {
    vector<GLfloat> vertex((3 * 4) * (numOf + 1));
    vector<GLfloat> normals((3 * 4) * (numOf + 1));
    vector<GLfloat> color((3 * 4) * (numOf + 1));
    vector<GLfloat> uv((2 * 4) * (numOf + 1));

    int nv = 0, nn = 0, nc = 0, nu = 0;

    GLfloat sizeV = 0, sizeN = 0, sizeC = 0, sizeUv = 0;

    for (int i = 0; i < numOf; i++) {      // The error seems to pop up over here.
        for (int j = 0; j < 3 * 4; j++) {
            vertex[nv] = quad[i].g_vertex_buffer_data[j];
            sizeV += quad[i].g_vertex_buffer_data[j];
            nv++;
            normals[nn] = quad[i].g_normal_buffer_bata[j];
            sizeN += quad[i].g_normal_buffer_bata[j];
            nn++;
            color[nc] = quad[i].g_color_buffer_data[j];
            sizeC += quad[i].g_color_buffer_data[j];
            nc++;
        }

        for (int j = 0; j < 2 * 4; j++) {
            uv[nc] = quad[i].g_uv_buffer_data[j];
            sizeUv += quad[i].g_uv_buffer_data[j];
            nc++;
        }
    }

    TextureID = glGetUniformLocation(shader, "textureSampler");
    texture_handle = Util::loadTexture("test.png");

    glGenBuffers(1, &normalbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(sizeN), &normals[0], GL_STATIC_DRAW);

    glGenBuffers(1, &colorbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, colorbuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(sizeC), &color[0], GL_STATIC_DRAW);

    glGenBuffers(1, &uvbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(sizeUv), &uv[0], GL_STATIC_DRAW);

    glGenBuffers(1, &vertexbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(sizeV), &vertex[0], GL_STATIC_DRAW);
}

void masterRenderer::draw(glm::mat4 Model, glm::mat4 View, glm::mat4 Projection, GLuint MatrixID) {
    glPushMatrix();
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texture_handle);
    glUniform1i(TextureID, 0);
    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
    glEnableVertexAttribArray(1);
    glBindBuffer(GL_ARRAY_BUFFER, colorbuffer);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
    glEnableVertexAttribArray(2);
    glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
    glEnableVertexAttribArray(3);
    glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
    glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
    for (int i = 0; i < numOf + 1; i++) {
        Model = glm::translate(glm::mat4(1.0f), glm::vec3(quad[i - 1].pos.x, quad[i - 1].pos.y, quad[i - 1].pos.z));
        Model = glm::rotate(Model, glm::radians(quad[i-1].yrot), glm::vec3(0.0f, 1.0f, 0.0f));

        glm::mat4 mvp = Projection * View * Model;
        glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &mvp[0][0]);
        glDrawArrays(GL_QUADS, 4 * i - 1, 4 * i);
    }
    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
    glDisableVertexAttribArray(2);
    glDisableVertexAttribArray(3);
    glPopMatrix();
}

masterRenderer::~masterRenderer() { }

```

# Answer
> 2 votes
There is an error in lines copying data to buffers, you give it incorrect size - not taking in account actual size of data. The second parameter should be size of data in bytes, the `sizeof(sizeN)` will **always** return 4 (=the size of `GLfloat`). For example, instead of

```
glBufferData(GL_ARRAY_BUFFER, sizeof(sizeN), &normals[0], GL_STATIC_DRAW);

```

you probably meant

```
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * sizeN, &normals[0], GL_STATIC_DRAW);

```

the size of *one* `GLfloat` times number of `GLfloat`s. Moreover, there is no need to keep incrementing the `sizeN`(also it should not be floating point type if you count integer number of elements) because you can get the element count directly from vector:

```
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * normals.size(), &normals[0], GL_STATIC_DRAW);

```

same applies to all buffers.
For the out of range problem I suggest you use `push_back()` and `reserve()` instead, this should avoid any of these problems completely. Summing it up:

```
void masterRenderer::init(GLuint shader, string texPath) {
vector<GLfloat> vertex;
vector<GLfloat> normals;
vector<GLfloat> color;
vector<GLfloat> uv;

vertex.reserve((3 * 4) * (numOf + 1));
normals.reserve((3 * 4) * (numOf + 1));
color.reserve((3 * 4) * (numOf + 1));
uv.reserve((2 * 4) * (numOf + 1));

for (int i = 0; i < numOf; i++) {
    for (int j = 0; j < 3 * 4; j++) {
        vertex.push_back(quad[i].g_vertex_buffer_data[j]);
        normals.push_back(quad[i].g_normal_buffer_bata[j]);
        color.push_back(quad[i].g_color_buffer_data[j]);
    }

    for (int j = 0; j < 2 * 4; j++)
        uv.push_back(quad[i].g_uv_buffer_data[j]);
}

TextureID = glGetUniformLocation(shader, "textureSampler");
texture_handle = Util::loadTexture("test.png");

glGenBuffers(1, &normalbuffer);
glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * normals.size(), &normals[0], GL_STATIC_DRAW);

glGenBuffers(1, &colorbuffer);
glBindBuffer(GL_ARRAY_BUFFER, colorbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * color.size(), &color[0], GL_STATIC_DRAW);

glGenBuffers(1, &uvbuffer);
glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * uv.size(), &uv[0], GL_STATIC_DRAW);

glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * vertex.size(), &vertex[0], GL_STATIC_DRAW);
}

```

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


title: Assimp and directX12 universal apps

text:
# Question
Title: Assimp and directX12 universal apps
I started a directX 12 universal app project on visual studios and started coding some stuff to create a physics engine. I was currently working on implmenting Assimp into the engine too load whatever 3d models I want. I believe I set the Assimp up incorrectly somehow. The code for loading the models worked on my last project with dx11 (non universal app). I will add the code anyways.

```
Mesh mesh;
// Create assimp importer to load the file
Assimp::Importer importer;
const aiScene* aiscene = importer.ReadFile(contentDirPath + filePath, aiProcess_OptimizeMeshes
    | aiProcess_PreTransformVertices
    | aiProcess_Triangulate
    | aiProcess_GenSmoothNormals
    | aiProcess_FlipUVs
    | aiProcess_OptimizeGraph
    | aiProcess_LimitBoneWeights);

// Append filePath to use file name as mesh name
mesh.name = filePath.substr(0, filePath.size());
mesh.name = mesh.name.substr(0, mesh.name.size() - 4);

for (UINT i = 0; i < aiscene->mNumMeshes; i++)
{
    // Set the size of indices and vertices
    mesh.vertices.resize(aiscene->mMeshes[i][0].mNumVertices);
    mesh.indices.resize(aiscene->mMeshes[i][0].mNumVertices);

    // Iterate through vertices
    for (UINT j = 0; j < aiscene->mMeshes[i][0].mNumVertices; j++)
    {
        if (aiscene->mMeshes[i][0].HasPositions())
            mesh.vertices[j].pos = XMFLOAT3(aiscene->mMeshes[i][0].mVertices[j].x, aiscene->mMeshes[i][0].mVertices[j].y, aiscene->mMeshes[i][0].mVertices[j].z);

        mesh.indices[j] = j;
    }
}

```

Now I think it has something to do with setting up the project. I went to Project-\>Properties-\>VC++Directories and in Executable, Include, & Library I added Assimp\bin, Assimp\include, and Assimp\lib respectively. Then in Project-\>Properties-\>Linker-\>Input-\>Additional Dependencies I added assimp.lib. I then included these into my project where needed. This is what I did for my non universal dx11 project and it worked fine.

```
#include <assimp\scene.h>
#include <assimp\Importer.hpp>
#include <assimp\postprocess.h>

```

Now when I run the program. I get this,

> "Unable to activate Windows Store app 'App name here' The 'exe name here' process started, but the activation request failed with error 'The app didn't start'."

So I looked at the output and it says,

> 'A dependent dll was not found'

I checked to see if there was even a dll for assimp in the bin I added, there was. I also tried moving it to where the exe was located, that didn't work either. Am I doing something wrong? Does assimp not work in universl apps? If I comment out my assimp code and rebuild it runs fine so I figured the dll it said was not found was the assimp.dll

# Answer
> 1 votes
There are several solutions to this problem:

* build assimp as a static library. When doing this make sure to link all dependencies into the library (you have to change the project properties for this, Properties-\>Linker-\>Link Library Dependencies). This way you get a proper static library (thats the way I did it). Then just link it with your Universal App.
* You can try and load the DLL yourself, make sure to use LoadPackagedLibrary and that the DLL is included in your deployed application (I did not try this with assimp, might not work depending on assimp)
* You can change the assimp project to a UniversalApp project, there is a How-To from Microsoft on this topic: https://msdn.microsoft.com/en-us/library/mt186162.aspx

That being said, the easiest way to go is by using the static library version. Universal Apps are run in a protected environment and are not allowed to load DLLs from outside this sandbox. So you have to include the DLL anyway, so there is no drawback when using a static library.

---
Tags: c++, directx, assimp
---


# Question
Title: How to create memory manipulation and how does it works?
How does memory manipulation works for cheats?, how does one create it, i think it must be something to do with your RAM and changed it to give a different value, but how to create it?

# Answer
In windows if you can get a HINSTANCE to the game process with access right of `PROCESS_VM_WRITE` or `PROCESS_VM_OPERATION` then you can use WriteProcessMemory to write arbitrary values into arbitrary locations of the game's virtual memory.

Otherwise you can attach to the process as a debugger and that will also let you stop the threads of the game to avoid race conditions.

Figuring out where to write what to is up to the designer of the cheat engine to reverse engineer.
> 4 votes

---
Tags: anti-cheat
---


# Question
Title: How to handle Multiple-accounts creation and cheating?
I am developing a game that is running as a web application. The fact is that the game lose sense if one player creates several accounts. Imagine that is a turn-based strategy game, and if you play against yourself (with another account) you can earn tons of points easily.

At first, I thought about logging every single user action, and then comparing the users IP to detect if there is any clue of cheating. But then I noticed that different users could be running under the same IP, for example if they are in the school and all them share the same IP using a proxy. Using this way innocent people could result banned.

Is there any better approach that I'm missing?

# Answer
There are a few different ways to handle this, and many solutions have their own merits. I will give my opinion of the ideal way to handle this.

First, it's important to understand that no matter how complicated your system is, someone who is sufficiently invested in gaming the system (with appropriate knowledge) will figure out a way to game it.

To seriously handle this issue, if it is really an issue for you, you need to handle this in both the design and technical implementation of your game.

---

On the technical end, you need to basically play a game of comparisons.
> In general, I am pro-logging if you are running any type of game with user interaction then verbose logs would allow you to modify and tailor your game based on real quantitative measurements.

Using your logs, you can set up a system to compare data between accounts of any number of similarities.

> For example, if two accounts are using the same IP address, or any other information that you deem an appropriate comparison measure, you would want to be able to look at overall interaction between the two (wins/losses, trading) in relation to the amount of interaction with others.

Using this data you can pass appropriate judgement on a case-by-case basis, or automatically. Depending on how widespread the issue has become, I would recommend an automatic option and handling any issues through a live moderator. It's important that you don't delete the account, just suspend it with a message along the lines of "This account has been suspected of violating this game's TOS agreement. If you disagree please go here" with a link to an arbitration panel or something.

It is important that such a thing is in place, because people could be sharing IP addresses at home, or at school. Also, for younger kids, they could be using their parent's email addresses, credit cards, or even names in their sign-up information depending on how protective they are.

---

The second phase is design side. While some benefit is to be expected, you need to sufficiently disincentivize this form of cheating with your gameplay. There are quite a few ways that you can go about this, there are the wholly annoying ones of very short timeouts (which may be necessary). But I feel the best way is by appropriately adjusting the benefits between two accounts.

> For example, some MMOs have altered the benefit that high level players recieve when playing with players outside of a reasonable level range. This discourages players with access to multiple accounts from powerleveling themselves (atleast within a specific range)

You *could* even specifically target accounts that share data and directly decrease the benefit that they gain when interacting with each other. This would encourage interaction with other players, but it can be circumvented with proxy servers and it would be ill-advised depending on your target audience.

The other way that think would work is having gameplay so engaging that people can't really manage to play two separate accounts and still keep up with everyone else.

---

Of course with this system, you would need to spend a nice deal of effort tweaking to prevent false positives and what not.

## tl;dr?

You want to collect appropriate data that allows you to automatically detect and handle potential threats and deal with false positives on a user-by-user basis. A good deal of babysitting would be necessary to make sure you don't have false-positives.

Also you want to reduce the benefit of cheating with multiple accounts on the gameplay end.
> 14 votes

# Answer
The simplest and most effective way to counter 'farming' of scores is to adjust the score received based on the disparity between the players. Bear in mind it's not just one player creating multiple accounts you need to worry about: imagine two friends, one deliberately losing so the others ranking is artificially boosted.

Chess and other games avoid this through forms of the Elo rating system. Basically the reward for beating someone of a higher rating than you is high, but the reward for beating someone of a much lower rating is very low. This very quickly makes deliberately losing to advantage another player ineffective. You can tune the rate at which winning against a poor player quickly results in little net gain. A player playing 'properly', i.e. winning against a wide range of similarly ranked opponents, will advance very quickly.

NB: it's not enough to just penalise players who lose so that winning against them gets you nothing, because then players can create an account, lose with it deliberately, then create another account. This isn't so much of an issue if there is a barrier to entry (e.g. entering credit card details to create a new account), but for free-to-play games that would work.

Also its worth noting that there is a danger if the ratings are used as a measure of actual ability, rather than just as a way to modify any rewards the player receives. If the rating itself is the measure, canny players will use the system to sabotage others. I.e. Player 1 gains a lot of skill/ability through practice, and then creates a new account. Player 2, who is about as good as Player 1, accepts a challenge from the newcomer. Losing to the newcomer will massively hurt their ranking, even though really the new player is of equivalent rank. However if the rating isn't actually used to measure the player, this is actually in Player 2's interest (having their rating pulled down will allow them to advance faster given their actual skill level).
> 8 votes

# Answer
You could award points based on the difference between the opponents' point totals. Very good players would earn few points for defeating newbies, and newbies would earn many points for defeating experienced players. Likewise, losers would lose points proportional to the same scale.

This wouldn't completely solve your problem, but it would eliminate the simple case of someone creating and defeating a bunch of newbie alts, as well as making it harder to level two different accounts of equal power.

Really, though, there's not a foolproof way of stopping this; a sufficiently dedicated cheater will succeed. But if you flag accounts with suspicious activity for review, where "suspicious activity" includes multiple accounts with the same e-mail or IP address, then you'll be able to spot the most egregious offenders.
> 7 votes

# Answer
I've found this is much easier to fix through game design than through enforcement/banning. Even if you permanently ban all of a player's accounts, sufficiently determined players can find a way around your ban (e.g. if you track IP, they can use dynamic IP or IP masking).

For example, if you award points to players for winning PvP contests, you give players incentives to make multiple accounts so they can lose to themselves. If instead you give bigger rewards for playing in groups with the same players over time (i.e. guild participation), you incentivize friendship and community over competition, which changes preferred behaviors. Having additional metagame characteristics tied to the player's account (such as a Reputation score and Friends list) further makes the maintenance of multiple accounts less appealing -- at the least, people would want one "primary" account with a good rep.

If your game is PvP by nature, a big way around the "I'll make several accounts and lose to myself on purpose" problem is to only offer automated matchmaking. So, the player requests to play a game, and the server automatically matches them against someone else who happens to be online at the time. If players can't choose their opponents, there's no way for them to guarantee they'll fight themselves (unless they happen to be the only one online at the time, but then you have bigger problems). See Microsoft Hearts/Spades, or most Facebook games that allow PvP, for examples of this. Note that in this case you'll definitely want some kind of intelligent matchmaking (either using some kind of ranking/rating system as part of the player account, or letting players self-select their preferred level of competitiveness).

If you're worried that players will want to play games with their friends, you can always offer that option as well, but only allow unrated/unranked/practice games when you choose your opponents.
> 6 votes

# Answer
The people over at https://panopticlick.eff.org/ did some testing on how somebody could be uniquely identified by several values that can be gathered from almost any browser. The results are astounding and you could use a similar approach (maybe combined with other measures) to identify and track your users.
> 5 votes

# Answer
There's a very simple design solution that Blizzard took in Warcraft 3 and Starcraft 2: only let players earn points/score/experience when playing in games using the automatic matchmaking service. Players can still play against their friends, but won't get points from it.

If the player has no way of deciding who they are playing against, there's no reliable way to game it by playing against dummy accounts.
> 4 votes

# Answer
i play on a game system called travian, and i really think the technology isnt good enough to catch cheats. Most cheats have 2-4 systems linked via KVM switch, each system runs different OS versions(windows xp, vista, win7, linux mint, Slitaz and so on) , and is run in via proxy servers (though the main account is not using proxy but standard)

This of course creates such an unfair advantage that most of the people that pay to play the game are leaving, with paying members down over 1000 in just a few months, and with the fewer players, its becoming increasing more obvious that accounts are suspicious, but with no evidence of cheating, the players that do cheat escape punishment, and those that pay fairly (whoops, meant to say play fairly) can see the suspicious activity, they get discouraged and quit the game - or they learn to cheat and hence inlies the problems.

Currently for travian, there is no player in the top of the game that can honestly say they dont cheat, or admitt they havnt hired people from countries like the phils and china to help them play the game for them while they sleep or are on holidays.

surely there must be better ways to catch multiple account cheats, or is this the future of games, where just a few actual people make up the entire game base and the winner is based on who can hire the most people in 3rd world countries to play the games for them.

would membership of $0.01 via credit card (and see who has identical credit card numbers) be a feasible way to detect multiple account cheats at time of registration?
> 1 votes

# Answer
One option if you have multiple servers is to require that any accounts from the same IP must be created on alternate servers. So if you want to create 10 accounts, great, but you'll have to create them on servers that don't interact with each other. This prevents people at the same location from being able to play together, so there is that drawback. On the plus side it also interferes with the effectiveness of proxies in cheating.

You're going to end up with pros and cons to any solution you come up with, and you won't completely eliminate cheating. So decide how far you're willing to go and keep a close eye on how those changes effect the user base.
> 1 votes

# Answer
Most people try to chase after multi accounts with external tools. Which is stupid. If you have proper logs and metrics for user activities you could nail most multi-accounters with a handful of criteria scans inside a game.

And no, I'm not going to hand you the breakdown - truth is - and very few people in the industry are going to spell it out - the more stupid game designers and coders are out there the better job security for the people who know what the hell it is they are doing.

Multi Accounting is only even viable to people if the benefit chain is badly designed and can by manipulated easily by multi-accounts.

If multi-accounting is hard and time consuming in terms of reward (not detection dodging - just gameplay effort and time)

Then the only people really doing it are the hardcore players. And you don't even need to bother raising an eye brow to them as they are community drivers. They spend every effort to know all your loopholes and study efficiency within an environment. By all rights the effort they invest should be the best rewarded. You still get to monetize the majority of lazy ones.

Good designers never really go plugging every loophole - just plug the major ones and make sure you have a way to take out excess out of the economy. Or obviously inject value in if need be.

I have a list on hand of 83 multiaccounters. They think they are fooling us - and get to enjoy the happiness of the idea that they are smarter than us. Most also invest real cash into the game - we don't want to ban them. Our coders didn't really have time for a system - So I set up CM with a secret dummy account to occasionally bash their heads ingame and "legitimately" steal their "riches".

They think they are playing us as company, and are getting increasingly motivated by thinking someone else ingame has an axe to grind. End result is - any critical excess is discarded by a CM - considering he knows what the user is upto, and pull an "ambush" at any time. All of which - can be automated by code but, who has time or budget for that?

Anybody building complex multi-account detection systems for profiling user IDS, to prevent multi accounts in games is pissing against the wind to begin with.
> 1 votes

# Answer
You really need to identify the specific behaviors that you want to prevent.

For example, if the real problem that you want to prevent is not "people making multiple accounts", but "individuals being targeted by multiple accounts controlled by the same person", that's an area where you can use similar traits between potentially clone accounts to **allow the players themselves to police multiplaying**. In other words, if they detect traits of multiplaying, they can act (via some interface) to check for similarities between the accounts, and if the accounts do have too many similarities, cause a punishment to occur. Player policing. The benefit of this is that multi-accounting **matters the most** to other, non-multiplaying individuals, so if they feel wronged, **they have a recourse** they can try to catch the multiplayer on the spot. It also allows things that in a flatly viewed account system would be false positives (like ip) to be much more real evidence of multiaccounting.

Similarly, as others have mentioned, if it's the gaining of rank by defeating their own dummy accounts, a system like the rep system here on stackexchange helps to turn taking ranking points from yourself into a zero-sum gain.
> 0 votes

# Answer
**Ensure that making multiple accounts isn't worth it**.

Examples of how you'd do this:

* Grant tiny awards in the first few levels compared to later levels.
* Compulsory tutorials - first time players will find it useful and multi-accouters will find them incredibly annoying.
* If there's a reward for referring others, give the award once the referred player reaches a certain level.
* If players battle one another, make winning against low(er) level players get waste of time. E.g. anyone under more than 5 levels than you won't give you rewards for winning against.
* The StackExchange network is an excellent example. Making new accounts has very little benefit.

Allow players to make multiple accounts because you can't stop them from doing it anyway:

* If you add IP blocks, people will use proxies and VPNs
    + IP checking also bring about false positives.
* Tracking cookies and local storage data can be deleted.
* If you try to collect (a lot of) personal information, it'll strongly discourage people from registering and it's useless if you don't verify it.
* Each account typically takes up a few bytes of space. You can afford that.

Out of all of these answers, this method is the only one that truly works. If people won't want to make multiple accounts, they won't do it. You can decide on what they want through good, considerate game design.
> 0 votes

# Answer
I think there is another aproach. Because there is another potential harm: Imaging two friends who both create two accounts: one looser and one winner account each. One day friend A uses his looser account to loose all games against friend B's winner account. The next day they change. Checking the IPs won't help here.

You should check the behaviour of the players (a strategy know from intrusion detections systems). If two player play each other often and one looses all the time, this is a clue. If games end very early, it is another clue.

You could score those clues, add the score up to a reputation (don't show the reputation to the users) and ban accounts if they reach a value you define. Maybe there should also be anti-clues that repairs the reputation.

Other clues depend very much on your game. But I think you get the idea.
> -1 votes

# Answer
You can use Flash local data storage, not everyone knows how to delete flash data.
> -1 votes

# Answer
Not really a solution, but a deterrent at least: Say that if people are discovered having multiple accounts, all accounts will be banned. This should keep many people from even trying it. Even if you don't actually ban all accounts, or don't have a way to detect it at all, most will be too afraid.
> -2 votes

---
Tags: web, anti-cheat
---


title: Movement calculation from delta time

text:
# Question
Title: Movement calculation from delta time
I'm trying to calculate object speed from delta time, to get object reaching the same distance in same time on all devices.

What I did:

```
while(running)
    float timeSinceStart = System.nanoTime();
    float deltaTime = (timeSinceStart - oldTimeSinceStart) / 1000000000;
    oldTimeSinceStart = timeSinceStart;

```

From that I'm getting deltaTime:

* 2.2789123E8 on my old Galaxy Ace S5830i
* 2.7855414E8 on my tablet A7600-F

And then I do this calculation:

```
float calculation = screenWidth/2 * deltaTime; //My game is in landscape mode
int speed = Math.round(calculation); //speed represents pixels per update

```

Which should give speed that half of the screen is reached per 1 second, regardless on device updates (fps). It should be small number, about 10-20, but calculation results in

* 546 on Ace
* 1782 on tablet

What to do with that? As I said, if I set speed to fx. 11, it's reaching about half of the screen in my game on tablet. So why are these number's so large?

Ed: Ace width = 480, tablet width = 1280;

# Answer
> 1 votes
Something is wrong with your delta time. 2.2789123\*10^8 are equal to 7.22 years for one frame. I think you don't initialize `oldTimeSinceStart` then read deltaTime after one frame. You should init `oldTimeSinceStart` with `System.nanoTime();`

---
Tags: java, android
---


title: Handling items at the Server-side

text:
# Question
Title: Handling items at the Server-side
I'm coding a very simple game Rust/Dayz like with Unity, and I'm using Forge Networking as network library.

A few days ago, I started to code the Loot system. The Loots in my game are Items that are instantiated in the game world (in other words, the items that are on the ground) and I was implementing the system that send and receive Loot data from and to the server (the server is fully authoritative).
I also created a LootSpawnManager class that contains, in a list, all the Loot spawned in a certain Loot spawn spot (so there is a LootSpawnManager for every spawn point of the Loots object).

In my game the server checks if a player is in a certain range from the Loot gameObject. If it is, then the server sends the Loot data through the network to the client, and the client with that data creates a Loot object and instantiates it in its world (scene).

For optimization (because checking if there are players in an area is a bit expensive), the LootSpawnManager has a list, with all the players nearby, that is refreshed every 4/5 seconds. So, for example (in the server) if a Loot is added to a LootSpawnManager (or a Loot already in the LootSpawnManager list has changed its properties) the server sends the data to the players that are in the LootSpawnManager's players list.

So far no problems. The issues come when a Loot doesn't belong to a LootSpawnManager. In the game there will probably be hundreds if not thousands of Loots that don't belong to a LootSpawnManager, so every single Loot would have to do its check every 4/5 seconds, and this will certainly kill server performance.

A solution to this problem could be to group near solitary Loots in a class similar to LootSpawnManager that has the player list for that zone. But I don't think that this will help, because there will be few cases in which a lot of Loots are near, although in the majority of cases there will be maximum 2-3 Loots. So the question is: are there any good performance solutions for this problem?

**EDIT :**
I didn't mentioned that the client doesn't have instantiated all the Loots that are in the server, and the players have instantiated only the Loots in a certain range from them. If they are too far from a Loot they delete it (I'm talking about the single client side, so deleting means deinstantiating the object, not removing it in the server) and, like I explained before, if they are nearby a certain range from a Loot, then the client has to wait for the server checks.

P.S. I hope my English is understandable (it's not my mother language) and that what I just wrote above is clear.

# Answer
> 2 votes
I think you need on the server a generalized subsystem that tracks/accelerates spatial queries for authoritative objects. Loot would be one of these where the loot is registered with the system. Objects would then be replicated to clients in range. Testing would be cheaper because the system accelerates it via spatial structure and multi-frame coherence. The objects on the server deemed near a player could perform authoritative actions and send results to clients as well.

From your comments you indicate that the world is a 3D-heightmap. You don't indicate number of players, but here is a basic rundown of how I would build a system:

Given that the size of the world is fixed, I would define a grid size (that will need to be tuned later for performance reasons). I would then start with a two-dimensional grid where each cell of the grid is a list of items in the grid. I can imagine that you might have an interface or base type for items in the grid to make things easy to start with.

Now we need to keep track of which cells to look at each frame - which cells are occupied by one or more players and need to be searched. There are two strategies here - you could simply iterate over each player and check the cell the occupy. Run the list of items in the cell and update them against the player. The problem I see here is that you would update an item twice if two people are in the cell, so you might need two steps: 1) maintain a dictionary of all the cells and a list of each player in the cell so you can iterate over the dictionary and update each cell regardless of number of people in it. 2) Run the list of players to update their relationship to the items in the cell.

I only consider a two-dimensional cell because most heightmaps can't support overhangs, so you can discard the z (height) dimension.

There are so many optimizations to be made here but I think starting out that way would help.

---
Tags: unity, networking, client-server
---


title: Speed from delta time not correct

text:
# Question
Title: Speed from delta time not correct
My game object isn't moving in correct speed calculated from deltaTime bellow. It should reach half of the screen in one second, on any device.

Devices:

* tablet A7600-F - deltaTime = 0.03355443; (res. 720x1280)
* Xperia Z3 Compact - deltaTime = 0.13421772; (res. 720x1280)

Calculation:

```
calc = (screenWidth / 2) * deltaTime. //I have app in landscape mode
speed = Math.round(calc);

```

speed on tablet - 21px per update; speed on xperia - 86px per update;

You can see these results are very different (actualy it should be something about 8px - 20px). Game object is then extreme fast on Xperia (on tablet it's just a bit faster - speed is more than half of the screen per second).

What am I missing?

# Answer
> 1 votes
The speed itself is correct. Because FPS = 1/dT. On tablet it is ~29.8FPS, and on xperia it is ~7.45 FPS. In 1 second the object travels updates count times pixels per update. That gives ~626px for tablet and ~640px on experia. The error above was caused by `Math.round(calc)` once in the process (="once per second"). If the position is stored as integer(rounded) the error will start to *accumulate* and **keep growing** each frame!
There is also the that fact actual number of updates per second is integer: For example with given integer speed xperia with (*constant*) 7.45FPS can do either 7 or 8 updates giving you either 602 px or 688 px, likewise the tablet will give either 609px or 630px. If the FPS is not constant (which is not in practice) the results can be even worse.
My suggestions:

* use higher accuracy tools (double instead of float, higher precision dT)
* postphone the rounding to the very last moment (save position as float-type and pass rounded copy to the actual drawing)

Also make sure the speed is incorrect: it can *perceived* incorrect while in-fact correct - for example physical dimension or the object is moving in dimension that is shorter that `screenWidth`.

---
Tags: java, android
---


# Question
Title: How do I avoid floating point indeterminism when implementing lockstep?
I am working on a multiplayer RTS game in Java. It uses lockstep for networking, which requires that both computers can deterministically.

These are the 2 closest/more viable approaches I could come up with- but both have issues:

* The first is to just use int and long for all my player positions and stuff, and get any use of floating point math totally out of the game model. I like this concept- but the problem is what happens when I need a square root, or a cosine? I would have to basically make an entire math library!
* I also found that I can use the strictfp modifier and StrictMath class to do deterministic math with doubles... Which I could see using this to create deterministic math within my games model. It would be very prone to bugs as it would be very easy to accidentally go outside of the "strict" scope though.

Also I cant seem to figure out if serializing a float or double causes it to lose its determinism. I'm using Kryo/Kryonet right now, but I cant seem to find any information on if it is deterministic with floats or not (I cant seem to find any information on the built in java serialization either, or any other serialization library)

Does anyone have any suggestions on how I could tackle this problem?

# Answer
Like you say, it is technically possible to get determinism out of floating point, and some well known RTSs have used floating point in the deterministic simulation, but it is easy to get wrong leading to bugs that are hard to find and reproduce and hard to solve.

A good link on floating point determinism is here: https://randomascii.wordpress.com/2013/07/16/floating-point-determinism/

A much simpler solution is to use fixed point math, and is also found in well known RTSs (SC2 for example).

Fixed point math stores values in integer types, using an implicit decimal point.

For instance if you had a uint32 that was in 24.8 format, you'd have 24 bits for the integer part, and 8 bits for the fractional part.

That means you can store fractions of $N/256$.

Adding and subtracting fixed point numbers is easy - you just add and subtract the integers.

Multiplication involves multiplying the ints and then right shifting by the number of fractional bits.

Division involves left shifting the divisor by the number of fractional bits and then doing the integer division.

Converting from float to fixed point is simply multiplying the floating point number by $2^F$ where F is the number of fractional bits, and then storing that number in the int.

Converting from fixed to float involves storing your int in a float and then dividing by $2^F$ to get the floating point value back.

Once you have a fixed point number class, you do need to implement things like pow, cos, sin etc if you need them.

Make sure and not use ANY floating point values in the simulation though.

All numbers in your game data for instance (like, how much damage a unit does) should be already be in the data file as fixed point.

Any mixing of fixed and float could cause two clients to fall out of sync and is no good.
> 3 votes

---
Tags: java, networking, floating-point
---


# Question
Title: Updating score in collision detection game in XNA
I created a collision detection game in XNA but I have a problem with the scoring. As online tutorials says, I initialised it

```
score = 0;

```

This is in the update section to check if the person hit the object

```
// Check collision with person
                if (personRectangle.Intersects(numberRectangle))
                    personHit = true;

```

Then in the draw section..

```
if (personHit)
            {
               score = +score + 1;
               spriteBatch.Draw(greenBackground, mainFrame, Color.White);
            }
            else if (personHit2)
            {
                score = +score - 1;

                //device.Clear(Color.Red);
                spriteBatch.Draw(redBackground, mainFrame, Color.White);
            }

```

But when the person hits the objects that fall, the score goes up until that object is on the person image. I don't know if I am clear. The score doesn't go up by one per hit, it goes up until that object stops touching the person..

I was wondering how can I fix this so the score goes up by 1 only?

# Answer
> 2 votes
Try doing something like this instead:

```
//Person wasn't hit yet, check if a hit occured
if (!personHit && personRectangle.Intersects(numberRectangle))
{
    personHit = true;     //hit occured
    score++;              //increase score
}
else
{
    personHit = false;    //person has moved outsite hit rectangle, reset
}

```

You really want to keep all processing out of your draw calls. All your processing should be done in your Update portion of your game loop.

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


title: Liang-Barsky Line Clipping Algorithm

text:
# Question
Title: Liang-Barsky Line Clipping Algorithm
Is it possible to generalize Liang-Barsky Line Clipping Algorithm for n-dimensional space ?

# Answer
To add a little context for those reading, the Liang-Barsky algorithm determines the segment of an infinite straight line that intersects an axis-aligned rectangle, if any. And yes, it can be trivially extended to clipping lines against n-dimensional axis-aligned hyperrectangles pretty trivially.

Since we don't have LaTeX markup in this exchange, I'll use bold to represent n-dimensional vectors.

The parametric equation of our line is:

**x** = **p** \+ u * **d**

where **p** is some arbitrary point on the line and **d** is a vector in the direction of the line. u is our parameter. The output of this algorithm will be two values of u where the line enters & exits our hyperrectangle, respectively, or a good reason why we lack two such values. ;)

Our hyperrectangle can be defined by two vectors, **Least** and **Greatest**, expressing the least and greatest values covered along each axis. (n-dimensional analogs of the bottom-left and top-right corners)

Now we can define two vectors A and B:

**A** = **Greatest** \- **p**, **B** = **Least** \- **p**

Now we look component by component...

```
u1 = NegativeInfinity;
u2 = PositiveInfinity;

for(i = 0; i < n; i++)
{
   if(d[i] == 0)  // for floats you'll want an epsilon here.
   {
       // Our line is parallel to two of the hyperrectangle's sides.
       // A[i] < 0 means it passes "above" our rectangle,
       // B[i] > 0 means it passes "below"

       if(A[i] < 0 || B[i] > 0)
          return NO_INTERSECTION;
   }
   else
   {
      b = B[i]/d[i];
      a = A[i]/d[i];

      if(d[i] < 0)
      {
          // The line runs high to low along this axis.
          // it crosses the high side first (at a), then the low side (at b)
          u1 = max(u1, a);
          u2 = min(u2, b);
      }
      else
      {
          // The line runs low to high along this axis.
          // it crosses the low side first (at b), then the high side (at a)
          u1 = max(u1, b);
          u2 = min(u2, a);
      }

      if(u2 < u1)
          return NO_INTERSECTION;
   }
}

```

If we get to the bottom, then the line segment crosses our hyperrectangle from

**x1** = **p** \+ u1 * **d**

to

**x2** = **p** \+ u2 * **d**

and "kisses" the box along an edge or corner if u1 == u2, so there's only one point of intersection.
> 1 votes

---
Tags: algorithm, clipping
---


# Question
Title: How do I structure AI that uses both Behavior Trees and Pathfinding?
Architecturally, what are the best practices for how these two concepts interact with each other?

For instance, say I have an asteroids like game where the AI player must dodge floating asteroids while at the same time collecting powerups. If we want him to perform well we can't just have two separate behaviors for dodge and collect, he should consider everything on the screen.

Should the behaviors in the tree modify the weights of the pathfinding graph nodes (assuming using a graph based approach here)? Is A\* like path finding even the best approach for this scenario?

# Answer
> 1 votes
> Should the behaviors in the tree modify the weights of the pathfinding graph nodes (assuming using a graph based approach here)?

That is an option, yes. A behavior mode that is trying to stay sneaky is likely to prefer A\* nodes that have a high stealth value while a behavior that wants to get somewhere quickly will prefer A\* nodes with the fastest traversal speed.

> Is A\* like path finding even the best approach for this scenario?

No, not really. For an asteroids-like game you almost certainly want steering behaviors as your primary movement, not path-finding. More complex games will typically use a combination of A\* and steering for traversing the terrain.

---
Tags: architecture, ai, path-finding
---


# Question
Title: Blender mesh mirroring screws up normals when importing in Unity
My issue is as follows:

I've modeled a robot in Blender 2.6. It's a mech-like biped or if you prefer, it kindda looks like a chicken. Since it's symmetrical on the XZ plane, I've decided to mirror some of its parts instead of re-modeling them. Problem is, those mirrored meshes look fine in Blender (faces all show up properly and light falls on them as it should) but in Unity faces and lighting on those very same mirrored meshes is wrong. What also stumps me is the fact that even if I flip normals in Blender, I still get bad results in Unity for those meshes (though now I get different bad results than before).

Here's the details:

Here's a Blender screen shot of the robot. I've took 2 pictures and slightly rotated the camera around so the geometry in question can be clearly seen:

Now, the selected cog-wheel-like piece is the mirrored mesh obtained from mirroring the other cog-wheel on the other (far) side of the robot torso. The back-face culling is turned of here, so it's actually showing the faces as dictated by their normals. As you can see it looks ok, faces are orientated correctly and light falls on it ok (as it does on the original cog-wheel from which it was mirrored).

Now if I export this as fbx using the following settings:

and then import it into Unity, it looks all screwy:

It looks like the normals are in the wrong direction. This is already very strange, because, while in Blender, the original cog-wheel and its mirrored counter part both had normals facing one way, when importing this in Unity, the original cog-wheel still looks ok (like in Blender) but the mirrored one now has normals inverted.

First thing I've tried is to go "ok, so I'll flip normals in Blender for the mirrored cog-wheel and then it'll display ok in Unity and that's that". So I went back to Blender, flipped the normals on that mesh, so now it looks bad in Blender:

and then re-exported as fbx with the same settings as before, and re-imported into Unity. Sure enough the cog-wheel now looks ok in Unity, in the sense where the faces show up properly, but if you look closely you'll notice that light and shadows are now wrong:

Now in Unity, even though the light comes from the back of the robot, the cog-wheel in question acts as if light was coming from some-where else, its faces which should be in shadow are lit up, and those that should be lit up are dark.

Here's some things I've tried and which didn't do anything:

* in Blender I tried mirroring the mesh in 2 ways: first by using the scale to -1 trick, then by using the mirroring tool (select mesh, hit crtl-m, select mirror axis), both ways yield the exact same result
* in Unity I've tried playing around with the prefab import settings like "normals: import/calculate", "tangents: import/calculate"
* I've also tired not exporting as fbx manually from Blender, but just dropping the .blend file in the assets folder inside the Unity project

So, my question is: is there a way to actually mirror a mesh in Blender and then have it imported in Unity so that it displays properly (as it does in Blender)? If yes, how?

Thank you, and please excuse the TL;DR style.

# Answer
> 1 votes
OK, I've solved it. Apparently it's normal than Blender does this when you mirror an object. The thing to do, in Blender, before exporting, is to select the object in question, hit CTRL-A, and from the menu that shows up, select (Apply) "scale".

To my shame, I do admit that I've now noticed that for objects such as my screwy cog, Blender would issue a warning along the lines of "something's bad with this objects transforms, apply scale to fix" when exporting, but that really didn't explain what was happening (plus, it issued this messages for other objects, which were fine when imported in Unity).

# Answer
> 2 votes
The above answer does indeed solve the problem, but I've also found that unless I recalculate the normals after applying Scale, the problem still occurs.

So - Mirror object, Apply Scale, Recalculate Normals - Hey Presto!

---
Tags: unity, blender, normals
---


# Question
Title: Can we port any game written in C++ with SDL to Android platform or we would need to change some codes too?
Just wanted to lean a cross-platform library!!

Since SDL library supports iOS too..

# Answer
> 2 votes
No, you cannot port any ol' game written in C++/SDL to another platform.

Most games only use SDL for a few small bits (windowing and input) and rely on a great deal of other platform-specific code for rendering, audio, file I/O, threading, debug facilities, networking, etc.

SDL does provide tools for those services, and some SDL games will be pure SDL with no other external dependencies, but as SDL's facilities in those areas is very weak those games are rare.

Even with pure SDL, Android and iOS use different C++ compilers and have numerous other minor differences that makes porting even well-written cross-platform applications more involved than just recompiling.

---
Tags: c++, android, sdl, sdl2
---


# Question
Title: Finding pitch/yaw values from lookat vector
I have a camera class that contains a position, a pitch, and a yaw (the pitch and the yaw correspond to y and x rotation values). I want to implement a lookAt function that takes a vector and the function changes the pitch and yaw so it's looking at that point in space. However, I cannot seem to find the math equation to do it (various ones online, none seem to work). How would I be able to implement it?

Here's an example of what I mean:

```
struct Camera
{
    Vec3 position;
    float pitch, yaw;

    void lookAt(Vec3 center)
    {
        //????
    }

    mat4x4 toTransform() //How I convert the values to a matrix (if this is relevant)
    {
        return CreateLookAtMatrix
            position,
            position + Vec3(cos(pitch)*sin(yaw), sin(pitch), cos(pitch)*cos(yaw)),
            Vec3(0.0f, 1.0f, 0.0f)
            );
    }
}

```

# Answer
You've already got the answer in your matrix function:

`lookAt = position + Vec3(cos(pitch)*sin(yaw), sin(pitch), cos(pitch)*cos(yaw))`

You just need to do a little algebra to get the yaw and pitch variables over to the left.

To start with the simplest expression, the y-axis gives:

```
lookAt.y = position.y + sin(pitch), which we can rearrange to...
sin(pitch) = lookAt.y - position.y
pitch = asin(lookAt.y - position.y)

```

Where asin is arcsine, the inverse of sine.

Note that this assumes `lookAt - position` is a unit vector (length 1) which in your matrix expression is true by construction. If `center` can be anywhere then you'll want to start by constructing the unit vector you need:

```
void lookAt(Vec3 center)
{
   Vec3 direction = (center - position).normalized;
   pitch = asin(direction.y);
   yaw = atan2(direction.x, direction.z);
}

```

I skipped ahead a bit on yaw there because we have both `k*sin(yaw)` and `k*cos(yaw)` for some real `k`, so we can just drop that into the atan2 convenience function and let it sort out all the cases for us. ;)
> 9 votes

---
Tags: opengl, c++, 3d, mathematics
---


# Question
Title: Libgdx switching between screens without losing Information
I've been having issues with Screens, as I want to switch between the main game screen, the battle screen and the ingame menu screen (JRPG). The problem is that I have initialised all the information (Position of Player and NPC's, Map data, Sava data, etc) in the Show() function of the screen. That means that when I switch between 2, it will rebuild and reload everything all over again. There is also no Create() function in Screen so I'm at a dead end right now. Is there a way I can reserve data or draw the other screen on top of the main game screen, pausing that one?

I really need help with this.

# Answer
Don't initialize everything in `show`. Consider passing a reference of the *parent* screen to the *child* screen along with a reference to your `Game` instance when creating new screens. That way the *child* screen has a way to get back to an already initialized version of the parent screen.

```
public class MyLibGdxGame extends Game {
  @Override
  public void create () {
    MainScreen mainScreen = new MainScreen();
    setScreen(mainScreen);
  }
}

public class MainScreen implements Screen {
  private final MyLibGdxGame game;

  public MainScreen(MyLibGdxGame game) {
    this.game = game;
    // Setup and load stuff here
  }

  @Override
  public void render(float delta) {
    // Update and render your game state as per usual here

    if (should_show_battle)
      game.setScreen(new BattleScreen(game, this));
  }
}

public class BattleScreen implements Screen {
  private final MyLibGdxGame game;
  private final Screen parent;

  public BattleScreen(MyLibGdxGame game, Screen parent) {
    this.game = game;
    this.parent = parent;
    // Initialize battle screen here
  }

  @Override
  public void render(float delta) {
    // Update and render your game state as per usual here

    if (should_return_to_parent) {
      // As parent here is already initialized, there's no need to reload
      // or setup anything
      game.setScreen(parent);
    }
  }
}

```
> 4 votes

---
Tags: java, libgdx, screen-management
---


# Question
Title: In what size should i design sprites for unity iOS?
I am developing a 2D platform game in unity.I have conceptualised the game and have to design the art assets/sprites, but the problem is at what resolution or size do i design them?

If I target the sprites size to iPad pro (as its has got highest resolution of all iOS device), can the older iPhone 4S handle it?

What are the best methods of designing art assets for multiple resolution(with best performance on older devices)?

# Answer
> 2 votes
I think you should design for one of the larger aspect ratios and use anchors and canvas scaler to get the layout to work on different aspects.

That makes it easy later (when testing on device) to decrease the resolution if you run out of memory or if you need to optimize for other reasons. Your UI might even look good in a smaller resolution.

If I'm not remembering this wrong, iPhone 4s supports a max texture size of 4096x4096 (using OpenGLES 2.0).

> Designing UI for Multiple Resolutions:
>
> http://docs.unity3d.com/Manual/HOWTO-UIMultiResolution.html

# Answer
> 2 votes
Design for Aspect ratios instead of fixed resolution. Unity will automatically scale everything if it is same aspect ration. Consider this:

iPhone 6 resolution : 1334x750 \[Aspect ratio 16:9\] iPhone 6+ resolution : 1920x1080 \[Aspect ratio 16:9\]

What it means is if you designed for iPhone 6 resolution, it will be automatically scaled on iPhone 6+ ensuring consistency.

Best approach is to design your game keeping in mind 4:3 and 16:9 aspect ratios which are most common. Ideally, all your game should take place in 4:3 and have background elements so that there's no black bars/skybox visible in 16:9.

However, exactly which resolution to set for a particular aspect ratio is tricky. Best approach would depend on the most popular devices on the market. Samsung Note 4 and some Galaxy S series have higher resolution than iPhone for example. Do take a look at my answer here. That explains about finding out sizes for aspect ratios.

# Answer
> 1 votes
The best resolution I consider to develop with designs, is according to iPhone6+. My designs work with all IOS, Android and WP devices. Just have to put some tricks like,

1- Use assets on scale of 0.5.

2- If your background solid in color, then no need to design, just put image to 10x10 px and resize it in Unity.

3- If your background image can afford small resizing (means no major changes occurred by squeeze or stretch it, just make a quad of unit size and scale it to the screen size. You can get 2d screen size by,

> var worldScreenHeight = Camera.main.orthographicSize * 2.0; var worldScreenWidth = worldScreenHeight / Screen.height * Screen.width;

4- If above condition is not true for you thn make background little larger then screen size so it will make no difference if it clips out.

---
Tags: unity, sprites, ios, resolution
---


# Question
Title: How to calculate Joystick margins/thresholds?
On a joystick that gives float position values **from -1 to 1** on either of **x and y** axis, how do I implement the math that adds "lower" and "higher" circular margins?

---

For example if lower margin is 25% (0.25 float) of radius, and higher margin is 50% (0.5 float), it might look like this:

The actual "hot" zone is green, meaning:

1. **Grey** area should always give **0,0** readings of x/y.
2. **Green** area should give **actual values** of x and y form range **-1 to 1**.
3. **Blue** should always give **1** or **-1**.

# Answer
> 1 votes
A better way of doing it if you represent the thumb-stick's position as a vector. It's similar to my other answer except it's using vector math, but at least it takes both the x and y at the same time and not just one by one which doesn't work.

If you say that the thumb-stick is at position x0 and y0, then it's corresponding vector u = \[x0, y0\]. The length of vector u is the distance from the origin (point 0,0). Now if the length of u is less than the lower margin, 0.25 in your case, you can set it equal the zero vector, u = \[0, 0\].

If the length of u is higher than the lower margin but smaller than the higher margin, then we can us the mapping \[low, high\]-\>\[0,1\] like in my other answer except here the input is the length of u and the output is the length of v, the output vector. To scale a vector we simply make it unit-length by dividing it by its length, then multiply it by however long we want it to be, in this case the length of v.

In the last case if length of u is higher than the high margin, we want it to have a length of 1. To get u to be of unit length, again we divide u by it's length.

Here is an example function that takes a vector u representing the thumb-stick's position and outputs a vector with your new marginalized x and y values. If you actually do it this way, you'd probably want to calculate the length of u once.

```
vector fromUtoV(vector u) {
    vector v;
    if (u.length < low) {
        v = vector(0, 0);
    } else if (u.length >= low && u.length <= high) {
        v = (u / u.length) * ((u.length - low) / (high - low));
    } else if (u.length > high) {
        v = u / u.length;
    }
    return v;
}

```

Interactive demo: http://ggbtu.be/m2237257

# Answer
> 0 votes
**Edit: On afterthought this answer doesn't work when considering both the x and y at the same time. If the thumb-stick was a lever with only 1 dimension of motion, and r was the distance from the center (lever pointing straight up) this should work. So I'm leaving this answer here. I've also have made another answer that's working with a proper 2D thumb-stick.**

How I would solve it would be to map the possible radius values to a corresponding desired value and clamp that. So if I have the radius values r=\[0.25, 0.50\] and the output values v=\[0, 1\]. I can find a math function that linearly maps r-\>v. v is either the x-value or y-value depending on whether the r represents the distance from the center along the x-axis or the y-axis.

```
v = 4 * r - 1
v = clamp(v, 0, 1)

```

Where the clamp function can simply be implemented like this if you are not familiar with it.

```
clamp(x, low, high) {
    if (x < low) {
        x = low;
    } else if (x > high) {
        x = high;
    }
    return x;
}

```

Now I assume negative value means the thumb-stick is going in the opposite direction. You never explained whether or not the radius can be negative, if it can't and you can tell the direction through some other means you can use the method above and put on the minus sign at the end if appropriate. If radius does become negative in the other direction, we need another mapping function, this time going from r=\[-0.50, -0.25\] to v=\[-1, 0\].

```
v = 4 * r + 1
v = clamp(v, -1, 0)

```

Unfortunately we can't use math expression for both ranges since both 0.25 and -0.25 are suppose to map to 0, the same value. However we can write a program function that combines both of the above for you. This does assume r goes from -1 to 1.

```
float mapRtoV(float r) {
    int v;
    if (r > 0) {
        v = 4 * r - 1
        v = clamp(v, 0, 1)
    } else if (r < 0) {
        v = 4 * r + 1
        v = clamp(v, -1, 0)
    }
    return v;
}

```

If your want values other than 0.25 and 0.50, here is a general function. Where low and high would be low=0.25 and high=0.5.

```
float mapRtoV(float r) {
    int v;
    if (r > 0) {
        v = (x - low) / (high - low)
        v = clamp(v, 0, 1)
    } else if (r < 0) {
        v = (x + high) / (high - low) - 1
        v = clamp(v, -1, 0)
    }
    return v;
}

```

# Answer
> 0 votes
This is how I would do it:

```
in = <2D input vector with [-1;1] value range>
map_min = 0.25;
map_max = 0.5;

l = length( in );
n = l > 0 ? in / l : vec2(0,0); // normalized input vector
// assuming max != min so division by 0 cannot happen
rl = ( l - map_min ) / ( map_max - map_min ); // remapped length
if( rl > 1 ) rl = 1;
if( rl < 0 ) rl = 0;
out = n * rl; // the corrected 2D input vector

```

---
Tags: mathematics, joystick
---


title: Change running tween speed

text:
# Question
Title: Change running tween speed
I have words inside a tween and I need to slow down a tween that is already running and I am using updateTweenData to do so. All running tweens are in an array.

updateTweenData works, but the problem is, when I set the slower speed, words become closer together and when I set the normal speed, words space out.

Here's a jsfiddle that demonstrates the problem.
Just click slower/faster buttons and notice how words behave.

I want just the speed to change and everything else to remain the same.
How can I achieve this?

Best regards.

# Answer
If the objects cover the same distance (400px) in 40 or in 80 seconds, it's going to have an impact on the spacing if the objects start with a fixed delay of 2 seconds (values taken from your jsfiddle).

First of all, you should incorporate the delay into the tween itself (use the `delay` property). Then, instead of using different durations for the tweens, use the `timeScale` property to speed-up or slow-down your tweens.

As an additional measure you'll probably also want to ensure that your tweens use linear easing.

**Update:** Here's an updated jsfiddle that incorporates what I outlined in my answer.
> 3 votes

---
Tags: phaser
---


# Question
Title: Making isKinematic false when OnCollisionEnter()?
I have an issue with my script, I want to make rb.isKinematic go from true to false when collision is detected. With this script, nothing happens when a supposed collision is happening which means that rb.Kinematic = false does not work... The problem is that collision CANNOT be detected in the first place because rb.isKinematic is initially true (in my other script)! I checked this using Debug.Log to detect collisions. How can I fix this problem?

```
string lastTagCollided = "";
public Rigidbody rb;

void OnCollisionEnter(Collision col)
{
    if(col.gameObject.tag == "Pentagon" && lastTagCollided == "Pyramid")
    {
    rb = GetComponent<Rigidbody>();
    rb.isKinematic = false;
    transform.DetachChildren();
    Destroy (GameObject.FindWithTag("Sphere"));
    }

if(col.gameObject.tag == "Pyramid" && lastTagCollided == "Pentagon")
{
    rb = GetComponent<Rigidbody>();
    rb.isKinematic = false;
    transform.DetachChildren();
    Destroy (GameObject.FindWithTag("Sphere"));
}

lastTagCollided = col.gameObject.tag;
}

```

My other script if you are curious:

```
void OnCollisionEnter(Collision col)
{
if (col.gameObject.tag == "Pyramid" || col.gameObject.tag == "Pentagon")
    {
        rb = GetComponent<Rigidbody>();
        rb.isKinematic = true;
        gameObject.transform.SetParent (col.gameObject.transform);
    }
}

```

# Answer
```
using UnityEngine;
using System.Collections;

public class CollisionDestroyer: MonoBehaviour {
    public AudioClip clip;
    public GameObject Bullet;

    // Use this for initialization
    void OnCollisionEnter(Collision theCollision){
        if(theCollision.gameObject.tag == "Bullet"){
            AudioSource.PlayClipAtPoint(clip, Vector3.zero, 1.0f);
            Bullet.GetComponent<Rigidbody>().isKinematic = true;
            Bullet.GetComponent<Rigidbody>().useGravity = false;
            Bullet.GetComponent<Collider>().isTrigger = false;
        }
    }
}

```
> 0 votes

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


# Question
Title: How to check for every n value interval, but not exactly n
Let's say I have a game where the player earns `n` number of points when they pick up an item; the value of `n` differs depending on what they picked up. When they pick up an item, a method gets called that adds `n` value to their current total score.

Pseudo code:

```
void tallyScore(int scoreToAdd) {
   PlayerScore += scoreToAdd;
}

```

I want to give the player an extra life every time they reach `y` total points. Let's say `200`, for now.

Pseudo code:

```
void tallyScore(int scoreToAdd) {
   PlayerScore += scoreToAdd;
   if (PlayerScore % 200 == 0) {
      GivePlayerExtraLife();
   }
}

```

The problem with the modulus approach is that if `PlayerScore` is currently `190`, and we call `tallyScore(11)`, the modulus condition will fail, but I still want to give the player an extra life because they've passed 200 points. If we were to call `tallyScore(2)` again, I wouldn't want to give them an extra life that time becasue we already did when we called `tallyScore(11)` previously.

What's a good way to check that `PlayerScore` has passed an interval of 200 points?

To reiterate, as the game went on, and `PlayerScore` becomes `395`, I call `tallyScore(8)`, I would then want to give the player another extra life since they earned another `200` points.

# Answer
> 5 votes
check pre and post status

```
void tallyScore(int scoreToAdd) {
   prec = PlayerScore / 200; //int division
   PlayerScore += scoreToAdd;
   post = PlayerScore / 200; //int division
   if (post  > prec) {
      GivePlayerExtraLife();
   }
}

```

Edit

If scoreToAdd \> 200,

post - prec

gives the number of lives to add. If scoreToAdd can be less than O , post - prec works fine to eventualy subtract extra lives.

# Answer
> 3 votes
Here is a variation of dnk drone.vs.drones answer that will add more than one life if `scoreToAdd` causes `PlayerScore` to break more than one 200 point increment.

```
void tallyScore(int scoreToAdd) {
   lifesGained = PlayerScore / 200; //int division
   PlayerScore += scoreToAdd;
   lifesToHaveGained = PlayerScore / 200; //int division
   while (lifesToHaveGained > lifesGained) {
      GivePlayerExtraLife();
      lifesGained++;
   }
}

```

# Answer
> 1 votes
You'll have to track how many one-ups the player has earned. This is assuming the players score can only go up. Also assuming one-ups are gained every 200 points forever.

```
int oneUpsEarned = 0; //Somewhere.

void tallyScore(int scoreToAdd){
 PlayerScore += scoreToAdd;
 if(PlayerScore > 200 * oneUpsEarned){
  GivePlayerExtraLife();
  oneUpsEarned++;
 }
}

```

If the player loses their 200 points when they get their one-up (like coins in Mario), you don't even have to track the number of one-ups earned.

```
void tallyScore(int scoreToAdd){
 PlayerScore += scoreToAdd;
 if(PlayerScore > 200){
  GivePlayerExtraLife();
  PlayerScore -= 200;
 }
}

```

---
Tags: unity
---


# Question
Title: How can i fix "get_transform can only be called from the main thread" error in my code?
Here's my code:

```
var forward = transform.TransformDirection(Vector3.forward);
var input = Input.GetAxis("Vertical");
function Update(){
transform.position += forward * input * Time.deltaTime;
transform.Rotate( 0 , Input.GetAxis("Horizontal") * 45 * Time.deltaTime , 0 );
}

```

I keep getting this error:

```
 get_transform  can only be called from the main thread.
 Constructors and field initializers will be executed from the loading thread when loading a scene.
 Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.

```

# Answer
> 1 votes
Don't referance GameObjects or Transforms (or components etc.) in initialization. Because Unity needs to prepare itself before you can access that objects to assign them to variables.

That is why we have an **Awake()** function, main purpose of **Awake()** function is field initialization before any **Start()** calls.

# Answer
> 0 votes
Like the error message tells you, the method you're using to assign a value to `forward` is being called in the loading thread because it's initializing the public field `forward`. It needs to be run during the game's main thread, so you need to move it.

```
function update() {
    var forward = transform.TransformDirection(Vector3.forward);
    var input = Input.GetAxis("Vertical");
    transform.position += forward * input * Time.deltaTime;
    transform.Rotate( 0 , Input.GetAxis("Horizontal") * 45 * Time.deltaTime , 0 );
}

```

---
Tags: javascript, unity
---


# Question
Title: Unity 3D: How to stop/reset 2D sprite animation after releasing key?
Im following a tutorial to create animations with a 2D sprite character. But i put in my own. Which has 8 animation positions. For some reason when my guy walks around,then stop, the walkings animation continues to play out then resets to idles.

I need the animation to reset as soon as i release the key.

Im using Animator if you are wondering.

EDITED: Original video with all the keys for each animations. Youtube video

Second video with only 2 keys per animation, it was a test. Second Video Here

Code Snipet!

```
using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour {

public float speed;

private Animator _animator;
private Rigidbody2D _rigidbody2D;

// Use this for initialization
void Start () {
    _animator = GetComponent <Animator>();
    _rigidbody2D = GetComponent <Rigidbody2D>();
}

// Update is called once per frame
void Update () {
    CheckDirection();
}

void CheckDirection(){
    if (Input.GetKey (KeyCode.A))
    {
        WalkAnimation(-1,0,true);
    }
    else if (Input.GetKey (KeyCode.D))
    {
        WalkAnimation(1,0,true);
    }
    else if (Input.GetKey (KeyCode.W))
    {
        WalkAnimation(0,1,true);
    }
    else if (Input.GetKey (KeyCode.S))
    {
        WalkAnimation(0,-1,true);
    }
    else
    {
        _animator.SetBool("Walking", false);
    }
}

void FixedUpdate (){
    Move();
}

void Move(){
    float dirX = _animator.GetFloat("VelX");
    float dirY = _animator.GetFloat("VelY");
    bool walking = _animator.GetBool("Walking");

    if (walking)
    {
        _rigidbody2D.velocity = new Vector2(dirX,dirY) * speed;
    }
    else
    {
        _rigidbody2D.velocity = Vector2.zero;
    }
}

void WalkAnimation (float x, float y, bool walking){
    _animator.SetFloat("VelX", x);
    _animator.SetFloat("VelY", y);
    _animator.SetBool("Walking", walking);
}

}

```

# Answer
> 2 votes
If you want your transition to have immediate effect you need to make sure that **Has Exit Time** is not checked in your transition.

Has Exit Time determines whether the transition’s condition can take effect at any time, or only during the state’s exit time.

http://docs.unity3d.com/Manual/class-Transition.html

# Answer
> 0 votes
I suppose you use Animation class. According to this page, calling

```
animation.Stop("%%animationName%%");

```

will stop animation.

---
Tags: unity, 2d, animation, sprites
---


# Question
Title: Filling a 2D polygone with N points more or less equally distanced
Following challenge: having any number of connected 2D faces forming virtually a polygone and filling the polygone with a variable number of points equally distanced to each other.

So here is a sample 2D object with any number of faces, all connected to each other, forming virtually a polygone:

Here is what I would like to calculate (in JavaScript or Python or pseudo): a variable number of points inside the faces, equally distanced to each other.

Some notes:

The points distance to each other doesn't need to be 100% the equal. Prioritized points are at the borders of the faces I should be able to define the targeted number of points, but it doesn't need to be exactly that number of points, can be more or less. Any ideas how to approach?

# Answer
> 1 votes
You probably want Lloyd's Algorithm. You'd confine the search space to the area contained within the original polygon, but would perform the iterations normally otherwise.

---
Tags: waypoints
---


# Question
Title: How do I instantiate a prefab to a specific coordinate?
I have a prefab called ‘road’. How can I instantiate it (using C#) such that it appears initially at coordinates `(5, 5, 5)`?

# Answer
> 7 votes
If you put the prefab into a directory called `Resources` inside your `Assets` directory, you'll be able to use the `Resources` class and its `load` functionality. This will load a prefab up as a `GameObject`, which can then be instantiated.

For example:

```
GameObject myRoadInstance = Instantiate(Resources.Load("road")) as GameObject;

```

Will create a instance of your "road" prefab in the game world.

You can either set its position by modifying its transform, or you can use the alternate version of `Instantiate` to specify a position.

```
GameObject myRoadInstance =
            Instantiate(Resources.Load("road"),
            new Vector3(5, 5, 5),
            Quaternion.identity) as GameObject;

```

# Answer
> 1 votes
The Unity Manual contains an example:

```
public class ExampleClass : MonoBehaviour {
    public Transform prefab;
    void Start() {
        for (int i = 0; i < 10; i++) {
            Instantiate(prefab, new Vector3(i * 2.0F, 0, 0), Quaternion.identity);
        }
    }
}

```

Note the vector3 passed as the second parameter and the quaternion as the third.

# Answer
> 0 votes
```
Vector3 position = new Vector3(5, 5, 5);

GameObject newGameObject = Instantiate(GameObjectToInstantiate);

newGameObject.transform.position = position;

```

You will always need to know what your going to instantiate, but from there you just call Instantiate as a function and load it into a new gameObject. You have to position it separately.

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


title: Unity3D - post-process unwanted on UI

text:
# Question
Title: Unity3D - post-process unwanted on UI
I have scene rendered with a single camera using target texture (a). Second camera is used to render UI and using same target texture (a) as the first one. Third camera takes target texture (a), depth texture and apply post proces. Result is rendered to the screen.

How can I apply postprocess only to the output elements that are not UI?

# Answer
> 1 votes
Simple, but not very "efficient" solution. First camera will have post-process effect attached. I apply it to the render target texture (a). Now I use the same path as before.

Problem is, that I double some calculations and I process twice many pixels.

---
Tags: unity, post-processing
---