# Question
Title: How do AI agents access information about their environment?
This might be kind of a trivial question, but I am having trouble understanding this. Would very much appreciate your help.

**In game development using object oriented design, I want to understand how AI-agents access the information they need from the game world in order to perform their actions.**

As we all know, in games very often AI agents need to 'perceive their environment' and act according to what is happening around them. For example, an agent might be programmed to chase the player if he/she gets close enough, avoid obstacles while moving (using the Obstacle Avoidance steering behavior), etc.

**My problem is I'm not sure how to do that. How can an AI agent access the information it needs about the game world?**

One possible approach is that **the agents simply request the information they need directly from the game world.**

There's a class called GameWorld. It handles important game logic (game loop, collision detection, etc), and also holds references to all of the entities in the game.

I could make this class a Singleton. When an agent needs information from the game world, it simply gets it directly from the GameWorld instance.

For example, an agent might be programmed to `Seek` the player when he/she is close. In order to do this the agent has to get the player's position. So it can simply request it directly: `GameWorld.instance().getPlayerPosition()`.

An agent could also just get the list of all the entities in the game, and analyze it for it's needs (to figure out what entities are close by , or anything else): `GameWorld.instance().getEntityList()`

This is the simplest approach: agents contact the GameWorld class directly and get the information they need. **However, this is the only approach I know. is there a better one?**

How would an experienced game developer design this? Is the "get a list of all the entities and look for whatever you need" approach naive? **What approaches and mechanisms are there to allow AI agents to access the information they need in order to perform their actions?**

# Answer
What you describe is a classic "pull" model of querying the world. Most of the time, this works pretty well, especially for games with basic AI (which is most). However, there are a couple of points you should consider that **might** be downsides:

* You probably want to double buffer. See game programming patterns on the subject. By always requesting the data directly from the world, you can get weird race conditions in which the outcome is dependent on which order the AI is called. Whether this is important to your game is for you to determine. One possible outcome is that it biases the game to whoever goes "first" or "last," making multiplayer unfair.
* It can often be much more efficient to batch requests, especially to certain data structures. Here you might make every AI agent that wants to search for obstacles create a "query object" and register that with a central obstacle singleton. Then, before the main AI loop, all queries are run against the data structure, which keeps the obstacle data structure more in cache. Then during the AI part, each agent processes it's query results, but isn't allowed to make any more directly. At the end of the frame, the AI objects update the queries with their new location, or add or remove them. This is similar to data oriented design.

Note that this basically does double buffering by storing the result of the queries in a buffer. It also requires you to anticipate whether you need to do a query the frame before. This is a "push" model, because the agents declare what kind of updates they are interested in (by making a corresponding query object), and these updates are pushed to them. Note you can also have the query object contain a callback, rather than storing all the results for a frame.
* Finally, you probably want to use interfaces or components for your searchable objects rather than inheritance, which is well documented elsewhere. Iterating over a list of `Entities` checking `instanceOf` is probably a recipe for pretty fragile code, the minute you want both `StaticObject` and `MovingObject` to be `Healable`. (unless `instanceOf` works for interfaces in your language of choice.)
> 5 votes

# Answer
AI being costly, performance is often the driving factor in architecture.

To ease your concerns around data access models, let's consider a few different AI examples both in- and outside of the games industry, working from that which is furthest from human navigation to that which is most familiar to us.

(Each example assumes a single, global logic update.)

* **A\* shortest path** Each AI calculates the state of the map for pathfinding purposes. A\* requires that each AI already know the entire (local) environment in which it must pathfind, so we must hand it information about map obstacles and space (often a 2D boolean array). A\* is a specialised form of Dijkstra's Algorithm, a shortest path open graph search algorithm; such approaches return lists representing the path, and on each step, the AI simply selects the next node in this list to step to, till it reaches its goal or recalculation is required (e.g. due to a map obstacle change). Without this knowledge, no realistic shortest path may be found. A\* is why AIs in RTS games always know how to get from point A to point B -- if a path does exist. It will recalculate shortest path for every individual AI, because path validity is based on the position of those AIs that have moved (and potentially blocked certain paths) previously. The iterative process by which A\* calculates cell values during pathfinding is one of mathematical convergence. One could say the end result resembles a sense of smell mixed with a sense of sight, but in all it is somewhat alien to our mindset.
* **Collaborative diffusion** Also found in games, this is most closely resembled by a sense of smell, based on diffusion of gases and particulates. CD solves the problem of costly re-processing found in A\*: Instead, a single map state is stored, processed once per update for all AIs, and the results are then accessed by each AI in turn, for it to make its respective move. No longer is a single path (list of cells) returned by a search algorithm; rather, each AI will inspect the map after it has been processed, and move to whichever adjacent cell has the highest value. This is called *hill-climbing*. Nevertheless, the map processing phase must *already* have prior access to the map information, which here also contains the locations of all AI bodies. Hence, map references AIs, and then AIs reference the map.
* **Computer vision and raycasting + shortest path** In rover & drone robotics, this is becoming the norm to determine the extent of spaces which the robot navigates. This allows robots to construct a full volumetric model of their environment, just as we would by sight or even sound or touch (for the blind or deaf), which the robot may then reduce to a minimal topographical graph (a bit like a waypoint graph used in games with A\*), upon which shortest-path algorithms may then be applied. In this instance, while "vision" may provide a clue to the immediate environment, it still *results in* a graph search that ultimately provides the path-to-goal. This is close to human thought: In order to reach the kitchen from the bedroom, I must pass through the living room. The fact that I have already seen them and know their spaces and their portals, is what enables this calculated move. This is a graph topology, to which a shortest path algorithm is applied, albeit embedded in soft protein rather than hard silicon.

So you can see that the first two are reliant on already knowing the environment in it's entirety. This, for reasons of the cost of evaluating an environment from scratch, is common in games. Clearly, the last is most powerful. A robot equipped this way (or for example, a game AI that reads the depth buffer each frame) could navigate sufficiently in any environment without prior knowledge of it. As you probably guessed, it is also by far the most costly of the above three approaches, and in games we typically cannot afford to do this on a per-AI basis. Of course, it is far less costly in 2D than 3D.

**Architectural points**

It becomes clear above that we can't assume just one correct data access pattern for AI; the choice depends on what you're trying to achieve. Accessing the `GameWorld` class directly is absolutely standard: it simply provides you with world information. Essentially it is your data model, and that's what data models are for. Singleton is fine for this.

> "get a list of all the entities and look for whatever you need"

Nothing naive about that, at all. The only thing that might be naive is performing more list iterations than you need to. In collision detection, we avoid this by using e.g. quadtrees to reduce the search space. Similar mechanisms can apply to AI. And if you can share the same loop to do multiple things, do so, because branches are costly.
> 5 votes

# Answer
Basically I'd have 2 ways of querying info.

1. when the AIState changes because you detected a collision or whatever cache a reference to whatever object is important. That way you know what reference you need. When have other systems having to run large searches every frame i'd recommend piggy backing off them so you don't have to perform multiple searches. So 'collision' detected with the zone that makes an enemy 'alert' send him a message / event that registers him with that object if he isn't already and change the game state to one that has him do his business based on being in that gamestate. You need an event of some type that tells you to make changes, I'd just pass a reference into whatever callback you use to give that information. This is more extensible then just having to deal with the player. Maybe you want an enemy to pursue another enemy or some other object. This way you only need to change whatever tag you identify it by.
2. With that information you will then perform a query to a path finding system that uses A\* or some other algorithm to give you a path or you can use it with some steering behaviour. Maybe a combination of both or whatever. Basically with the transform of both you should be able to query your node system or navmesh and have it give you a path. Your gameworld likely has many things other then pathfinding. I'd submit your query to pathfinding only. Also batching these things is probably best if you have many queries because this can get pretty intensive and batching will help performance.

```
Transform* targetTransform = nullptr;
EnemyAIState  AIState = EnemyAIState::Idle;
void OnTriggerEnter(GameObject* go)
{
   if(go->hasTag(TAG_PLAYER))
   {
   //Cache important information that will be needed during pursuit
   targetTransform = go->getComponent<Transform>();
   AIState = EnemyAIState::Pursue;
   }
}

void Update()
{
   switch(AIState)
   {
      case EnemyAIState::Pursue:
       //Find position to move to
       Vector3 nextNode = PathSystem::Seek(
                          transform->position,targetTransform->position);
       /*Update the position towards the target by whatever speed the unit moves
         Depending on how robust your path system is you might want to raycast
         against obstacles it can't take into account or might clip the path.*/
        transform->Move((nextNode - transform->position).unitVector()*speed*Time::deltaTime());
        break;
    }
 }

```
> 2 votes

---
Tags: architecture, ai, oop
---


# Question
Title: bug in webgl phong shader: lighting rotates with object
I'm working on a simple phong shader in webgl, and I think I'm getting close but something is still wrong. Dead give away: if I have a billboard and have it roll (so it spins like a wheel), the part of the billboard that is lit up spins with it :(. This confuses me, because it seems like a problem with the model matrix, but the transform makes all the positions & rotations correct, and lighting math is done entirely in world-coordinates , just the lighting wrong. Ditto with the view matrix, I can move around and look freely and everything is located in its proper place, just lit wrong.

Here are my shaders (minus the definitions for space, and with the lighting in the model matrix moved into GPU for clarity) {if you prefer reading in github: https://github.com/nickgeorge/quantum/blob/master/index.html#L41}

```
<script id="fragment-shader" type="x-shader/x-fragment">
  void main(void) {
    vec3 lightWeighting;
    if (!uUseLighting) {
      lightWeighting = vec3(1.0, 1.0, 1.0);
    } else {
      vec3 lightDirection = normalize(vLightPosition.xyz - vPosition.xyz);

      float directionalLightWeighting = max(0.0, dot(
          normalize(vTransformedNormal),
          lightDirection));
      lightWeighting = uAmbientColor + uPointLightingColor * directionalLightWeighting;
    }

    vec4 fragmentColor;
    if (uUseTexture) {
      fragmentColor = texture2D(uSampler,
          vec2(vTextureCoord.s, vTextureCoord.t));
    } else {
      fragmentColor = uColor;
    }
    gl_FragColor = vec4(fragmentColor.rgb * lightWeighting, fragmentColor.a);
  }
</script>

<script id="vertex-shader" type="x-shader/x-vertex">
  void main(void) {
    vPosition = uModelMatrix * vec4(aVertexPosition, 1.0);

    // TODO: Move back to CPU
    vLightPosition = uModelMatrix * vec4(uPointLightingLocation, 1.0);

    gl_Position = uPerspectiveMatrix * uViewMatrix * vPosition;
    vTextureCoord = aTextureCoord;
    vTransformedNormal = normalize(uNormalMatrix * aVertexNormal);
  }
</script>

```

Thanks a lot, and let me know if there's anything else useful to add.

# Answer
The problem with the code is that you are transforming the light with the model matrix, that is the position and orientation of the object you are rendering.
> 2 votes

---
Tags: shaders, webgl
---


# Question
Title: Make openGL program only update every 1/60 seconds
I'm learning C++ and openGL and have this program as a result from tutorials and playing around. The problem is that the main loop is running at "full speed", making the program unnecessarily cpu intensive. I have managed to make it only perform rendering every 16.7 ms or so, but the outside loop that is waiting to render still is iterating as fast as my computer can handle.

This is the full main.cpp: http://pastebin.com/KaCW7wZw

This is the main loop at line 95:

```
while (!terminate) {
    if (SDL_GetTicks() >= time_start + frame_rate)
    {
        time_start = SDL_GetTicks();
        while (SDL_PollEvent(&event))
        {
            if (event.type == SDL_QUIT) {
                terminate = true;
                break;
            }
        }

        glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        renderLoop(entities, &counter);
        SDL_GL_SwapWindow(m_window);;
        counter += 1.0f;
    }
}

```

I've tried googling and haven't found anything concrete (obviously), except that using some kind of sleep is bad design for these loops.

So how can I alter this to slow the whole thing down, and avoid having 100% cpu usage for a program that's not doing much at the moment?

# Answer
> 5 votes
Here's my game loop:

```
        double              lastTime        = game->GetGameTime().TotalTime();
        double              timeBehind      = 0.0;
        while( !end )
        {
            // Update the game time.
            game->GetGameTime().Update(); // Update game time values.
            flagEnd = game->HasEnded();   // Ignore this.
            timeBehind += game->GetGameTime().TotalTime() - lastTime; // Here we figure out how many updates behind we are. Update will not be called until this is a large enough value( the timestep we want. )
            lastTime = game->GetGameTime().TotalTime(); // Keep track of the last frame's time.

            // So, while we're behind more than one timestep, we'll update. So, even if drawing takes
            // about half a second, we update here until e have caught up. This way we'll never have
            // slow updates because of drawing. No matter how slow the game draws, it'll always update based on time.
            while( timeBehind >= targetTimeStep )
            {
                // Update the game.
                game->Update();
                // Every time we update, we subtract a timestep from the amount we are behind.
                timeBehind -= targetTimeStep;
            }

                // Draw whether we update or not. ( You can remove all draws where there was no update, since nothing should be different. ) You could sleep here.
            game->Draw();
                // Swap the buffers.
            SwapInstanceBuffers();
        }

```

Here I have targetTimeStep at 1000 / 60. This is 60fps. The HUGE advantage of this game loop is that updates will be consistent. So, all your objects can move based on time, rather than frames. No matter how slow your game draws, your updates will still be consistent.

Here is where I learnt this from: http://gameprogrammingpatterns.com/game-loop.html It's a great article that's certainly worth your time to read.

# Answer
> 2 votes
The above answers are basically correct, but I will take that different angle, you don't need to do anything. The moment you start actually rendering something you will be happy when your code actually runs at 60fps.

All my "real" games run with with a main loop that is unbounded. It keeps the entire thing responsive and I need to invest large amount of effort to get it to render at 60fps. The only thing I do is ensure that any logic is frame rate independent. (Though in recent years allot finds itself in other threads.)

But if you must you can implement a "yield", this basically works well with `SDL_Delay(0)`. But this may have adverse effects, since that may be something up to 10 ms.

# Answer
> 0 votes
You could enable double buffering which would enable vsync (limit your framerate to whatever refresh rate your monitor supports (usually 60Hz, so 60fps)).

```
SDL_SetVideoMode(yourWidth, yourHeight, yourBpp, SDL_HWSURFACE  | SDL_DOUBLEBUF | SDL_FULLSCREEN);

```

---
Tags: opengl, c++, sdl, game-loop
---


# Question
Title: Should my GLSL Shader object/wrapper encapsulate loading/setting a VertexArrayObject?
I am working on a 2D game in C++, with a simple rendering layer over OpenGL.

I have a wrapper for GLSL shaders and shader programs, these wrappers encapsulate shader objects into C++ classes and automatically handle loading/compiling/linking and using shader programs.

VertexArrayObjects, it seems to me, are basically a collection of configuration settings to use with a particular ShaderProgram.

My question is: Should I encapsulate VAO's within my ShaderProgram objects, or within the Sprite objects? Does a VAO change on a per-shader basis or do I need a new VAO for every type of drawable object? If the latter, do I need one VAO to draw all Sprites (each containing 4 vertices, a position/orientation etc), or one VAO per sprite object in the game?

# Answer
> 3 votes
No, you shouldn't attach the VAO to a Shader Program. The VAO has to be linked with a Vertex Buffer, which makes it somewhat not shareable. You can only share it to the same extent you would share a Vertex Buffer. Whereas a Shader Program is highly shareable (you may be able to render all objets with the same program).

The purpose of the VAO is to reduce some API overhead when setting a Vertex Buffer and Vertex Format, so you can think of it as a container for a Vertex Buffer and its state.

It is up to you how you want to lay it out on code, but my suggestion would be having 3 distinct classes: `VertexBuffer`, `VertexFormat` and `VAO`.

Give a unique VAO to each mesh/model and then attach shared VertexBuffers and VertexFormats to them.

---
Tags: opengl, c++, 2d, vao
---


title: 2D physics rotation w/ XNA

text:
# Question
Title: 2D physics rotation w/ XNA
I'm creating a simple game with space ships made of blocks that are all the same size. After having looked at this: Calculating the rotational force of a 2D sprite I have created the following code for applying a force

```
public void AddForceAtBlock(Vector2 force, Block block)
    {
        float mass = 1F*blocks.Count;
        this.velocity.X += force.X/mass;
        this.velocity.Y += force.Y/mass;
        Vector2 momentArm = GetGameWorldCoordinates(block) - centerOfMass;
        Vector2 parallelComponent = momentArm * (Vector2.Dot(force, momentArm) / Vector2.Dot(momentArm, momentArm));
        Vector2 angularForce = force - parallelComponent;
        Vector2 torque = angularForce * momentArm.Length();
        float momentOfInertia = 10000F*blocks.Count;
        float angularAcceleration = torque.Length()/momentOfInertia;
        this.rotationalVelocity += angularAcceleration;
    }

```

However this code is unable to create negative rotational acceleration so I think I did it wrong. Will someone point out to me what's wrong here?

All blocks are 50 units wide, this is the output for a 3 block ship like so: TST where T are thrusters and S is a dull forceless block. Floats are slightly imprecise as is shown in the debug log but it shouldn't matter for videogames.

Right Thruster Stop 1: force = (0, 0.951147) momentArm = (50,0) parallelComponent = (0,0) torque= (0, 47.55) angularAcceleration = 0.001585 centerOfMass = (0,0)

Left Thruster Stop 2: force = (0, 0.951147) momentArm = (-50, 0) parallelComponent = (-8.315191E-08, 7.269371E-15) torque = (4.157595E-06, 47.55735) angularAcceleration = 0.001585245 centerOfMass = (0,0)

As you can see the equation seems to be working but it fails to make the right thruster's angular acceleration negative.

# Answer
The path of fewest changes involves keeping your rotation sign as another variable in the function scope. You can acquire it by taking the cross product of the force and your moment arm.

After your `momentArm` assignment, add the following:

```
Vector3 rotation = Vector3.Cross(
    new Vector3(momentArm, 0),  // the Vector3(Vector2 v, float z) constructor
    new Vector3(force, 0));
float rotationDirection = Math.Sign(rotation.Z);

```

Then modify the last line of your method:

```
this.rotationalVelocity += angularAcceleration * rotationDirection;

```

---

From Wikipedia's Cross product article:
> 1 votes

---
Tags: xna, c#, physics, monogame
---


# Question
Title: How to add isometric (rts-alike) perspective and scolling in unity?
I want to develop some RTS/simulation game. Therefore I need a camera perspective like one knows it from Anno 1602 - 1404, as well as the camera scrolling. I think this is called isometric perspective (and scrolling).

But I honestly have no clue how to manage this. I tried some things I found on google, but they were not satisfying.

Can you give me some good tutorials or advice for managing this?

Thanks in advance

# Answer
> 2 votes
I don't always play RTSs, but, when I do, I fail miserably. As such, I can offer general implementation ideas based on my understanding of RTS camera movement/mechanics.

The isometric perspective could be fairly easily achieved by setting your camera to orthographic and finding a rotation that looks down at an angle that "feels right" for your game.

Scrolling around the world in this style is just movement on the world's XZ plane; you would not change its height at all.

# Answer
> 1 votes
Orthographic projection can be done in advance, making it simply a 2d game with a tileset constructed either: from a 3d model with orthographic projection on (in blender you can set this in the camera's object data properties window), or by manually drawing the pixels.

This way you bypass the need for projecting at runtime, which will make the game significantly faster to run.

---
Tags: unity, camera, rts, simulations
---


title: Managing and rendering bullets

text:
# Question
Title: Managing and rendering bullets
I'm developing something similar to Galaga and I'm not entirely sure how to "manage" the bullets i.e. what data structures/algorithms/approaches to use when rendering them on the screen. Let's forget collision detection for now. The way I'm thinking of implementing this is:

1. When the application starts, create an array of bullets. Make sure this is at least as big as the total number of bullets you want to have on the screen at any given time. Initialize all the bullets to some default settings. Also create a list of the bullets that are on the screen at any time. Obviously this will be empty initially.
2. When the user shoots, get an element of the array and add it to a list of bullets that are currently rendered.
3. When drawing, iterate the list of bullets and render each of them. If a bullet gets out of the screen (say `y > 1.0f`) then remove it from the list and reset it to default position.

Is this a sensible approach to the problem? Are there alternatives I should consider?

P.S. This question is language/framework (etc) agnostic, but if you think it makes a difference, I'm using OpenGL ES 2 on Android.

# Answer
There are two problems with storing game objects in arrays.

1. You set a limit on how many game objects you can have. Sure, you could set some astronomically high amount which you are sure you will never reach, but then your data structure will always need the maximum amount of memory.
2. When game objects are removed, you get holes in the array.

A better data structure would, for example, be a linked list. A linked list has the advantage that it can shrink and grow dynamically. Its maximum size is only limited by RAM, it never takes more space than necessary and you can remove items from the middle of it without causing holes in it.

When a new object is created, you append it to the end of the list. When you iterate the objects and notice that the object needs to be removed (leaves screen, hits a target or whatever), you can just remove it from the list by linking the predecessor to the next element and freeing the current node.

The downside is that it is less efficient than an array. It requires additional memory and the constant memory reallocation when you create and remove elements leads to memory fragmentation which can be detrimental to performance. But these issues are unlikely to be a problem in the case of a simple 2d shot-em-up.
> 2 votes

# Answer
The only suggestion I would make to your approach is to keep away from linked-lists. Try to always keep the bullets in arrays, they are far more efficient when it comes to CPU cache. For more info on the subject, read this excellent article on Data Locality.

So for item 1 of your list, when you create a new "alive" bullet and move it from the global pool to a live bullets set, make this set an array and copy the whole structure to it. This way you keep a sequential array of alive bullets that is going to be super fast to iterate and cache efficient. It may seem like a dumb thing to copy the whole structure into another array, but chances are that the gained cache efficiency will outweigh the copy cost.
> 1 votes

---
Tags: game-design, game-mechanics
---


# Question
Title: Preventing rapid inversions of boolean on Collision detection
I know this is both a strange question and a stupid question. But this is an issue I have dealt with in every single game I've made, and I have yet but to find a solution. I can't be the only one who's run into this problem. My google-fu must suck though, because I can't find any information on how to fix this.

Here's the situation:

* A dynamic object is moving in a certain direction.
* This dynamic object then hits a static object.
* This dynamic object now changes the direction, and heads the other way until it hits an object, and then it changes the direction once again. Kind of like paramecia movement, but not exactly. Seems simple enough.

Now here's the issue. I detect the collision, but I can simply inverse the velocity. Using OOP, I have my own class for this object, which performs all movement and actions. So, instead, I have a boolean in this class. A simple boolean that asks whether I'm moving left. If I am, my velocity is negative. I may also need to flip the sprite. If, however, the boolean is false, my velocity is positive. So, all is fine and dandy.

Now, here is where the common issue comes in. I detect collision, and inverse the boolean(`object.movesLeft != object.movesLeft`). This is performed EVERY time it detects a collision. The issue now comes in. I inverse the boolean and start to move it in the opposite direction; however, it is not quick enough, and before it gets moving, it still detects the collision, reversing the boolean once again, turning in back into its original value.

I have yet to find a good solution to this. I have found workarounds, but often times I still get this issue.

Currently, I am using Box2D for collision detection, so my flexibility for solutions are constrained. Box2D provides a method for when specific collisions are happening, and when the specific collisions end. I tried only changing the boolean when a collision ends, but there was a pretty big issue. It would only run when a collision ended, obviously. It didn't have to be the moving object that I'm trying to inverse, it could be any dynamic object. The obvious issue is that I need some kind of collision to end before the object will inverse the direction.

So anyways, this is the issue I have faced in even simple games such as pong, and really, really need to find a way to solve it. I can't be the only one of us who have run into this issue.

If anybody understands the issue I'm having, or has experienced it themselves, and has a solution, help would be greatly appreciated. Thanks in advance.

# Answer
> 0 votes
Alright, so I used another one of my workarounds. Hopefully this one is more stable than others I've used in the past. I'm using Box2D, so I have a custom class implementing a ContactListener so I can apply my own effects on collisions. I'm going to refer to the dynamic object I want to change the direction as a DObject. Alright, so first, I define a boolean for when I first detect the collision.

```
private boolean firstHitCollision = true;

```

It will initialized as true.

So, next, I handle when the collision is detected:

```
@Override
    public void beginContact(Contact contact) {
        Fixture fixtureA = contact.getFixtureA();
        Fixture fixtureB = contact.getFixtureB();

        if (fixtureB.getBody().getUserData().getClass() == DObject.class)
            handleDObjectCollisions(fixtureA, fixtureB);
    }

```

Now it will run this handleDObjectCollisions method while there is a collision with my DObject.

```
private void handleDObjectCollisions(Fixture fixtureA, Fixture fixtureB) {
        float[] sides = getSidesArray(fixtureA, fixtureB);

        if (collidesWithLeft(sides) | collidesWithRight(sides)) {
            DObject dObject = (DObject) fixtureB.getBody().getUserData();
            if(firstHitCollision) {
                dObject.moveLeft = !dObject.moveLeft;
                firstHitCollision = false;
            }
        }
    }

```

Above is the handleDObjectCollisions method. I check if my DObject collides with the left or right sides of another object. If its true, then I check make my DObject that is currently collided with another object. Next, I check if firstHitCollision is set to true. If it is, then I inverse the direction boolean and set firstHitCollision to false. So now the next time I run this, firstHitCollision will be set to false and the boolean won't be inverted again. So that all works fine, but now firstHitCollision will be false for the rest of the game, and the DObject won't be inverted again. Well, to solve this issue, I override the endContact method. As seen below, I check if the object that has ended collision is my DObject object. If it is, I need to set firstHitCollision back to true so the next time it collides with the side of an object, it can inverse the direction.

```
@Override
    public void endContact(Contact contact) {
        Fixture fixtureA = contact.getFixtureA();
        Fixture fixtureB = contact.getFixtureB();
        if(fixtureB.getBody().getUserData().getClass() == DObject.class)
            firstHitCollision = true;
    }

```

And there we go. No more sticking to walls, no more rapid inversions of the boolean. However, I feel like this is a workaround. Now I'm wasting more memory with these extra if statements, and it is susceptible to bugs. But, I digress. That's how I will be handling this issue in this project.

Edit: If anybody cares, here's the getSidesArray method, along with the methods to check if it collides with a specific side. The getSidesArray method only gets a rectangle.

```
// 0-3:FixtureA, 4-7:FixtureB
// Top, Left, Bottom, Right
private float[] getSidesArray(Fixture fixtureA, Fixture fixtureB) {
        float[] sidesArray = new float[8];

        // Collided-with object
        sidesArray[0] = fixtureA.getBody().getPosition().y
                + Constants.BLOCK_SIZE / Constants.METER_FACTOR;
        sidesArray[1] = fixtureA.getBody().getPosition().x;
        sidesArray[2] = fixtureA.getBody().getPosition().y;
        sidesArray[3] = fixtureA.getBody().getPosition().x
                + Constants.BLOCK_SIZE / Constants.METER_FACTOR;

        // Character object
        sidesArray[4] = fixtureB.getBody().getPosition().y
                + Constants.CHARACTER_HEIGHT / Constants.METER_FACTOR;
        sidesArray[5] = fixtureB.getBody().getPosition().x;
        sidesArray[6] = fixtureB.getBody().getPosition().y;
        sidesArray[7] = fixtureB.getBody().getPosition().x
                + Constants.CHARACTER_WIDTH / Constants.METER_FACTOR;

        return sidesArray;
    }

    private boolean collidesWithLeft(float[] sides) {
        if (sides[1] >= sides[7])
            return true;
        return false;
    }

    private boolean collidesWithRight(float[] sides) {
        if (sides[3] <= sides[5])
            return true;
        return false;
    }

    private boolean collidesWithBottom(float[] sides) {
        if (sides[2] >= sides[4])
            return true;
        return false;
    }

```

---
Tags: java, collision-detection, box2d
---


# Question
Title: What technical specifications should be set out for music?
I'm writing the music for a video game. At some point, I'm going to need to work with the programmers to determine the technical specifications for the audio files I'm going to hand over to them. What kinds of details are we going to need to talk about?

For example, a few questions I think we might need to work out are:

* What format should the audio files be in?
    + Uncompressed? Lossless? Compressed?
    + What's the balance between high-quality audio and small files sizes?
* How loud should the music be?
    + What should be the average volume level of each track?
    + What should be the loudest volume level?
* What should be the frequency distribution?
    + For example, should I make a point of writing music that doesn't have much bass so that low-pitched foley can be easily heard?

Are the questions I thought of important ones to ask? Are there any other questions we should discuss?

# Answer
If I understand correctly, you have two different questions in here:

1. What kind of technical (as in programming) considerations should be set out?
2. What kind of technical (as in audio engineering) considerations should be set out?

For both questions, your best bet is to ask the person in charge. For the first one, it could be the lead audio programmer, while for the second one it could be the audio director.

Now, I suppose that since you're asking this in here, you are on a small team with no such roles, and your programmer probably doesn't know what you're talking about, so I'm going to answer with some general guidelines that could work for most projects. But in any case, I wouldn't recommend making decisions on your own. Discuss with your other team members to reach a conclusion.

That said, let's first talk about some technical (programming) considerations.

* Usually, the format in which your audio files will be distributed is already determined by the platform or game engine you're using. If you're going to be doing multi-platform, it is likely that each platform will have completely independent resource directories, and the characteristics of audio files may be different for each platform.

For example, you may be required to turn in Ogg Vorbis files for Android, MP3 or AAC for iOS and WMA for Windows.

Sometimes, even the format is dependent on the purpose of each file. While iOS plays nice with MP3 and AAC files for any purpose, PlayStation Mobile requires MP3 for BGM, but only supports uncompressed PCM or Microsoft ADPCM.

Do ask your programmer what format must the files be in.
* Most of the times, the basic specifications for the files will already be defined, so make sure you ask your programmer about this. For example, BGM files are usually distributed in stereo, while SFX and voice files are usually distributed in mono (so they can be easily positioned inside the game)
* For bitrates and other parameters, once again, they are usually dependent on the engine or platform. If you have some freedom in here, consider that sound data is usually the biggest component of a game, and if the game is to be distributed via digital downloads, your programmer (and your customers) will thank you if you make the files as small as possible.

If you will be distributing on physical media, then the maximum distribution size is predetermined, and you will have to do some serious negotiations with the rest of the content creation team.
* Some games require your sounds (mostly BGM) to be loopable; other games require your sounds to have strict timing constraints (like rhythm games). Most lossy compression schemes will add padding silence at the beginning and end of the track which may break loops and strict timing. Discuss these issues with your programmer.

There are too many ways to compress audio, so what I recommend you is to output a master version of each sound file in uncompressed PCM at 44.1KHz 16 bit Stereo, and then use that file to create the actual files for each platform. (Optimally, you could create a transform script which can be applied to each file so you don't have to reconvert each file each time you make a small change in the master file).

Now, in terms of technical (as in audio engineering) considerations, your programmer will most likely don't care, so you will have some more freedom in this area. There are some things you can do though to make your programmer's life easier:

* All the sounds in the game should have normalized loudness. At the very least, all BGM files should have the same loudness between themselves, and all SFX files should have the same loudness between themselves. Don't make your programmer have to tweak the volumes inside the code.
* Playback code is very limited, and can usually only do linear amplification. Because of this, between high and low loudness, high might be preferred, as reducing volume during playback usually leads to better results than amplifying it. It's difficult to say what should be the exact loudness, but as a rule of thumb, the greater the overall peak-to-peak amplitude is, the better you're using the sampling range.

You might want to load other games and play their sounds at their maximum volume settings and compare your sounds with theirs.
* In terms of equalization, I would have to say this really depends on what other sounds your game will have. Apart from discussing this with the sound director, you might want to also take into consideration the playback hardware you will be using: while desktop computers may have a huge variety of playback hardware, handheld devices usually have very small speakers, and you may want to compensate for that. Arcade machines usually have much different requirements as well.
> 6 votes

# Answer
I differentiate between two situations, what I keep around during development and later (storage) and what I put in the final delivery.

For storage I use the highest quality possible, that is for audio some format that is lossless. As long as the compression is lossless it does not really matter; WAV or FLAC will do. I basically am OK with a 44.1 kHz / 16 bit recording and the volume should be "natural" as possible, so basically original recording with minimal gain if needed. (If you really want to you can go with 96 kHz or 192 kHz recordings.) Size does not really matter, hard disks are not that expensive and you can always throw more at that problem. The main rationale is that you can always compress into a lossy format from lossless one, but once you only have lossy files, you can never move to higher quality.

For delivery that is totally a different story. Here you need to make some hard choices about quality vs. space vs. speed. For small SFX I use WAV files because they load the fastest. Music on the other hand size does matter, so I normally use MP3 with variable bitrate. You can get away with 64 kbps files, but that is a matter of taste. The sounds should basically be at their natural volume, though balanced against each other. The game engine will then do any adjustment as needed, especially if you are doing something like 3D sound.
> 2 votes

---
Tags: music
---


# Question
Title: What kind of projection is demonstrated in this screenshot?
I want to know what projection is used in the following game:

The game is Goodgame Empire.

# Answer
This is orthographic projection plain and simple. You can see this by the fact that all lines, especially the horizontal ones are perfectly parallel.

*Addendum:*

The comments are correct, this is isometric projection, which is a special case of the orthographic projection.
> 12 votes

# Answer
The diamonds of the grid measure 23 by 45. If this were isometric projection, they would be in ratio 1:sqrt(3). (That is 35.264… degrees above horizontal, *not* 45 as Nathan Reed suggested.) By taking arcsin(23/45), we find that this projection is 30.737… degrees above horizontal.
> 6 votes

---
Tags: 2d, graphics, projection
---


# Question
Title: How can I implement a "20 Questions" algorithm?
Ever since childhood, I've wondered how the *20Q* electronic game worked. You think of an object, thing, or animal (e.g. *potato* or *donkey*). The device then asks you a series of questions such as:

* Is it larger than a loaf of bread?
* Is it found outdoors?
* Is it used for recreation?

For each question, you can answer *yes*, *no*, *maybe*, or *unknown*. I always imagined it work with immense, nested conditionals (`if`-statements). However, I think that's an unlikely explanation because of its complexity for the programmer.

How would I implement such a system?

# Answer
I don't know how 20Q did it specifically, but there is plenty of information on how to implement a game of 20 questions.

There are lots of ways of solving this, but I'll describe one way. These games can implement some sort of decision tree. For an electronic game like 20Q, this tree would be precomputed and fairly easy to traverse. There are methods for using learning decision trees where the game can accept new objects at the end of it's questions if it's unable to guess what the user is asking.

When the questions are a series of yes or no answers, you end up with a binary tree. Each node is a question and the leaves are answers. When questions are answered with unknown or not sure, the child nodes can be combined and their questions asked in series to further cull the possible answers.

Basically this is the process:

1. Start with a full list of the objects. These can all start at equally likely, or they can be sorted by how likely the object was to be chosen in testing.
2. Start with the first question in the decision tree. Push it onto the question queue.
3. Ask the question on top of the queue.
4. Process response:
    1. Yes/No answers removes/adds a predetermined amount of probability from each answer based on the question.
    2. "Maybe" answer removes/adds a fraction of the predetermined amount of a "yes".
    3. "Unknow" does not change probabilities
5. An "Unknown" or "Maybe" response pushes both of the next nodes questions onto the question queue. A "Yes" or "No" response just adds the one respective yes/no node onto the question queue.
6. Go to step 3 until out of questions or probability of a single answer is beyond a predefined "certainty" threshold.
7. Provide most probable answer.

Generating the tree is probably the topic of another question. But basically it's choosing questions that split the answers as much as possible. Put the questions that divide the questions most equally near the beginning so that the most number of questions can be culled the fastest.
> 19 votes

# Answer
The simple answer is that the handheld game 20Q was created from the artificial intelligence that lives at http://20Q.net. At 20Q.net you can play different versions of the game of Twenty Questions, similar to the toy except that the game learns from every game played. The handheld toy uses the same neural network algorithms. The neural network picks the questions to ask as well as making guesses. This approach means that the A.I. will often guess correctly even if you answer a question differently from what the A.I. has been taught. Another advantage is that the game will ask questions differently every game even if you are thinking of the same thing.

The algorithms and the neural network of the classic english game (Animal, Vegetable, Mineral) was created in 1988 by Robin Burgener . . . me.

Thanks for asking.
> 17 votes

# Answer
I googled "20q code" and found this: http://mosaic.cnfolio.com/B142LCW2008A197

This version is only for animals but the actual 20 Questions probably has a similar algoritm.

**Here is a quick overview of the code I linked:**
There are several different answers hard coded into the program. Several TRUE or FALSE attributes are then assigned to them:

```
#define ANIMALS_LIST      "daddylonglegs bee penguin eagle giraffe octopus tiger elephant jellyfish bull \nparrot dolphin python crocodile cat leopard monkey zebra sheep rat \nowl spider frog polarbear snail tortoise rabbit salmon rhino fox"
#define MAMMALS                    "0 0 0 0 1 0 1 1 0 1 0 1 0 0 1 1 1 1 1 1 0 0 0 1 0 0 1 0 1 1"
#define FLYING_ANIMALS             "1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0"
#define WATER_ANIMALS              "0 0 1 0 0 1 0 0 1 0 0 1 0 1 0 0 0 0 0 0 0 0 1 1 0 1 0 1 1 0"
#define BEAK                       "0 0 1 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0"
...

```

As you can see a bee is not mammal but it does fly, etc.

There is an array for each group:

```
int   mammals[ TOTAL_ANIMALS ] = { 0 };
int   flying_animals[ TOTAL_ANIMALS ] = { 0 };
int   water_animals[ TOTAL_ANIMALS ] = { 0 };
...

```

When each question is asked:

```
  askUserQuestion( guesses, "\nQuestion %d: Is your animal a mammal? \n", mammals );

```

The program looks at the definition of the appropriate category and tracks which animal is most likely the one you are thinking of based on the TRUE or FALSE values and your inputed Yes or No answer to the question.

This is done in:

```
void askUserQuestion( int guessNumber, char* question, int* animalData );

```
> 7 votes

# Answer
It's not a massive decision tree or a bunch of hard-coded if/else statements. Robin Burgener, the inventor, completely documented his algorithm in his 2005 patent filing. It's ingeniously simple.
> 2 votes

---
Tags: ai
---


# Question
Title: How can I implement a dialogue where the words appear as if they were being typed?
I'm planning on putting a dialogue system into my game, I don't really work with surface so my way of implementing SDL\_Ttf is by turning it into a texture, in other words, every paragraph would be shown within the rect, is there a way to make the words appear as if they were being typed?

# Answer
> 8 votes
What you may wish to do in this case is check the timer when you `started` printing the text on the screen and decide on an `amount` of time that it will take to print each letter in the paragraph.

Then each frame check the `time` and print this portion of the text:

```
int charsToPrint = (time - started) / amount;
if (amount < originalText.length()){
    printedPortion = originalText.substr(0, charsToPrint);
else
    //DONE: you may wish to do something else here?
    printedPortion = originalText;

```

You will probably want to play a sound when each when each letter is added. You could also accomplish this with a timer or check `if (amount > lastAmount) playSomeSound()...`

---
Tags: c++, sdl
---


# Question
Title: Scrolling with SDL2 & Box2d - My Camera isn't keeping up with my player
I'm trying to get a game on the google play store before I'm 40 (long held dream to publish a game since the days of the speccy), I have just over a month to go so it's not looking good! Foolishly I decided to use SDL2 and Box2d to write the game, both technologies I have little experience in & to compound my misery I'm a noob at C++ so please bear with me if I've made a common error.

Basically I've managed to get a simple physics simulation up and running and have sorted applying my SDL textures to the box2d collision boxes, that all seems to be fine and dandy, where I've come a cropper is my player moves along a ground entity on the X axis,

I've managed to implement a scrolling background but it doesn't keep pace with the player, in which I mean the player moves across the screen instead of remaining central as I'd like him to and the background scrolls behind him. I've probably completely mis-interpreted how to manage my requirements and after days of searching for reference code I'm now at a bit of a loss.

Hopefully some kind soul can help me realise my dream! I've posted what code I think is relevant but if theres something missing I'll add it.

Player movements

```
// Get the position and angle of the player
playerPos = player.pl_body->GetPosition();
playerDeg = player.pl_body->GetAngle();
playerVel = player.pl_body->GetLinearVelocity();

float velChange = desiredVel - playerVel.x;
float impulse = player.pl_body->GetMass() * velChange; //disregard time factor
player.pl_body->ApplyLinearImpulse( b2Vec2(impulse,0), player.pl_body->GetWorldCenter(), true );

```

SDL2 rendering

```
//Render current frame using clips
SDL_Rect* playerCurrentClip = &playerClips[ plAnimFrame / 2 ];

// Render player texture to x & Y of player entity
gPlayerTexture.render (playerPos.x - player.PLAYER_WIDTH/2, playerPos.y - player.PLAYER_WIDTH/2, playerCurrentClip, playerDeg, NULL, flipType);

```

Camera setup

```
// Setup a surface for the camera area
SDL_Rect camera = {0, 0, SCREEN_WIDTH, SCREEN_HEIGHT};
// Render background texture
gBackgroundTexture.render (0, 0, &camera, NULL, NULL, flipType);

```

Camera scrolling

```
//Center the camera over the player
camera.x = (playerPos.x + player.PLAYER_WIDTH / 2 ) - SCREEN_WIDTH / 2;

 //Keep the camera in bounds
 if( camera.x < 0 )
 {
     camera.x = 0;
 }
 if( camera.x > LEVEL_WIDTH - camera.w )
 {
     camera.x = LEVEL_WIDTH - camera.w;
 }

```

# Answer
> 0 votes
From the code you posted:

```
// Render player texture to x & Y of player entity
gPlayerTexture.render (playerPos.x - player.PLAYER_WIDTH/2, playerPos.y - player.PLAYER_WIDTH/2, playerCurrentClip, playerDeg, NULL, flipType);

```

It appears you are not subtracting the camera.x from the player position.

```
// Render player texture to x & Y of player entity
gPlayerTexture.render (playerPos.x - player.PLAYER_WIDTH/2 -(( camera.x )), playerPos.y - player.PLAYER_WIDTH/2, playerCurrentClip, playerDeg, NULL, flipType);

```

---
Tags: c++, box2d, sdl, scrolling
---


# Question
Title: Wrapping each script with classes causes errors
The goal here is to change variables from another script. Thing is that they must be in classes, so for example I wrapped this code (which is from **PadControl.js**):

```
#pragma strict

public var ball : GameObject;
public var moveSpeed : float = 10;
public var rotationSpeed : float = 10;

function Update () {
    var padMove : float = Input.GetAxis("Horizontal");
    var padRotate : float = Input.GetAxis("Vertical");

    this.transform.position.x += padMove * moveSpeed * Time.deltaTime;
    this.transform.rotation.y += padRotate * rotationSpeed * Time.deltaTime;
}

function OnCollisionEnter(col : Collision){
    if(col.gameObject.name == "Ball"){
//      Debug.Log("SAY SOMETHING");
    }
}

```

like so:

```
#pragma strict

public class PadControl{
    public var ball : GameObject;
    public var moveSpeed : float = 10;
    public var rotationSpeed : float = 10;

    function Update () {
        var padMove : float = Input.GetAxis("Horizontal");
        var padRotate : float = Input.GetAxis("Vertical");

        this.transform.position.x += padMove * moveSpeed * Time.deltaTime;
        this.transform.rotation.y += padRotate * rotationSpeed * Time.deltaTime;
    }

    function OnCollisionEnter(col : Collision){
        if(col.gameObject.name == "Ball"){
    //      Debug.Log("SAY SOMETHING");
        }
    }
}

```

As stated in this tutorial coming from Unity's website (https://unity3d.com/learn/tutorials/modules/intermediate/scripting/statics)

But when I do it, this is the error:

> Assets/PadControl.js(12,22): BCE0019: 'transform' is not a member of 'PadControl'. Assets/PadControl.js(13,22): BCE0019: 'transform' is not a member of 'PadControl'.

And I really don't know what's actually going on and what should I do. Any suggestions?

# Answer
> 1 votes
You need to adjust the start of your class to this:

```
public class PadControl extends MonoBehaviour {

```

Without adding `MonoBehaviour`, the class is just a class that isn't seen as a Component, and doesn't inherit `transform`, `gameObject`, etc.

---
Tags: unity, javascript
---


# Question
Title: How to rotate vertices of 2D shape using a transform matrix?
I am making a top-down 2D game and am currently working on implementing improved collision using SAT. I programmed a Shape class with a Vector2 center that is its position in world space. On top of this is a list of Vector2's that act as the vertices of the shape and are defined as offsets in local space. The Shape class also has a rotation variable that is used in the Update method with a transformation matrix to rotate it around the Z axis. Since the Shape is parented by a Collider which is then parented by an actor, I have programmed its rotation to lock in with the Collider's parent actor. The problem is when the actor is turning the Shape begins to behave very oddly and spin about the actor at varying speeds. Here is the code:

The Update method inside the Shape class:

```
    public void Update()
    {
        if (!Circle && Rotation != lastRotation)
        {
            lastRotation = Rotation;

            Matrix rotate = Matrix.CreateRotationZ(Rotation);

            for (int v = 0; v < Vertices.Count; v++)
            {
                Vertices[v] = Vector2.Transform(Vertices[v], rotate);
            }
        }
    }

```

The Update method inside the Collider class:

```
    public void Update()
    {
        if (BoundingShape != null)
        {
            BoundingShape.setCenter(position.X, position.Y);
            BoundingShape.Update();
        }
    }

```

Part of the Update method in the actor class involving the Collider (Test) and Shape:

```
        Test.Update();
        Test.setPos(position.X, position.Y);
        Test.BoundingShape.Rotation = Rotation;

```

I looked around quite a bit before asking so I apologize if something similar has already been answered. All help is greatly appreciated!

# Answer
In this line here:

```
Vertices[v] = Vector2.Transform(Vertices[v], rotate);

```

You are overwriting your shape's vertices with the transformed vertices. The transformation you are creating is an **absolute** rotation, but you are applying it like a **relative** rotation. If this were simple algebra, you could use a relative rotation instead:

```
Matrix rotate = Matrix.CreateRotationZ(Rotation - lastRotation); // DON'T DO THIS!!

```

The reason you *don't* do this is because floating-point error will accumulate in your vertices as you repeatedly transform them. Floating-point is an approximation, so tiny amounts of imprecision will add up to large errors over time.

Instead, you should start with a base set of vertices (like a template), and always apply the absolute rotation. Like so:

```
TransformedVertices[v] = Vector2.Transform(Vertices[v], rotate);

```

If you are applying a translation transformation (your `setPos` method?), you should do it in the same way. You should never modify the original vertices. Instead, store the position (as you are storing the rotation), and then apply both transformations at once to output a transformed set of vertices. You can combine transformation matrices by multiplying them together (note that the order is important).

This is the standard way of using transformations (particularly for rendering things). Your original set of vertices is said to exist in "model space", and the transformed set of vertices exist in "world space".
> 1 votes

---
Tags: xna, c#, 2d, matrix, transformation
---


# Question
Title: How does Lua work as a scripting language in games?
I'm a little hazy on what exactly Lua is and how a game that is programmed in C++ would use it. I'm asking primarily about how it is compiled and run.

For instance when you use a program written in C++ which uses Lua scripts: does the code in Lua just call to functions in the main program written in C++ and act as a uncompiled class waiting to be compiled and added to the memory heap of the C++ program?

Or does it act like a bash script in Linux where it just executes programs completely separate from the main program?

# Answer
> 98 votes
Scripting is a programming abstraction in which you (conceptually) have a program (the script) running inside another program (the host). In most cases, the language in which you write the script is different from the language in which the host is written, but any program-inside-a-program abstraction could be considered scripting.

Conceptually, the common steps to enable scripting are the following (I will be using pseudo-c for the host and pseudo-lua for the script. These are not exact steps, but more like the general flow in which you enable scripting)

1. Create a virtual machine in the host program:

```
 VM m_vm = createVM();

```
2. Create a function and expose it to the VM:

```
 void scriptPrintMessage(VM vm)
 {
     const char* message = getParameter(vm, 0); // first parameter
     printf(message);
 }

 //...

 createSymbol(m_vm, "print", scriptPrintMessage);

```

Notice that the name in which we exposed the function (`print`) does not have to match the internal name of the function itself (`scriptPrintMessage`)

3. Run some script code that uses the function:

```
 const char* scriptCode = "print(\"Hello world!\")"; // Could also be loaded from a file though
 doText(m_vm, scriptCode);

```

That's all there is to it. The program then flows in the following manner:

1. You call `doText()`. Control is then transferred to the virtual machine, which will execute the text inside `scriptCode`.
2. The script code finds a previously exported symbol `print`. It will then transfer control to the function `scriptPrintMessage()`.
3. When `scriptPrintMessage()` finishes, control will transfer back to the virtual machine.
4. When all of the text in `scriptCode` has been executed, `doText()` will finish, and control will be transferred back to your program on the line after `doText()`.

So in general, all you're doing is running a program inside another program. Theoretically speaking, there is nothing you can do with scripts that you can't do without them, but this abstraction allows you to do some interesting things really easily. Some of them are:

* Separation of concerns: it is a common pattern to write a game engine in C/C++ and then the actual game in a script language like lua. Done right, the game code can be developed completely independently from the engine itself.
* Flexibility: scripting languages are commonly interpreted, and as such, a change in a script will not necessarily require a rebuild of the entire project. Done right, you can even change a script and see the results without even a program restart!
* Stability and security: since the script is running inside a virtual machine, if done right, a buggy script won't crash the host program. This is specially important when you allow your users to write their own scripts to your game. Do remember that you can create as many independent virtual machines as you like! (I once created an MMO server in which each match ran on a separate lua virtual machine)
* Language features: when using scripting languages, based on your choice for host and script languages, you can make use of the best features each language has to offer. In particular, lua's coroutines are a very interesting feature that is very difficult to implement in C or C++

Scripts are not perfect though. There are some common disadvantages to using scripting:

* Debugging becomes very difficult: usually, the debuggers included in common IDEs are not designed to debug the code inside scripts. Because of this, console trace debugging is much more common than I'd like.

Some scripting languages like lua have debugging facilities which can be taken advantage of in some IDEs like Eclipse. Doing this is very difficult, and I've honestly never seen script debugging working as well as native debugging.

By the way, the extreme lack of interest the Unity developers have in this matter is my main criticism of their game engine, and the main reason I don't use it anymore, but I digress.

**Update from 2023:** I now use a Lua debugger for Visual Studio Code called LuaPanda, which allows you to attach the debugger to a Lua VM by just adding one line of code to the script (no changes to the host program). It's a bit clunky to install, but it works really well once you're up and running with it.
* IDE integration: It is unlikely that your IDE will know which functions are being exported from your program, and as such, features such as IntelliSense and the like are unlikely to work with your scripts.
* Performance: Being commonly interpreted programs, and meant for an abstract virtual machine whose architecture may be different from the real hardware, scripts are commonly slower to execute than native code. Some VMs like luaJIT and V8 do a really good job though. This may be noticeable if you do some very heavy usage of scripts.

Usually, context changes (host-to-script and script-to-host) are very expensive, so you may want to minimize them if you're having performance problems.

How you use your scripts is up to you. I've seen scripts used for things as simple as loading settings, to as complex as making entire games in the scripting language with a very thin game engine. I once even saw a very exotic game engine that mixed lua and JavaScript (via V8) scripting.

Scripting is just a tool. How you use it to make awesome games is completely up to you.

# Answer
> 8 votes
Generally, you bind or expose some native functions to Lua (often using a utility library to do so, although you can do it by hand). That allows Lua code to make calls into your native C++ code when your game executes that Lua code. In this sense, your assumption that the Lua code just calls into the native code is true (although Lua has its own standard library of functionality available; you do not *need* to call into your native code for everything).

The Lua code itself is interpreted by the Lua runtime, which is C code that you link as a library (usually) in your own program. You can read more about how Lua works at the Lua homepage. In particular, Lua is not "an uncompiled class" as you surmise, especially if you are thinking of a C++ class, because C++ is almost never dynamically compiled in practice. However, the Lua runtime and objects created by Lua scripts that your game runs do consume space in your game's pool of system memory.

# Answer
> 5 votes
Scripting languages like Lua can be used in several ways. As you said you can use Lua to call functions in the main program but you can also just have Lua functions called from the C++ side if you want. Generally you build up an interface to allow some flexibility with the scripting language of your choice so you can use the scripting language in a series of scenarios. The great thing about scripting languages like Lua is they are interpreted instead of compiled so you can modify the Lua scripts on the fly so you don't have to sit around waiting for your game to compile only for you to re-compile if what you've done doesn't suit your tastes.

Lua commands only get called when the C++ program wants to execute them. As such, the code will only be interpreted when it is called. I guess you can consider Lua as a bash script that executes separately from the main program.

Generally you want to use scripting Languages for things you may want to update or iterate further down the line. I've seen a lot of companies use it for the GUI so it provides a lot of customizability to the interface. Providing you know how they have made their Lua interface you can also modify the GUI yourself. But there are numerous other paths you can take to using Lua, such as AI logic, information about weapons, dialogue of characters, etc.

# Answer
> 4 votes
Since no one mentioned this, I will add it here for those interested. There is a whole book on the subject called Game Scripting Mastery. This is a fantastic text that was written quite a while ago, but it remains completely relevant today.

This book will not only show you how scripting languages fits into native code, it also teaches you how to implement your very own scripting language. While this will be overkill for 99% of users, there is no better way to understand something than actually implementing it (even in a very basic form).

If you ever want to write a game engine yourself (or you work with a render engine only), this text is invaluable for understanding how a scripting language can best be incorporated into your engine/game.

And if you ever want to create your own scripting language, this is the one of the best places to start (as far as I know).

# Answer
> 3 votes
Most scripting languages, including Lua, operate on a Virtual Machine (VM), which is basically a system to map a script instruction to a "real" CPU instruction or function call. The Lua VM normally runs in the same process as the main application. This is specially true for games that use it. The Lua API provides you with several functions that you call in the native application to load and compile script files. E.g. `luaL_dofile()` compiles the given script into Lua bytecode and then runs it. This bytecode will then be mapped by the VM running inside the API into native machine instructions and function calls.

The process of connecting a native language, such as C++, with a scripting language is called *binding*. In the Lua case, its API provides functions that help you expose native functions to the script code. So you can for example define a C++ function `say_hello()` and make this function callable from a Lua script. The Lua API also provides methods for creating variables and tables via C++ code that will be visible for the scripts when they are run. By combining these features you can expose entire C++ classes to Lua. The opposite is also possible, the Lua API allows the user to modify Lua variables and call Lua functions from the native C++ code.

Most if not all scripting languages provide APIs to facilite the binding of script code with native code. Most are also compiled into bytecode and run in a VM, but some may be interpreted line-by-line.

Hope this helps clarifying some of your questions.

# Answer
> 2 votes
Firstly, **scripting languages are USUALLY not compiled**. That is a large part of what generally defines them as scripting languages. They are often, instead, "interpreted." What this essentially means is that there is another language (one that *is* compiled, more often than not) that is reading in the text, in real time, and performing operations, line-by-line.

The difference between this and other languages is that scripting languages tend to be simpler (commonly referred to as "higher level"). However, they also tend to be a bit slower, as compilers tend to optimize a lot of the issues that come with the "human element" of coding, and the resulting binary tends to be smaller and faster to read, for the machine. Additionally, there is less overhead from another program needing to be run to *read* the code being run, with compiled programs.

Now, you might be thinking, "Well I get that it's a bit easier, but why on earth would someone give up all that performance for a little bit extra ease of use?"

You would not be alone in this assumption, however the level of ease you tend to get with scripting languages, depending on what you're doing with them, can be well worth the sacrifice in performance.

Basically: **For instances where speed of development is more important than speed of the program being run- use a scripting language.** There are PLENTY of situations like this in game development. Especially when dealing with trivial things like high-level event handling.

Edit: The reason lua tends to be rather popular in game development is because it is arguably one of the fastest (if not the fastest) publicly available scripting languages on earth. However, with this extra speed, it has sacrificed some of its convenience. That being said, it's still arguably more convenient than working with straight up C or C++.

**Important Edit:** Upon further research, I've found that there's a lot more controversy over the definition of a scripting language (see Ousterhout's dichotomy). The primary criticism of defining a language as a "scripting language" is that it is neither significant to the syntax nor the semantics of the language that it is interpreted or compiled.

While languages that are usually considered "scripting languages" are usually traditionally interpreted, rather than compiled, the long and short of their definition as "scripting languages" is really up to a combination of how people view them, and how their creators defined them.

Generally speaking, a language could be easily considered a scripting language (assuming you agree with Ousterhout's dichotomy) if it fulfills the following criteria (according to the article linked, above):

* They are typed dynamically
* They have little or no provision for complex data structures
* Programs in them (scripts) are interpreted

Additionally, it is often accepted that a language is a scripting language if it is designed to interact and function alongside another programming language (usually one that is *not* considered a scripting language).

---
Tags: c++, scripting, lua
---


# Question
Title: Different ways to load/select characters in a RPG game
I am brand new here, and have been designing a two player card game where from tens of thousands of cards each player selects up to 80 cards DECK, and then fights with those cards.

For reference Yu Gi Oh

There's a lot of data and a player can have up to 3 instances of a card to play and they select the cards they want before the game starts. How do I load this information when starting the game? Any suggestions on the different ways to do it during game initialization?

Like how this is done in RPG games like League of Legends.

# Answer
What kind of data are you storing? You should only save references to cards for your player, unless there are some random stats that may change (in that case you'll have to store those as well).

Since you didn't specify any language, I'm assuming C++. Similar techniques can be used in other languages as well, they'll just require some different syntax.

First of all, you'll need your cards identified by some unique ID. Since there might be unassigned IDs, I'll be using a `std::map` for now:

```
std::map<unsigned int, CardInformation> cardData;

```

This now allows me to access the card information for any specific card. For example, let's assume you'd like to retrieve the card data for ID 50123:

```
const CardInformation &myCard = cardData[50123];

```

As you can see, this is pretty straightforward. Now, as part of your player's dataset, you'll want some collection of cards - or more specific: card IDs.

You could use a `std::vector` for this, which is more than sufficient. However, this makes counting cards quite cumbersome. So instead, I'm using another `std::map`, which would then be part of the player data:

```
std::map<unsigned int, unsigned char> playerDeck; // own up to 255 copies of each card!

```

This now allows you to do some pretty neat and simple tricks.

How about giving the player one copy of card ID 1023?

```
playerDeck[1023]++;

```

Does the player have card ID 323 in his deck? (naïve approach; will slow down/fill your map over time)

```
const bool hasCard = playerDeck[323] > 0;

```

Does the player have card ID 323 in his deck? (better approach)

```
const bool hasCard = (playerDeck.find(323) != playerDeck.end());

```

How to let the player remove card ID 50 from the deck? (Note this won't remove empty entries)

```
playerDeck[50]--;

```

So, how to store the data in a game file or submit it for a networked game? Pretty easy: Just iterate over the `std::map` containing the deck and store/submit values if the value is not 0. Keep in mind that submitting your deck to the enemy might not be a good idea and subject to abuse (to see the enemy's/your deck).
> 0 votes

# Answer
When you have thousands of players where each player owns hundreds of copies of thousands of different cards, you are dealing with quite a lot of information. To manage all that information, you should store it in a database.

You could either use a good old SQL database, or when you feel a bit more experimental you could use one of the many different NoSQL databases. The question which one to pick is off-topic here, so I will not elaborate further.

But no matter which database you choose, you should load the users decks and the information about each individual card from the database before the match starts and then keep it in memory during the match. The reason for this is that accessing a database is very slow compared to reading the information from memory. For that reason you should avoid any unnecessary database access while the match is running.

Details about how to store and retrieve data from a database are database-specific and a lot too broad to explain here. I would recommend you to read a tutorial on the database of your choice and ask specific questions when you are unsure about details.

An exception from this could be the cards themself (which are different from card-instances. There is only one card "Orc Warrior" but thousands of instances of that card which are owned by different players). Most trading-card games have quite complex cards which might be hard to model in a relational database. There is also the difference that the cards are changed very rarely while the decks and players are data entities which change all the time. That means it might be better to describe each individual card with a file which includes its properties and scripts. The deck database would then only reference the names, while all of the card-data is read from these files.
> 0 votes

---
Tags: rpg, initialization
---


# Question
Title: Error when using GetComponent (Object reference not set to an instance of an object)
I'm using a textmesh to check variables in real time. Thing is if I use AddComponent within Update(), it obviously starts spamming and slows the game. If I try with GetComponent the error is the following:

> NullReferenceException: Object reference not set to an instance of an object
>
> DebugCombo.Update() (at Assets/DebugCombo.js:9)

which points to the `text.text` assignment.

This is the script from DebugCombo.js, from which I call the Combo class (from Combo.js)

```
#pragma strict

public class DebugCombo extends MonoBehaviour{

    function Update () {
        var text = gameObject.GetComponent(TextMesh);
        var combo = gameObject.GetComponent(Combo);

        text.text = "Current: "+ Time.time +" | Limit: " + combo.comboTime;
    }

}

```

How do I get rid of this error?

# Answer
You seem not to have a TextMesh component in your game object, and you are not checking if `GetComponent` method has returned any. You can add it once at runtime if it doesn't exist:

```
var text = gameObject.GetComponent(TextMesh);
if( text == null )
{
    text = gameObject.AddComponent(TextMesh);
}

```

Or to make it better, you can make `var text` a private class variable to cache it, and not to call `GetComponent` all the time.

The second way, is to make `text` and `combo` a public class variables, and then drag and drop the proper instances in the editor. Then, you wouldn't have to call any `Add/GetComponent` calls at runtime, because you would already have them attached.

Anyway, you should always check if `GetComponent` has returned something, and if not you should call `Debug.LogError("Your error message here")` to avoid NullPointer exception and application crash.
> 1 votes

---
Tags: unity, javascript, objects
---


title: Converting xnb files to fbx files

text:
# Question
Title: Converting xnb files to fbx files
All the while I can only find how to convert from FBX to XNB but not the other way around. Does anyone know how can I do that?

# Answer
XNB is a binary container for all your content in programs that use the XNA content pipeline, this includes models, but also textures, fonts, audio, and sprites.

While it is possible to extract information from an XNB file (see for example this plugin for paint.net that extracts the textures in an XNB file: ) I do not know of any programs that extract model information. You will probably have to write your own program to do this.

On another note, why would you want to extract models from an XNB file, did you lose the source models? Or are you trying to extract and use a model that you didn't make yourself? Because that is legally gray/black territory.
> 3 votes

# Answer
Googling, I found these descriptions of the file formats:

> FBX (Filmbox) is a proprietary file format (.fbx) developed by Kaydara and now owned by Autodesk. It is used to provide interoperability between digital content creation applications.

and

> ...compiled data files (.xnb) produced by the XNA Game Studio 4.0 Content Pipeline build process...

Judging from those short quotes, I'd guess it's a case of data loss in translation. Not all data in FBX ends up in XNB.

EDIT: Microsoft has posted a sample XNB parser (along with the format spec) which could be a starting point for the converter: http://xbox.create.msdn.com/en-US/sample/xnb\_format
> 1 votes

---
Tags: 3d, models, fbx
---


# Question
Title: Component based architecture: "pure" or some inheritance?
*(I asked a similar question, but it had more questions inside it and I feel it wasn't clear enough, so I'm opening a new one).*

Until recently I implemented all my games using an inheritance hierarchy. Those were simple games.

For example:

```
          Entity
          /    \
      Movable  Static
      /  \        /  \
    Orc  Mage   Tree  Wall

```

This worked for simple games.

However recently I read about 'entity component systems'. Using this approach, a class doesn't inherit from another class in order to receive functionality. Instead it is composed with it, which allows for more flexible designs.

My question is this:

I know that each component is a class (derived from a common base class).

However, there is one thing I don't understand: In the 'component system' approach, is there **one** class that all entities are instances of - and the only difference between entities is the components they contain?

For example: There is a class `Entity`. All entities in the game are instances of this class.

The only differences between them is that they are composed with different `Component` objects.

For example:

```
Component aiComponent = new AIComponent();
Component movementComponent = new MovementComponent();
Component physicsComponent = new PhysicsComponent();
Component rangedAttackComponent = new RangedAttackComponent();

Entity orc = new Entity();
orc.addComponent(aiComponent);
orc.addComponent(movementComponent);
orc.addComponent(physicsComponent);

Entity shootingCastle = new Entity();
shootingCastle.addComponent(aiComponent);
shootingCastle.addComponent(rangedAttackComponent);
shootingCastle.addComponent(physicsComponent);

```

All of this as opposed to my old approach:

```
Orc orc1 = new Orc();
ShootingCastle castle1 = new ShootingCastle();

```

As you can see, both `orc` and `shootingCastle` are instances of the `Entity` class. But they are composed with different components.

Is this how 'entity component systems' are supposed to be? **No inheritance hierarchy at all?** **Or is there still a basic inheritance hierarchy, but most of the logic is inside components?**

# Answer
Yes! No! Maybe!

To 1:

No, your understanding of the Component-Entity-Model is not fully correct. If you had a "superclass" than you did something wrong in the first place. You will gain much if you resolve that issue first before chopping up your code into components.

As a basic rule of thumb **favor composition over inheritance**. This does not necessarily mean you naturally end up at a Entity Component Model. You can extract bits of your code into objects without having one singular base class.

For example you can extract different attack behavior into multiple classes (MagicAttack, MeleeAttack, etc.) that have the common Attack base class. This would then be composed into different entities where needed.

The primary gain of the Entity-Component-Model is ludicrous flexibility at the cost of added complexity. If you add this with a data driven method to generate the entities, you get the ability to create new entities without recompiling. But this only really makes sense when you have non programmers adding logic to the game.

To 2:

You can use inheritance for the process of how to get the components into the entities. It works fine, but defies primary gain of a Entity-Component-Model. This is the case, since the biggest power is gained when entity composition is done outside of the code.

What should you use? That is a hard problem, especially since we do not know what you are trying to apply it on. You can gain much by employing an Entity Component Model, but the added effort may not be worth the effort.
> 2 votes

# Answer
I don't think there is any reason for an entity to be a class in the first place. It could be represented by an index number unique to that entity. Components can then have a member named entity\_id with that index. There is no need for any inheritance or classes to represent entities.

Components could and would possibly use classes and inheritance.

Using classes an inheritance is wasteful if it's not done to prevent code duplication or substantially improve your productivity in some manner. I would recommend using only what your project needs when it is needed as it is absolutely disastrous\* to use a technique when it is not useful or avoid using one that is needed.

\*Detrimental to productivity and if you're an indie with a very limited budget I would consider it to be a disaster.
> 0 votes

---
Tags: architecture, component-based
---


# Question
Title: How do I convert a partially transparent image into polygons?
I'm using *GLEE2D*, a level editor allowing me to import images, scale them, rotate them, and position them onto layers and export the data into XML format. However, it does not tell me objects' boundaries. I can calculate them, but only given the original image's polygons.

How do I get polygons of objects in a transparent image?

An example object (I outlined it):

How would I turn the object, knowing the scaled size of the image, into polygons? Is there an algorithm for this? I'll use OpenGL to draw them.

# Answer
> 1 votes
You could use the Marching Squares algorithm to generate the 2d-mesh you want. After using the marching squares to outline the object, you could use this library to do the triangulation.

---
Tags: physics, algorithm, image, gleed2d
---


# Question
Title: Generating shaders from fragments / HLSL Dynamic Linking in older shader models
In shader model 5 is a feature called dynamic linking which separates hlsl fragments by using interfaces and their methods implemented in classes.

I don't have any experience with this technique, my program uses about 10 shaders (10 separated files \*.hlsl) and there are some identical parts in different shaders. So it will be good for me to separate a common logic (light for example) to its own file and just use it from other shaders.

I was always fascinated by modern game engines and their development kits capable of composing these shader fragments together by simple clicking in some internal editor. So a developer can create very complex scenes this way - choose materials, lights, particles, animations, etc. and it's very cool and productive I guess. If I omit some graphical editor and a sophisticated logic behind it, it is pretty what I want to achieve, isn't it? Just on a code level.

So with hlsl's dynamic linking in shader model 5 I have some idea how it can be done, but what about older shader models? When there was no shader model 5, what technique did engines use?

# Answer
I believe very few game developers actually use the dynamic linking feature in HLSL, as it's a fairly limited, awkward form of abstraction and isn't as general as one might like it to be. Also, developers have needed to maintain backward compatibility with earlier APIs; there haven't been very many D3D11-only games to date.

In practice, you can get all the same benefits in terms of code reuse, and greater flexibility, by simply using header files that define common functions and data structures, then writing (or automatically generating from a tool) shaders that `#include` those headers and call functions out of them.

You can imagine implementing an Unreal-style node-based shader system by writing a function to represent each type of node in the graph, then writing code to generate a `main()` function for the shader that calls the functions for all the nodes, wiring up the parameters and returns according to the user-specified connections and values. The generated shader would then be passed to the usual shader compiler, which optimizes away any code that isn't used by that particular shader.
> 1 votes

---
Tags: shaders, hlsl
---


# Question
Title: How do I fit the camera frustum inside directional light space?
I'm trying to improve the coverage of a shadow map for a directional light. Currently, it works great if the camera is looking straight down. However, if the camera is close to the ground and looking toward the horizon, I can see where the shadow map ends because it doesn't cover enough of the scene.

I'd like to create a frustum for the directional light so that it entirely encloses the camera's frustum, as this article suggests in figures 14 and 15. (I'm not really worried about the near and far planes for the light; I've picked a number that works well for every test I've tried)

I know the direction of the light, and the position, rotation, and field of view of the camera. I'm using OpenGL.

How do I create a frustum for the light so that it encloses my view frustum?

# Answer
The basic process for a directional light (whose rays are parallel) is as follows:

1. Calculate the 8 corners of the view frustum in world space. This can be done by using the inverse view-projection matrix to transform the 8 corners of the NDC cube (which in OpenGL is \[‒1, 1\] along each axis).
2. Transform the frustum corners to a space aligned with the shadow map axes. This would commonly be the directional light object's local space. (In fact, steps 1 and 2 can be done in one step by combining the inverse view-projection matrix of the camera with the inverse world matrix of the light.)
3. Calculate the bounding box of the transformed frustum corners. This will be the view frustum for the shadow map.
4. Pass the bounding box's extents to `glOrtho` or similar to set up the orthographic projection matrix for the shadow map.

There are a couple caveats with this basic approach. First, the Z bounds for the shadow map will be tightly fit around the view frustum, which means that objects outside the view frustum, but between the view frustum and the light, may fall outside the shadow frustum. This could lead to missing shadows. To fix this, depth clamping can be enabled so that objects in front of the shadow frustum will be rendered with clamped Z instead of clipped. Alternatively, the Z-near of the shadow frustum can be pushed out to ensure any possible shadowers are included.

The bigger issue is that this produces a shadow frustum that continuously changes size and position as the camera moves around. This leads to shadows "swimming", which is a very distracting artifact. In order to fix this, it's common to do the following additional two steps:

1. Fix the overall size of the frustum based on the longest diagonal of the camera frustum. This ensures that the camera frustum can fit into the shadow frustum in any orientation. Don't allow the shadow frustum to change size as the camera rotates.
2. Discretize the position of the frustum, based on the size of texels in the shadow map. In other words, if the shadow map is 1024×1024, then you only allow the frustum to move around in discrete steps of 1/1024th of the frustum size. (You also need to increase the size of the frustum by a factor of 1024/1023, to give room for the shadow frustum and view frustum to slip against each other.)

If you do these, the shadow will remain rock solid in world space as the camera moves around. (It won't remain solid if the camera's FOV, near or far planes are changed, though.)

As a bonus, if you do all the above, you're well on your way to implementing cascaded shadow maps, which are "just" a set of shadow maps calculated from the view frustum as above, but using different view frustum near and far plane values to place each shadow map.
> 14 votes

---
Tags: opengl, shadow-mapping
---


title: android game development using unity 3d

text:
# Question
Title: android game development using unity 3d
I want to learn android game development. I dont have any programing knowledge. So should I learn JAVA and eclispe to develop games for android.

Or should I learn Unity 3d. And is knowledge of java programing is necessary to develop android games in unity? Or knowledge of Javascript/UnityScript will do. Can I develop android games in unity with just JavaScript knowledge??

what are the benefits of unity over Java/eclipse and vice versa when talking of android game dev??

# Answer
> 0 votes
When you build a mobile game in Unity to port onto Android, it creates an .apk package that loads onto your phone and runs. Technically you don't need to know any Java because it builds it all for you, but it would be recommended to learn the basics so that if any edge cases come up when building your apk package, you would be able to figure them out. You could jump right into Unity using UnityScript or JavaScript, but learning the technology it is built on will help you fundamentally with knowing how your game works as a whole and allow you to manipulate your environment to a greater extent. Keep in mind that Unity is a great development platform, but every platform has it's limitations, and if you want to develop a game outside of Unity's restrictions then coding in Java in Eclipse may be preferred.

# Answer
> 0 votes
There are tons of resources for learning Java focused on android Development right now, as well as Unity 3D. If you plan to develop a game in android with java then start with Java, but don't go over the entire android framework just to switch to Unity.

Try to start with a simple project or tutorial in unity as soon as possible, seeing your game and getting something running through programming in Unity for the first time is a beautiful experience. The longer you wait to do that, chances are you'll get frustated before getting something running.

Unity has C# scripting which is similar in some ways to java, and there are lot more of resources in that languange than in Unityscript. Start small with some tutorials, such as this one: http://pixelnest.io/tutorials/2d-game-unity/

Tl;dr; Manage your frustation. Try to get some stuff running as quick as possible and then improve upon it.

---
Tags: java, android, unity, javascript, unityscript
---


title: GameObject remains null for some reason

text:
# Question
Title: GameObject remains null for some reason
The idea is to access the function **BlockWasDestroyed();** from Combo class.

Instead of `var combo = gameObject.GetComponent(Combo);` I've also tried with

> var combo = GetComponent(Combo);
>
> var combo:Combo = gameObject.GetComponent(Combo);
>
> var combo:Combo = GetComponent(Combo);

But the console keeps telling it's null. However it could work when the function was static, but thing is now that function is calling another function, and so the errors happen once again.

Here's my code so far:

**Brick.js**

```
#pragma strict

public class Brick extends MonoBehaviour{

    function OnCollisionEnter(col : Collision){
        if(col.gameObject.name == "Ball"){
            var ballb = gameObject.GetComponent(BouncingBall);
            var combo = gameObject.GetComponent(Combo);
            combo.BlockWasDestroyed();
            ballb.velocityZ = ballb.velocityZ * -1;
            Score.score += 20;
            Destroy(this.gameObject);
        }
    }
}

```

# Answer
There is no Combo attached to the GameObject to which Brick is attached, most likely.

Are you sure you don't mean this?

```
#pragma strict

public class Brick extends MonoBehaviour{

    function OnCollisionEnter(col : Collision){
        if(col.gameObject.name == "Ball") {
            var ballObj = col.gameObject;
            var ballb = ballObj.GetComponent(BouncingBall); //Getting components
                                                            //from the ball instead.
            var combo = ballObj.GetComponent(Combo);
            combo.BlockWasDestroyed();
            ballb.velocityZ = ballb.velocityZ * -1;
            Score.score += 20;
            Destroy(this.gameObject);
        }
    }
}

```
> 2 votes

---
Tags: unity, javascript
---