# Question
Title: Unity: Increase animation speed of individual component in a blend tree?
I have blend tree with four different turns: a sprinting turn, running turn, walking turn, and standing turn.

I need to somehow make the angular velocity increase from sprinting down to standing, so that as the character gets slower he turns faster (otherwise it is basically unplayable).

How do I increase the angular velocity of an individual animation in the blend tree? The usual "speed" attribute disappears when I put the animation in the blend tree...and I have not figured out how to access the blend tree substate from code yet.

Here is an image of the blend tree, and the inspector:

# Answer
> 2 votes
There's a speed field in each line of the blend tree. It's the column with the clock icon. You can use that to adjust the speed of each animation.

You can see it in the last image on this page: http://docs.unity3d.com/Manual/class-BlendTree.html

---
Tags: animation, unity
---


# Question
Title: Moving Objects Relatively With Their Parent Object [Gamemaker]
I have an object type, `oFur`, instances of which are generated in a random distribution over the sprite area of a parent object, `oFurArea`.

However, I would like the `oFurArea` to change its `image_xscale` and `image_yscale` dynamically, as well as its `y` position. This is easy to do, but I would also like all of the `oFur` instances to move with their parent (i.e. change their own 'y' values), whilst maintaining their relative positions on the parent object.

Either I'm having a brain-fart, or I cannot work out how to do this. Any help would be appreciated.

# Answer
> 1 votes
Thanks to @DH above, I've managed to find an elegant solution to this, I think.

Every step, the `oFurArea` updates its `Difference` variable as the *distance between its original y value and its current y value*. This needs to be done every step, as `oFurArea` is constantly moving:

```
Difference = OriginalY - y

```

Each `oFur` instance than also has an `OriginalY` value, set upon Create. Every step, they set their own `y` value to a distance *relative to `oFurArea`'s distance*.

Therefore, if the distance between oFurArea's current `y` and its `OriginalY` was 15 pixels, each `oFur`'s `y` would be 15 pixels from its own `OriginalY` as well. This keeps everything relative to each other.

So, in the `oFur`'s Step event:

```
y = OriginalY - oFurArea.Difference

```

I think this solution is elegant as it only requires two variables and only two lines of code. Thank you for the help, DH.

---
Tags: game-maker
---


# Question
Title: How can I give the illusion of height to a ball in 2D?
In 2D top down soccer games, sometimes a ball is given the illusion of being in the air, like below:

How can I achieve this?

# Answer
> 79 votes
Give the ball a height value. Draw a shadow at the ball's actual 2D position; the shadow will help spatially orient the ball for the player.

When you draw the ball *itself*, offset the Y position by the "height" of the ball. If you want to implement more than just an illusion, use this height value in computations as well -- for example, you can implement the ability for the ball to go over a player's head in a game like you showed by checking if the height is geater than than a player's height.

# Answer
> 77 votes
**Shadow and texture**.

Texturize the ball to show it rotating. This helps give the illusion of rotation of a sphere, which is more than 2 dimensions.

A shadow can trick your brain into believing all sorts of things. Making flat things look like they have a third dimension.

You don't even have to change the height of the ball, you just need to change the location of the shadow.

This video is an excellent example of what shadow can do. You'll notice that the ball moves exactly the same in each sequence, only the shadow changes: https://www.youtube.com/watch?v=5fgOK0odA1o

# Answer
> 1 votes
Shadow and Ball are key aspects. Shadow size and distence between Ball and shadow should increase when height increase. Also, Ball size should increase when Ball height increase. Shadow position represents position of ball in 2d and when Ball height increase you have to change Ball position (I m assuming that light source is homogen and it is not single point like a lamp. Light source changes everything about shadow). Finally you can add some animation like air flow.

# Answer
> 0 votes
I would do what the above posters suggested, Shadow and size increase when ball is higher. A thing I remember from playing tennis on old TV games is that the ball also slowed down the higher it went and bigger it became. When it reached it's zenith and started "coming down" it would start going faster again as it became smaller.

# Answer
> -1 votes
You draw a shadow below the ball, like it's done in the gif. The higher the ball, the longer the distance between the ball and the shadow.

---
Tags: java, libgdx, physics
---


# Question
Title: Unity Surface Shader: Conditinally noforwardadd
I'd like to have this in my shader:

```
#if SHADER_API_MOBILE
#pragma surface surf Lambert noforwardadd
#else
#pragma surface surf Lambert
#endif

```

But this tries to compile both #pragma surface and ignores the second one instead of respecting the #if condition.

Anyone know how to add "noforwardadd" to a shader, but only when it's compiled for mobile platforms?

Thanks!

Allen

# Answer
> 2 votes
Preprocessor macros don't work on pragmas, because they are parsed before any preprocessing happens. What you can do instead is to make two identical subshaders, the top one without noforwardadd and the bottom one with. If you assign different LOD thresholds to those subshaders, you can then choose between them by making mobile builds use a lower LOD value:

```
SubShader {
    // Desktop shader
    LOD 300

    CGPROGRAM
    #pragma surface surf Lambert
    ...
    ENDCG
}
SubShader {
    // Mobile shader
    LOD 100

    CGPROGRAM
    #pragma surface surf Lambert noforwardadd
    ...
    ENDCG
}

```

With LOD set as:

```
#if (UNITY_IOS || UNITY_ANDROID)
    Shader.globalMaximumLOD = 200; // Only subshaders with LOD <= 200 will run
#else
    Shader.globalMaximumLOD = Int32.MaxValue;

```

---
Tags: unity, shaders
---


# Question
Title: Unity Profiler - What would cause PlayerEndOfFrame to have 10-16MB in GC Alloc?
I can't find much documentation on what "PlayerEndOfFrame" does. Sure it is the end of a frame but what would cause the GC Alloc to go so high?

This is the profiler results from a debug build on a remote machine using the IP connect to unity profiler.

# Answer
PlayerEndOfFrame is where your work shows up when you run a Unity coroutine and increment it by using the command "yield return new WaitForEndOfFrame();"

In this case the coroutine you are running is instantiating a lot of memory and doing a lot of work every frame.

It is also worth noting that by using WaitForEndOfFrame here you are running your coroutine after all the other processing for that frame has finished. This is not normally a good idea. Most of the time you should be progressing to the next frame using the statement "yield return null;", which will run your coroutine in the normal update loop.

You probably won't notice any difference when using WaitForEndOfFrame most of the time, but it will cause some weird graphical issues if your framerate drops or when you initialize a game object in one section of your code and then set it's values in a different section.
> 1 votes

---
Tags: unity, optimization, memory-efficiency, profiler
---


# Question
Title: Unity Non-shader method of combining two RGB Textures into a single RGBA Texture
I work in a broadcast environment that delivers video signals over SDI as Fill (RGB) and Key (A) signals. My SDI rendering method produces a Texture for each SDI input and applies it to a material. I'm currently using a shader to populate two texture slots on the material in order to use the Key signal as an alpha mask.

This works pretty well, but it would be ideal to produce a single RGBA Texture from the two, and feed the material with the single Texture. A shader would not produce a new Texture I could get a handle on, so I'm looking for an alternate solution. So far, my google-fu has only produced shader-based approaches, or use somewhat inefficient getPixel/setPixel loops. Is there any affordance for generating a new Texture and defining channel-based inputs?

# Answer
There are two main ways that you can approach this:

1. Use a shader, which will take advantage of the GPU and generally be the most efficient solution all around. You would do this by creating a material that points to a shader and using Graphics.Blit to write to your destination texture using the shader.
2. Use Texture2D.ReadPixels to read the array of pixels from the two images, average the value of every pixel in image1 with the coorsponding pixel in image2, and then use Texture2D.SetPixels to save them.
> 1 votes

# Answer
is it possible to render to a texture? In that case you could use a shader to combine the textures, then use the composite texture.
> 0 votes

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


title: Check rotation before rotating

text:
# Question
Title: Check rotation before rotating
I am making a puzzle game in Unity. I have several `GameObjects` that have children objects where each child object has a `BoxCollider2D`.

The game requires that the pieces be rotated, but to position them correctly, they also need to be translated under certain rotations. I thought a good way to handle this would be using an animator that has 0, 90, 180 and 270 degree states. When the objects are by themselves, I have this working correctly.

The problem I am having is when there are two adjacent `GameObjects`. When the user tries to rotate a block and the rotation would result in overlapping colliders, I want to ignore the rotate command and do nothing. Traditionally, this would mean that I would rotate the piece, check collisions, and if there is a collision, rotate back in the same `Update()` call.

My question is: Is there any way after telling the animation to rotate i.e.

```
animator.SetFloat("Rotation",animator.GetFloat("Rotation") + 90);

```

to subsequently tell it to jump to the last frame of the new animation state so that I can check collisions on it and then revert the animation to its original position if there is a collision -- all in the `Update()` function?

Or am I better off ditching the `Animator` and doing it myself?

# Answer
You should not have your logic be done in the animator. You need to do your calculations in the code behind, and then you can call on the animator when you know what you want animated. You may want to look into adapting the MVC pattern for unity.

If you really want to do it like this though, you can add an event to a key frame in Unity animations. This event will call a method, where you can perform a check. Then in that check, you can either stop your animation, play it in reverse, or let it play through.
> 0 votes

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


# Question
Title: How can I support component-to-object communication safely and with cache-friendly component storage?
I'm making a game that uses component-based game objects, and I am having a hard time implementing a way for each component to communicate with its game object. Rather than explain everything at once, I will explain each part of relevant sample code:

```
class GameObjectManager {
    public:
        //Updates all the game objects
        void update(Time dt);

        //Sends a message to all game objects
        void sendMessage(Message m);

    private:
        //Vector of all the game objects
        std::vector<GameObject> gameObjects;

        //vectors of the different types of components
        std::vector<InputComponent> input;
        std::vector<PhysicsComponent> ai;
        ...
        std::vector<RenderComponent> render;
}

```

The `GameObjectManager` holds all the game objects and their components. It is also responsible for updating the game objects. It does this by updating the component vectors in a specific order. I use vectors instead of arrays so that there is virtually no limit to the number of game objects that can exist at once.

```
class GameObject {
    public:
        //Sends a message to the components in this game object
        void sendMessage(Message m);

    private:
        //id to keep track of components in the manager
        const int id;

        //Pointers to components in the game object manager
        std::vector<Component*> components;
}

```

The `GameObject` class knows what its components are and can send messages to them.

```
class Component {
    public:
        //Receives messages and acts accordingly
        virtual void handleMessage(Message m) = 0;

        virtual void update(Time dt) = 0;

    protected:
        //Calls GameObject's sendMessage
        void sendMessageToObject(Message m);

        //Calls GameObjectManager's sendMessage
        void sendMessageToWorld(Message m);
}

```

The `Component` class is pure virtual so that classes for the different types of components can implement how to handle messages and update. It also is able to send messages.

Now the problem arises on how the components can call the `sendMessage` functions in `GameObject` and `GameObjectManager`. I came up with two possible solutions:

1. Give `Component` a pointer to its `GameObject`.

However, since the game objects are in a vector, the pointers could quickly become invalidated (The same could be said of the vector in `GameObject`, but hopefully the solution to this problem can also solve that one). I could put the game objects in an array, but then I would have to pass in an arbitrary number for the size, which could easily be unnecessarily high and waste memory.

2. Give `Component` a pointer to the `GameObjectManager`.

However, I do not want components to be able to call the manager's update function. I am the only person working on this project, but I do not want to get in the habit of writing potentially dangerous code.

How can I resolve this problem while keeping my code safe and cache friendly?

# Answer
Your communication model seems fine, and option one would work okay if only you could store those pointers safely. You can solve that problem by picking a different data structure for component storage.

A `std::vector<T>` was a reasonable first choice. However, the container's iterator invalidation behavior is a problem. What you want is a data structure that is fast and cache-coherent to iterate over, *and* which also preserves iterator stability when inserting or removing items.

You can build such a data structure. It consists of a linked-list of *pages*. Each page has a fixed capacity, and holds all its items in one array. A count is used to indicate how many items in that array are active. A page also has a free list (allowing reuse of cleared entries) and a skip list (allowing you to skip *over* cleared entries while iterating.

In other words, conceptually something like:

```
struct Page {
   int count;
   int capacity;           // Optional if every page is a fixed size.
   T * m_storage;
   bool * m_skip;          // Skip list; can be bit-compressed.
   std::stack<int> m_free; // Can be replaced with a specialized stack.

   Page * next;
   Page * prior;           // Optional, allows reverse iteration
};

```

I unimaginatively call this data structure a *book* (because it's a collection of pages you iterate though), but the structure has various other names.

Matthew Bentley calls it a "colony." Matthew's implementation uses a jump-counting skip field (apologies for the MediaFire link, but it's how Bentley himself hosts the document) which is superior to the more typical boolean-based skip list in these sorts of structures. Bentley's library is header-only and easy to drop in to any C++ project, so I'd advise you to simply use that versus rolling your own. There are a lot of subtleties and optimizations I'm glossing over here.

Because this data structure never moves items once they are added, pointers and iterators to that item remain valid until that item itself is deleted (or the container itself is cleared). Because it stores chunks of contiguously-allocated items, iteration is fast and mostly-cache-coherent. Insertion and removal are both reasonable.

It's not perfect; it's possible to ruin cache coherency with a usage pattern that involves deleting heavily from effectively random spots in the container and then iterating over that container before subsequent inserts have backfilled items. If you are in that scenario often, you will be skipping potentially-large regions of memory at a time. However in practice I think this container is a reasonable choice for your scenario.

Other approaches, which I will leave for other answers to cover, might include a handle-based approach or a slot-map sort of structure (where you have an associative array of integer "keys" to integer "values," the values being indices in a backing array, which allows you to iterate over a vector by still access by "index" with some extra indirection).
> 5 votes

# Answer
Being 'cache friendly' is a preoccupation *big games* have. This seems to be premature optimization to me.

---

One way to solve this without being 'cache friendly' would be to create your object on the heap instead of on the stack: use `new` and (smart)pointers for your objects. This way, you'll be able to reference your objects and their reference will not be invalidated.

For a more cache friendly solution, you could manage the de/allocation of objects yourself, and use handles to these objects.

Basically, at the initialization of your program, an object reserves a chunk of memory on the heap (let's call it MemMan), then, when you want to create a component, you tell MemMan that you need a component of size X, it'll reserve it for you, create a handle and keep internally where in it's allocation is the object for that handle. It'll return the handle, and that the only thing you'll keep about the object, *never* a pointer to its location in memory.

As you need the component, you'll ask MemMan to access this object, which it will gladly do. But don't keep the reference to it because....

One of the jobs of MemMan is to keep the objects close one to another in memory. Once every few game frames, you can tell MemMan to rearrange objects in memory (or it could do it automatically when you create/delete objects). It'll update its handle-to-memory-location map. Your handles will always be valid, but if you kept a reference to the memory space (a *pointer* or a *reference*), you'll find only despair and desolation.

Textbooks says that this way of managing your memory has at least 2 advantages:

1. less cache misses because objects are close one to another in memory and
2. it reduces the number of memory de/allocation calls you'll make to the OS, which are said to take *some* time.

Keep in mind that the way you use MemMan and how you'll organize the memory internally is really dependant on *how* you'll use your components. If you'll iterate through them based on their type, you'll want to keep components by type, if you iterate through them based on their game object, you'll need to find a way to make sure they're close one to another based on that, etc...
> 4 votes

---
Tags: c++, entity-system, component-based
---


title: How to make Pong Ball Control?

text:
# Question
Title: How to make Pong Ball Control?
I want to know how can I make the control of the Pong Ball in Plain Javascript. I would like to know how to make the ball faster when it hits the edges just like the original pong game, or how if the ball hit's the middle of the paddle it would go straight and slow. I just want to get a feel for how it works.

# Answer
> 2 votes
This is one way on how to do it and might not be the best, there should be some other way.

If you want to change the speed according to where the ball hit the paddle you could do it like this:

You calculate the ball's x position and the middle position of the paddle (x coordinate too of course). For the formula, you could do it like this: `speed = extraSpeed * distance / (0.5f * paddleWidth) + constant;`

For distance, you can do it like this: `abs(paddleMiddle.x - ball.x);` We don't want it to be negative/minus.

Okay, with the formula above `distance / (0.5f * paddleWidth)` will return `0.0f` when the ball hits the middle (`distance = 0.0f`), and will return `1.0f` when the ball hits the edge of the paddle (it can return more than `1.0f` though, you might want to do something about it like clamping the value or perhaps checking the distance from the side of the ball). This value will multiply `extraSpeed`, so the ball will not gain any extra speed when it hits the middle and gain full extra speed when it hits the edge of the paddle. And `constant` here will act as the base speed or you can say the slowest speed (when it hits the middle) you don't want the ball to stop when it hit the middle, do you?

---
Tags: javascript, jquery
---


# Question
Title: Simple javascript HTML5 canvas start menu
I'm currently looking for a simple and basic start screen for a game using javascript, so basically its the first function that is called and then press play which then goes into the game.

Looked online and they all seem to be advanced ones and can't seem to find any tutorials either.

# Answer
Menus and other non-gameplay related UI are actually *much* easier to create when they are driven by the same visualization code used in your gameplay. In the same way you display animate your game objects, you should be able animate your UI buttons and menus as well.

Think of a menu button as a game object with a different sprite. When polishing your game you'll be happy to have the ability to easily tween, scale and fade in/out your UI elements.

Since you don't mention a framework (such as ImpactJS or Crafty, for example) I'm assuming that you've got something home grown. If that's the case you may not have such generic ways to visualize game elements. While you can brute force through creating menus and title screens which do not share the same visualization code as your core game, you'll end up with something much less maintainable and extensible.

Because you're using HTML5 it's also an option to create your menu code using HTML DOM and CSS. While much of the animating and layout of menus will be easy with some CSS transitions, it's still (in my opinion) an inferior option to having your canvas framework be generic and flexible enough to easily create and animate any kind of game object.
> 3 votes

# Answer
I'm guessing your using plain Javascript with no engine. You could just hold off drawing your objects to the screen. If you put all of your game objects in a function then you could hold of rendering them until someone click continue. After that condition is met then the render of all your object can happen. There you go. A nice simple start menu. Was this helpful? If you want a example in code then I might be able to do that for you
> 0 votes

---
Tags: game-design, javascript, html5, html-canvas
---


# Question
Title: 2D Platformer: add ability to jump on top of other character
I want to add ability to jump onto a head of other character/player, but still be able to go through them horizontally. There is one useful tutorial about one-way platforms, but that approach doesn't allow player to go through a platform from a side.

I tried to add sensor to foot and head of characters and enable contact in `preSolve` method, but it doesn't look to work very well (sometimes bodies are thrown out from each other with additional impulse).

Do you have any ideas? Also it would be nice to not change sources of box2d as it was done in tutorial as I'm using it from LibGDX.

# Answer
**Brief:**

The solution is not in collision listeners, but in collision filters. Collision filters have a shouldCollide method that you can implement to return false if you want to disable collision or true to allow it. Collision filters are executed before collision listeners.

You can use, for example the linear velocity of the player sprite to decide if you allow or not the collision with the enemy/platform during that frame of the simulation. For example, if your player sprite has a linear velocity with a negative y (pointing down, angle isn't important) then allow the collision by returning true, if it is 0 or positive do not allow it by returning false.

**Demonstration:**

The following example needs some notes to be correctly analyzed as some "not so common" design decisions were taken. As I used a simple String variable to hold the game level, having `y` pointing down in the positive axis was more convenient, so I inverted the physics world. This means that gravity is Vector2(0f, 10f) the opposite of the examples in the box2d manual where gravity is Vector2(0f, -10f). This may create some confusion when trying to understand the following code.

Another thing that may be not so clear at first sight is the formulas to transform the y axis to the coordinate system of the graphics API. I know I could use matrices to invert the coordinates of the graphics API but I found simpler this method.

What matters most is the implementation of the shouldCollide method from the ContactFilter interface.

To run the example provided, some assets are needed. They are public domain. Filenames that the game expects included. They must be placed in directory `core/assets`.

hard\_block.png

platform.png

platform\_left.png

platform\_left\_corner.png

platform\_left\_corner\_background.png

platform\_right.png

platform\_right\_corner.png

platform\_right\_corner\_background.png

platform\_up.png

The player sprite is controlled by the Left, Up and Right keys. There is no jump, the Up key adds impulse to fly like using a jet pack so you can fly through the game level.

Use gdx-setup.jar to create a new libGDX project. Don't forget to enable box2d.

In the MyGDXGame.java file, replace everything for this (com.mygdx.game was used as package name, rename it if you used a different name in the libGDX wizard):

```
package com.mygdx.game;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.ContactFilter;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.utils.TimeUtils;

public class MyGdxGame extends ApplicationAdapter implements ContactFilter {
        public class Entity
        {
            public String mName = "";
            public int mContacts = 0;
            public Fixture mFixture = null;
        }

        public class TileDef {
            Texture image;
            //BodyDef body;
        }

        double mCurrentTime = 0;
        double mTimeStep = 1.0/60.0;
        double mMaxFrameTime = mTimeStep * 4;
        SpriteBatch batch;
    World mWorld;
        Vector2 mGravity;
        String mLevel;
        int mLevelWidth;
        int mLevelHeight;
        int mTileSize = 32; // pixels
        int mCameraLeft = 0;
        int mCameraTop = 0;
        float mBackgroundColor [] = {222f/255f, 243f/255f, 250f/255f, 1f};
        Entity mPlayerEntity;

        TileDef mTiles [];

        @Override
        public boolean shouldCollide(Fixture fa, Fixture fb) {
            Fixture player_fixture = null;
            Fixture tile_fixture = null;
            int tile_x = 0;
            int tile_y = 0;

            Fixture fixtures [] = {fa, fb};

            for (int f = 0; f < fixtures.length; ++f)
            {
                if (fixtures[f].getBody().getType() == BodyType.DynamicBody)
                {
                    // Then this is the player
                    player_fixture = fixtures[f];
                } else
                {
                    // Then this is a solid tile of the game level
                    tile_fixture = fixtures[f];
                    Vector2 vec = fixtures[f].getBody().getPosition();
                    tile_x = (int)vec.x;
                    tile_y = (int)vec.y;
                }
            }

            char tile_type = mLevel.charAt(tile_y * mLevelWidth + tile_x);

            if (tile_type == '-' || tile_type == 'o' || tile_type == 'O' || tile_type == '<' || tile_type == '>')
            {
                // Remember, positive y is down, negative y is up

                if (player_fixture.getBody().getLinearVelocity().y <= 0 ||
                    player_fixture.getBody().getPosition().y >= tile_fixture.getBody().getPosition().y)
                    return false;
            }

            return true;
        }

        public float getBoxWidth(PolygonShape shape) {
            float result = 0f;

            if (shape.getVertexCount() != 4)
                return 0f;

            Vector2 vec1 = new Vector2();
            Vector2 vec2 = new Vector2();

            for (int i = 0; i < 4; ++i)
            {
                shape.getVertex(i, vec1);

                for (int j = 0; j < 4; ++j)
                {
                    shape.getVertex(j, vec2);

                    if (vec2.y == vec1.y)
                    {
                        float d = Math.abs(vec2.x - vec1.x);
                        if (d > result)
                            result = d;
                    }
                }
            }

            return result;
        }

        public float getBoxHeight(PolygonShape shape) {
            float result = 0f;

            if (shape.getVertexCount() != 4)
                return 0f;

            Vector2 vec1 = new Vector2();
            Vector2 vec2 = new Vector2();

            for (int i = 0; i < 4; ++i)
            {
                shape.getVertex(i, vec1);

                for (int j = 0; j < 4; ++j)
                {
                    shape.getVertex(j, vec2);

                    if (vec2.x == vec1.x)
                    {
                        float d = Math.abs(vec2.y - vec1.y);
                        if (d > result)
                            result = d;
                    }
                }
            }

            return result;
        }

    @Override
    public void create () {
            batch = new SpriteBatch();

            // For compatibiliy with our level format, positive y is down.
            // That means that we need a positive gravity vector, the opposite
            // of the examples in the Box2D manual.
            mGravity = new Vector2(0, 10);

            // Create the physical world for our simulation
            mWorld = new World(mGravity, true);
            mWorld.setContactFilter(this);

            //mTileShape = new PolygonShape();

            // Define a test level
            // TODO: load levels from a file. Some loadLevel() function.

            // A brief on our level format
            //   '#' is impassable tile
            //   '(' and ')' are tiles passable by the side
            //   '-' is a plataform that only collide with player when falling, you can pass if coming from below and you cannot if coming for above.
            //   'P' is the starting point of the player. After the player sprite is created it will be replaced by an empty tile ' '

            mLevel = "####################################################";
            mLevelWidth = mLevel.length();
            mLevel +="#                                                  #";
            mLevel +="#                ############                      #";
            mLevel +="#                                                  #";
            mLevel +="#   ######                                         #";
            mLevel +="#                                  <------>        #";
            mLevel +="#                                  (******)        #";
            mLevel +="#                                  (******)        #";
            mLevel +="#                                  (******)        #";
            mLevel +="#          <----->             #################   #";
            mLevel +="#          (*****)                                 #";
            mLevel +="#          (****O--->                              #";
            mLevel +="#          (****(***)                              #";
            mLevel +="#     <---------o***)                              #";
            mLevel +="# P   (*********)***)                              #";
            mLevel +="#   <----o******)***)     ####                     #";
            mLevel +="#   (****)******)***)   ######       #####         #";
            mLevel +="####################################################";
            mLevelHeight = mLevel.length() / mLevelWidth;

            // Build the tile palette
            mTiles = new TileDef [256];
            mTiles['#'] = new TileDef();
            mTiles['#'].image = new Texture("hard_block.png");

            mTiles['('] = new TileDef();
            mTiles['('].image = new Texture("platform_left.png");

            mTiles[')'] = new TileDef();
            mTiles[')'].image = new Texture("platform_right.png");

            mTiles['-'] = new TileDef();
            mTiles['-'].image = new Texture("platform_up.png");

            mTiles['*'] = new TileDef();
            mTiles['*'].image = new Texture("platform.png");

            mTiles['<'] = new TileDef();
            mTiles['<'].image = new Texture("platform_left_corner.png");

            mTiles['O'] = new TileDef();
            mTiles['O'].image = new Texture("platform_left_corner_background.png");

            mTiles['>'] = new TileDef();
            mTiles['>'].image = new Texture("platform_right_corner.png");

            mTiles['o'] = new TileDef();
            mTiles['o'].image = new Texture("platform_right_corner_background.png");

            // Physicalize world
            for (int tile_y = 0; tile_y < mLevelHeight; ++tile_y)
            {
                char prev_tile_type = '\0';
                Body prev_body = null;

                for (int tile_x = 0; tile_x < mLevelWidth; ++tile_x)
                {
                    char tile_type = mLevel.charAt(tile_y * mLevelWidth + tile_x);

                    if (tile_type == ' ')
                    {
                        // We do nothing
                        prev_body = null;
                    } else
                    if (tile_type == 'P')
                    {
                        prev_body = null;

                        // Create the player and replace for an empty tile ' '
                        mLevel = mLevel.replace('P', ' ');

                        BodyDef bdef = new BodyDef();
                        bdef.type = BodyType.DynamicBody;

                        // As in classic platformers, we want the player sprite
                        // to modify its position in response to forces, not
                        // its rotation. Other objects of the game, like falling
                        // boxes, may be fully physicalized.
                        bdef.fixedRotation = true;
                        bdef.position.x = tile_x + 0.5f;
                        bdef.position.y = tile_y + 0.5f;

                        // Note: for this example we use the tile shape to create
                        // the player fixture too. But the idea is that in the
                        // real game entities like the player will have varying
                        // shapes.
                        Body body = mWorld.createBody(bdef);

                        FixtureDef fd = new FixtureDef();
                        fd.density = 1;
                        fd.friction = 0.3f;
                        fd.shape = new PolygonShape();
                        ((PolygonShape)fd.shape).setAsBox(0.5f, 0.5f);

                        Fixture f = body.createFixture(fd);

                        mPlayerEntity = new Entity();
                        mPlayerEntity.mName = "Player";
                        mPlayerEntity.mFixture = f;
                    } else
                    if ("<->oO#".indexOf(tile_type) > -1)
                    {
                        // If the tile is part of a continuous line of the same
                        // type, then expand the previous body, do not create
                        // a new body. This is necessary to avoid a glitch many
                        // physics engines have when the world is built on blocks.
                        // The player sprite may collide with the side of the
                        // next tile even if the expected result is that it stays
                        // stepts into the next tile, resulting in the player
                        // sprite getting stuck between tiles.

                        if (prev_tile_type == tile_type || ("<->oO".indexOf(tile_type) > -1 && "<->oO".indexOf(prev_tile_type) > -1))
                        {
                            float prev_width = getBoxWidth((PolygonShape)prev_body.getFixtureList().first().getShape());
                            float prev_height = getBoxHeight((PolygonShape)prev_body.getFixtureList().first().getShape());
                            prev_body.destroyFixture(prev_body.getFixtureList().first());
                            PolygonShape shape = new PolygonShape();
                            shape.setAsBox((prev_width + 1f) / 2f, prev_height / 2f);
                            prev_body.createFixture(shape, 0);
                            prev_body.setTransform(prev_body.getPosition().add(0.5f, 0f), 0f);
                        } else
                        {
                            float vertical_extent = 0.5f; // half the desired height
                            if ("<->oO".indexOf(tile_type) > -1)
                            {
                                vertical_extent = 0.03f / 2f; // a very slim box
                            }

                            BodyDef bdef = new BodyDef();
                            bdef.allowSleep = true;
                            bdef.type = BodyType.StaticBody;
                            bdef.fixedRotation = true;
                            bdef.position.set(tile_x + 0.5f, tile_y + vertical_extent);
                            Body body = mWorld.createBody(bdef);

                            PolygonShape shape = new PolygonShape();
                            shape.setAsBox(0.5f, vertical_extent);
                            body.createFixture(shape, 0);

                            prev_body = body;
                        }
                    }

                    prev_tile_type = tile_type;
                }
            }

            mCurrentTime = TimeUtils.millis() / 1000.0;
    }

    @Override
    public void render () {
            Vector2 linear_vel = mPlayerEntity.mFixture.getBody().getLinearVelocity();

            double new_time = TimeUtils.millis() / 1000.0;
            double frame_time = new_time - mCurrentTime;
            mCurrentTime = new_time;

            if (frame_time > mMaxFrameTime)
                frame_time = mMaxFrameTime;

            while (frame_time >= mTimeStep)
            {
                if (Gdx.input.isKeyPressed(Input.Keys.LEFT))
                {
                    if (linear_vel.x > -10f)
                        mPlayerEntity.mFixture.getBody().applyForceToCenter(-10f, 0f, true);
                }

                if (Gdx.input.isKeyPressed(Input.Keys.RIGHT))
                {
                    if (linear_vel.x < 10f)
                        mPlayerEntity.mFixture.getBody().applyForceToCenter(10f, 0f, true);
                }

                if (Gdx.input.isKeyPressed(Input.Keys.UP))
                {
                    mPlayerEntity.mFixture.getBody().applyForceToCenter(0, -20f, true);
                }

                mWorld.step((float)mTimeStep, 6, 2);
                frame_time -= mTimeStep;

                mCameraLeft = (int)(mPlayerEntity.mFixture.getBody().getPosition().x * (float)mTileSize - (float)Gdx.graphics.getWidth() / 2f);
                if (mCameraLeft < 0)
                    mCameraLeft = 0;
                if (mCameraLeft + Gdx.graphics.getWidth() > mLevelWidth * mTileSize)
                    mCameraLeft = (int)(mLevelWidth * mTileSize - Gdx.graphics.getWidth());

                mCameraTop = (int)(mPlayerEntity.mFixture.getBody().getPosition().y * (float)mTileSize - (float)Gdx.graphics.getHeight() / 2f);
                if (mCameraTop < 0)
                    mCameraTop = 0;
                if (mCameraTop + Gdx.graphics.getHeight() > mLevelHeight * mTileSize)
                    mCameraTop = (int)(mLevelHeight * mTileSize - Gdx.graphics.getHeight());
            }

            Gdx.gl.glClearColor(mBackgroundColor[0],
                                mBackgroundColor[1],
                                mBackgroundColor[2],
                                mBackgroundColor[3]);

            Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
            batch.begin();

            // If you don't understand what happens with the y coordinate during
            // rendering, remember that we are using a positive y for down then
            // you will understand the formulas.

            for (int y = 0; y < Gdx.graphics.getHeight() / mTileSize + 2; ++y)
            {
                int y_offset = mCameraTop - mCameraTop / 32 * 32;

                for (int x = 0; x < Gdx.graphics.getWidth() / mTileSize + 1; ++x)
                {
                    int x_offset = mCameraLeft - mCameraLeft / mTileSize * mTileSize;

                    int tile = (y + mCameraTop / 32) * mLevelWidth + (x + mCameraLeft / 32);
                    if (tile >= mLevel.length())
                        break;

                    if (tile < 0)
                        continue;

                    char tile_char = mLevel.charAt(tile);

                    if (tile_char != ' ')
                    {
                        batch.draw(mTiles[mLevel.charAt(tile)].image, x * mTileSize - x_offset, Gdx.graphics.getHeight() - y * mTileSize + y_offset);
                    }
                }
            }

            // Draw the player sprite
            if (mPlayerEntity != null)
            {
                Vector2 pos = mPlayerEntity.mFixture.getBody().getPosition();
                batch.draw(mTiles['#'].image, ((pos.x - 0.5f) * (float)mTileSize) - (float)mCameraLeft, Gdx.graphics.getHeight() - ((pos.y - 0.5f) * (float)mTileSize) + (float)mCameraTop);
            }

            batch.end();
    }
}

```

The example has some issues and if you insist enough when playing with it you will trigger them sooner or later.

Conclusion: I was testing box2d with the intention to use it in a platformer and reached the conclusion that box2d is what you need when making a clone of Angry Birds, but is not the library for a platformer game like Mario Bros (IMHO).

I find simpler to just implement AABB and any needed functionality to detect collisions and calculate penetration vectors between two AABB. box2d doesn't come in a way that let you just use it for collision detection, it is meant to completely control the physics simulation of the game (as probably most physics engines/libraries). So I would only enable a full physics simulation at specific parts of a game level, and use a simpler collision detection during the rest of the game, applying the gravity in the main loop.
> 1 votes

# Answer
I think that the most simple way of getting around your problem is as follows. I assume that your player entity helps you keep track of his state. Maybe it's *running*, or *climbing* or whatever you might have used. If you add to make sure that the only time you will ever check if the player sprite is on top of an enemy is when the player's state is falling, your problem should be solved.

I hope this helps.
> 0 votes

---
Tags: java, libgdx, box2d, platformer
---


# Question
Title: Loading non-skeletal animation to opengl via assimp
I'm a newbie in assimp and openGL. I'm trying to import .fbx or .dae formatted file to openGL via assimp. Importing skeletal animation was kind of easy. Lots of introductions and sample projects helped me to run several files properly. But, in case of none skeletal animation(does it named 'vertex animation'?), which has no bone, I can't find any of source, instructions, including assimp tutorials. Or, I'm not sure it is even possible, maybe assimp doesn't support this kind of animation. Is there any recommendable project for non skeletal animation? Any single comment, will be helpful. Thanks.

# Answer
It is actually easier than you think. The way this works is really simple, it is a lot like video.

So, when you watch a video(I am sure you know this already but just as a reminder) you are not actually watching a moving image, instead you are watch a lot of images getting displayed one after the other REALLY fast, faster than your eye can see(There is a video from gamespot called "Do we need 60 fps" if you are interested).

Non-skeletal animation works in the same way. Let's say you have an animation with 240 frames, and each frame is a file in a directory. Let's also say that your computer runs at 60 fps. All you have to do is, for every next frame load the next model frame and draw that. In simple words, each time you draw to the screen you move to the next model frame.

But, this is only if you are running at 60fps. If you are running at lower fps, like 30fps, the animation will appear to slow down. I will not explain this a lot because since you have already done skeletal animation, I assume that you have dealt with this problem. Solution: find out have much time has passed since the last frame and if that is bigger than the time that each animation frame takes, move to the next frame. Some thing like this:

```
 int framesToMove = (int)((lastFrameTime - currentFrameTime) / animFrameTime)

```

If you do not understand, ask me.

**Advantage**: A lot more performance friendly, than skeletal animation.

**Disadvantage**: Requires A LOT more memory.

**Recommendation**: Use skeletal animation for complicated animations, like character movement, and for animation with complicated models that have many vertices, and use non-skeletal animation for simpler models, like a gate opening animation.

Here is some example code:

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

Assimp::Importer importer;

const aiScene* scene = importer.ReadFile(("./res/models/" + fileName).c_str(), aiProcess_Triangulate | aiProcess_GenSmoothNormals |  aiProcess_FlipUVs |  aiProcess_CalcTangentSpace);

if(!scene) {
    std::cout << "Mesh load failed!" << std::endl;
}

const aiMesh* model = scene->mMeshes[0];

std::vector<Vector3f> positions;
std::vector<Vector2f> texCoords;
std::vector<Vector3f> normals;
std::vector<Vector3f> tangents;
std::vector<unsigned int> indices;

for(unsigned int i = 0; i < model->mNumVertices; i++) {
    const aiVector3D pos = model->mVertices[i];
    const aiVector3D normal = model->mNormals[i];
    const aiVector3D texCoord = model->HasTextureCoords(0) ? model->mTextureCoords[0][i] : aiVector3D(0.0f, 0.0f, 0.0f);
    const aiVector3D tangent = model->mTangents[i];

    positions.push_back(Vector3f(pos.x, pos.y, pos.z));
    texCoords.push_back(Vector2f(texCoord.x, texCoord.y));
    normals.push_back(Vector3f(normal.x, normal.y, normal.z));
    tangents.push_back(Vector3f(tangent.x, tangent.y, tangent.z));
}

for(unsigned int i = 0; i < model->mNumFaces; i++) {
    const aiFace& face = model->mFaces[i];
    assert(face.mNumIndices == 3);
    indices.push_back(face.mIndices[0]);
    indices.push_back(face.mIndices[1]);
    indices.push_back(face.mIndices[2]);
}

```
> 2 votes

---
Tags: opengl, animation, vertex, assimp
---


title: Unity 2D C# Enemy Attackng Ai issue

text:
# Question
Title: Unity 2D C# Enemy Attackng Ai issue
> Ok to be specific, both of my enemies will continuously play their attack animation even when it is false. I don't understand what I am doing wrong here :(

```
void OnTriggerEnter2D(Collider2D other){
    //If attack collider is player and we're not attacking
    if (other.name == "Player" && !attacking) {
        attacking = true;
        attackTimer = attackCD;
    }
    if (attacking)
    {
        if (attackTimer > 0)
        {
            Debug.Log ("Decreasing");
            attackTimer -= Time.deltaTime;
        }else if (attackTimer == 0)
          {
            attacking = false;
            Debug.Log ("Done attacking!");
            //attackTimer = attackCD;
          }
    }
}

anim.SetBool ("Attack", attacking);//This sets the animation but it is in my Update function not my OnTriggerEnter2D function

```

# Answer
It could be that the attack timer never reaches 0 as the delta time will keep removing time which will eventually cause it to go negative. Instead check if the timer is less then or equal to 0 so if it goes negative the attack animation is stopped.

```
else if (attackTimer <= 0f)

```

Note: You should add an "f" behind numbers that you want to be floats because without the "f" the compiler thinks that you want a double which could waste memory if you have lots of them without needing the extra precision.
> 2 votes

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


title: How do I avoid writing Manager classes?

text:
# Question
Title: How do I avoid writing Manager classes?
I seem to keep reading it's a bad idea to use `XxxManager` style classes in game engine programming, yet even when I try to avoid their use I always end up with something that holds all the actors/entities/game world locations and acts upon them, which ends up being a `Manager` if by another name.

Is this really a bad pattern to follow? If so, what are the alternatives?

# Answer
"Manager" classes *can* be problematic for various reasons. The two key reasons tend to be:

* the name is unclear (what *actually* does "management" entail, and is it always the same for every type of thing being managed?)
* they tend towards being buckets of functionality that violate the single responsibility principle (that is, that a type should do one thing)

Often one of those reasons causes or implies the other.

Those issues are good things to keep in mind, but don't them let paralyze your ability to actually *make your game*. In the end nobody is going to care what your classes are called or what they do. They're going to care about your game.

It's usually pretty easy to separate most "managers" into two parts:

* the part that stores the actual objects and provides access to them (which you can call a "store," a "repository," a "database," a "cache," or various other things. This is the type that is usually responsible for the lifetime of the objects; that is, when an object is removed from or otherwise no longer contained by an instance of this type it ceases to exist.
* the part that *processes* the actual objects and performs some work on them. It might update those objects (then it's an "updater" or "simulation") or it might draw them (then it's a "drawer" or "renderer"). Or it might do something else with them; the important thing is to name it according to its primary purpose. You'd generally give instances of this type a instance of or reference to instances of the first type (the one that just handles lifetime of the objects).

A reasonable argument *could* be made that the name of the first type could include manager (as it "manages the lifetime of" some objects). The world will not end if you name your type thusly, although you may need to put up with knee-jerk reactions of the form "don't call things managers" rather often, so you may want to avoid it just for that.
> 10 votes

# Answer
When you read the blog post you linked to in the comments, then you will see that "being a Manager if by another name" is exactly what it wants you do to. It's general consensus in software development that global variables are evil, and the only alternative is that any data is held by other data.

The problem with a class named `FoobarManager` is that the word "Manager" doesn't tell you what the class *actually* does. For example:

* When it controls the game mechanics of the foobars, you can name it `FoobarController`.
* When it instantiates foobars but then delegates control to something else, it's a `FoobarFactory` or `FoobarBuilder`.
* When it draws the foobars to the screen, it's a `FoobarRenderer`.
* When it listens to events generated by foobars, it's a `FoobarEventHandler`.
* When it waits for something to happen with the foobars, it's a `FoobarObserver`.
* When it's just a dumb data holder for a collection of foobars without any logic at all, you just name it `Foobars`.

You could name any of these classes "Manager". But then it could perform any of these functionalities. And when you later realize that you need another of the above functionalities, you will also integrate that into the FoobarManager. So you will end up with a God Object which breaks the Separation of Concerns principle (every class should do exactly one thing).
> 6 votes

---
Tags: architecture, software-engineering, design-patterns
---


# Question
Title: How can I facilitate communication between "attack" and "movement" components?
I'm currently programming in Unreal, but this is more of a component oriented design question.

I'm trying to follow a component driven aproach, and I have currently achieved creating a movement component which gets connected to the character object, it can do the following (apart from the usual walk, jump behaviour)

* WallSlide/WallClimb (like parkour) on Walls that the character cannot climb.
* Ledge Grab when reaching the apex of a wall, the character will start grab the ledge and climb to the end so he can be on top of the ledge.
* Hook Movement Implementation: you set a target point and the movement component will make the character travel to that point, triggering an event when it reaches the destination or it's interrupted by something in it's journey

The problem is that I'm right now trying to figure where and how to put the "attack" actions of the character. Say I make an Attack component, how do I deal with the weapon or attack wanting to move the character while the movement component is wanting to do the same thing (think of a shoryuken or a stinger)?

The thing that confuses me is that the movement is the domain of the movement component, and adding the movement logic of the combo breaks the decoupling of the modules, if I have to program the movement component thinking of the attack component.

I know this is an abstract question and i have asked it aroud everywhere, but I just cannot find some good material on how to approach this, every place I check, they use some "patch like" programing where they program directly to the character and don't worry decoupling the behavior.

# Answer
> 1 votes
One way to approach this is to have some facility for components that don't normally deal with movement to *request* of the appropriate that a movement occur.

If you're using a message-passing approach to talk between components, you'd just fill out a `RequestMovement` message with information about the desired movement or animation and send it off, and the movement component would trap and respond to it.

In Unreal's case, the component architecture it uses allows you to directly obtain a reference to the movement component from the attack component, and so you could just call `myMovementComponent->RequestStartMovement(WhateverMovement)`.

The `RequestStartMovement` function can check to see if the character's current locomotion state allows for the requested movement to begin, and if so, begin the motion. One advantage of this approach versus the message-passing approach is that `RequestStartMovement` can immediately return a value indicating if the request was approved, so your attack component can (for example) abort the rest of its attack processing if the required motion could not be started for some reason.

This implies that your "movements" must be factored out into data or at least into some fashion where there are unique identifiers for each movement or animation you'd want to be able to request so that components can refer to them without having to know anything more about the movement other than the fact that it exists under a given name (in the past I've used Blueprint enumerations for this; they are trivial to extend as data and can be correlated to animations or more complex motion scripts fairly easily).

---
Tags: component-based, design-patterns, unreal-4, data-driven
---


# Question
Title: How to calculate 2D viewport coordinates in a shader?
In Unity, I use the following shader to calculate 2D viewport coordinates :

```
Shader "Foo"
{
    SubShader
    {
        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            struct vertInput {
                float4 pos : POSITION;
            };

            struct vertOutput {
                float4 pos : SV_POSITION;
                float4 uv : TEXCOORD0;
            };

            vertOutput vert (vertInput input)
            {
                vertOutput o;
                o.pos = mul(UNITY_MATRIX_MVP, input.pos);
                o.uv = mul(UNITY_MATRIX_MVP, input.pos);
                return o;
            }

            fixed4 frag (vertOutput output) : SV_Target
            {
                float2 viewport = output.uv.xy / output.uv.z;
                return float4(sin(viewport.x*10.0), sin(viewport.y*10.0), 0.0, 1.0);
            }
            ENDCG
        }
    }
}

```

At first, it seems to work great. Here is results :

However if I move camera very close to the surface, the following unexpected glitch occurs :

# Answer
> 1 votes
When the distance to the camera is really small, you can end up dealing with very small numbers which create floating point rounding errors in your calculations. If you change

```
o.uv = mul(UNITY_MATRIX_MVP, input.pos);

```

to

```
o.uv = mul(UNITY_MATRIX_MV, input.pos);

```

then the projection portion of the matrix will no longer be included in your calculations (for the uv component at least), which has the effect of making the distance to the camera irrelevant and removing that warping.

---
Tags: unity, shaders, viewport
---


# Question
Title: How to use Resources.Load with an AudioClip in Unity?
I'm trying to load an audio clip that's in my assets directory and play it. Here is my C# script:

```
if (Input.GetKeyDown(KeyCode.X))
 {
     audioSource = gameObject.GetComponent<AudioSource>();
     Debug.Log((audioSource == null) ? "Audio source is null" : "Audio Source is not null");
     string path = "Sounds/Aurora/Aurora_IGSSin";
     Debug.Log(path);
     sound = (AudioClip)Resources.Load(path, typeof(AudioClip)) ;
     Debug.Log((sound == null) ? "Sound is null" : "Sound is not null");
 }

//Output:
//Audio source is not null
//Sounds/Aurora/Aurora_IGSSin
//Sound is null

```

There is an AudioSource component attached to this object, as proved by the first Debug.Log(). Attached is a picture of my folder, proving that the file path is correct. I've seen 90 different posts and tried this 81 different ways, including using the file extension in the path, omitting the directory and only including the file name, omitting (AudioClip) before Resources.Load(), using as AudioClip rather than typeof(AudioClip) and none of it has worked.

Please, someone help me before I pull my hair out over this. I'm incredibly flustered over being stuck on something that should be so simple, and I'd like to get on with my project.

My Project Directory:

# Answer
> 3 votes
```
Resources.Load()

```

requires that you have a `Resources` directory as a chils of the `Assets` directory where you put everything that has to be loaded with that method.

In your case create a `Resources` directory and then move in your `Sounds` directory.

EDIT: the you can simplify your call in this way

```
sound = Resources.Load<AudioClip>(path);

```

---
Tags: unity, c#, assets, sound
---


# Question
Title: Full Engine or Not: C++ Programmer Trying to get into Game Development
I'm a fairly experienced programmer, and I want to try out doing some game development. However, I am unsure of whether or not to use a full engine like Unity or just start with something like OpenGL. How much flexibility/extensibility do you use going with Unity. I know it can be used with minimal coding, but if you can write your own code, will it constrain you later down the line? For my first project I want to just build a simple tile based rpg and build it up to something larger. Any advice is welcome.

# Answer
> 1 votes
There are only a couple of coding related restrictions:

1. Unity is not (very) mulit-threaded.
2. You don't get direct access to the app's starting point or it's core rendering loop.
3. You can't call core windows or other OS specific libraries easily (because it's cross platform).

Other than that, you have almost the entire scope of .net 3.5 (C# and a version of javascript only.. and boo, but no one uses that) to work in.

---
Tags: unity, opengl
---


# Question
Title: Where should I store an object? - QuadTree
I'm designing a QuadTree to scene partitioning, I've read theory and seen some code examples.

When a node has more than 4 objects, it will be splitted into 4 sub-nodes and its objects will be put into them, but if an object is on the edges of any sub-node, it will be placed in the parent node. **Why should I do this?**

I think it's better put it on every sub-node where it's colliding. **Am I wrong?**. I've designed a pattern to achieve this ;).

# Answer
There are multiple solutions to this problem. You can place the object in the smallest node which fully contains it. You can split its edges among multiple nodes and tag them with which object they belong to. Another solution is to use a "loose" quadtree. The idea with a loose quadtree is that the nodes are larger than in a normal quadtree, such that they overlap. This means that you can hold larger objects further down the tree. Usually you choose which node to place an object in with a loose quadtree according to the coordinates of its origin.
> 2 votes

# Answer
One chief concern of putting the object in *every* leaf node it occupies instead of the inner node that actually contains it is that, when traversing the tree, you have to track whether you have visited that object before or not. Consider the following case:

A large box spans four leaf nodes, and you are testing if a smaller sphere that straddles two leaf nodes intersects it. Unless you keep track of all the objects you have already collided with you will end up colliding the sphere against the box twice. If, instead, the large box is in the parent node that fully encloses it, you only collide with it once on the way done the tree.

If you have an efficient way of managing this (and there are some) then it is not as important to worry about whether you chose an object in leaf nodes, or object in inner node approach.
> 1 votes

---
Tags: quadtree, space-partitioning
---


# Question
Title: How to avoid 2d enemy using trigonometry?
I'm making a game in Javascript & HTML5.

I have a "bullet" (let's call it so) that needs to reach the enemy (at fixed position) and that need to avoid the enemy's "bullet".

To make the bullet move to the enemy i'm using this code:

```
var direction = Math.atan2(self.enemy.y - self.y, self.enemy.x - self.x);
var dir_diff = self.rotation - direction;
// ... other code
self.rotation -= dir_diff;
self.x += Math.cos(self.rotation) * self.speed / dt;
self.y += Math.sin(self.rotation) * self.speed / dt;

```

How can I make the bullet avoid another moving bullet?

I tried to search but algorithms like A\* etc. doesn't seem right for this.

Thank you.

# Answer
```
/* Detect nearest enemy */
for (var i = 0; i < nears.length; i++) {
    /* self.void is an array containing the types of objects I want to avoid */
    if (self.avoid.indexOf(nears[i].type) > -1 && nears[i] != self) {
        var dist = Math_distance(nears[i].x, nears[i].y, self.x, self.y);
        if (dist > self.avoidRadius) continue;
        if (dist < near_dist || near_dist == null) {
            near_i = i;
            near_dist = dist;
        }
    }
}

if (near_i != null) {

    var avoid_direction = Math.atan2(nears[near_i].y - self.y, nears[near_i].x - self.x);
    var avoid_diff = self.rotation - avoid_direction + Math.PI;
    if (avoid_diff > Math.PI / 5) {
        avoid_diff = Math.PI / 5;
    }
    if (avoid_diff < -Math.PI / 5) {
        avoid_diff = -Math.PI / 5;
    }

    /* Delta, frame rate */
    avoid_diff /= dt;

    /* Strength of the avoid force */
    var strength = 1 / near_dist * 100;

    dir_diff += avoid_diff * self.avoidForce * strength * self.avoidSign;
}

```

Thanks to PRDeving for the idea of "steering". This works for me.
> 0 votes

---
Tags: path-finding, html5, trigonometry
---


# Question
Title: LibGDx android : Show animation on button click
I am trying to create an application using libgdx where i need an animation to be played on pressing an image button, i've been able to achieve it using this code

```
   if(slapBossFlag==true) {
        currentFrame = animation.getKeyFrame(timePassed, true);
            batch.begin();
            timePassed += Gdx.graphics.getDeltaTime();
        Gdx.app.log("time","time is"+timePassed);
            batch.draw(currentFrame, screenWidth / 2 - ((currentFrame.getRegionWidth()) / 2), screenHeight / 2 - ((currentFrame.getRegionHeight()) / 2));
            batch.end();
            slapBossFlag = false;
    }

```

the problem is the animation goes by too quickly.

i've tried setting timePassed to zero when slapBossFlag is false, and that didnt work.

Can anyone help?

# Answer
You missuse the animation class.

you need to do the following:

```
currentframe = animation.getKeyFrame(Gdx.graphics.getDeltaTime(), true);

```

Currently you use an increasing time for your time passed. which is wrong, the animation class handles the passed time by itself.

Easier explained: Imagine a cake. If you eat constantly 3 percent you'll see it fade slowly away(what you want). On the other hand If you eat first 3 percent, than 6 percent and than 9 percent(what you have) the animation is fked up.
> 1 votes

---
Tags: android, libgdx, android-studio
---


# Question
Title: LIBGDX font.draw() makes letters blink on PC
I load Bitmapfont then try to draw it, but on PC(desktop) build screen blinks with frequecy that I can judge that backbuffer is not drawn. On Android all is fine, I don't see blinking. I simply do this:

```
SpriteBatch = new SpriteBatch();
Bitmapfont font = new Bitmapfont();
font.setColor(Color.GREEN);
spriteBatch.begin();
font.draw(spriteBatch, "Hello world", 0, 100);
spriteBatch.end();

```

Ways to fix?

# Answer
> 1 votes
Do you have called that in your render method:

```
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

```

Because, it looks like your code should work.

We figured out, that he needed to disable, because he wanted to draw the Screen on demand

"continuus rendering" https://github.com/libgdx/libgdx/wiki/Continuous-%26-non-continuous-rendering

---
Tags: java, libgdx
---


# Question
Title: Optimizing black and white matrix block drawing
Disclaimer: I am uncertain if this is the best place to post this question, so please advise me of how I can best find the answer if I am doing something wrong. I am asking this question because I am trying to optimize a drawing function of a PC game I am programming.

Preface: There is a matrix of blocks, that can be either on (black) or off (white). There will be different colors, but for the sake of simplicity I am presenting the problem to you as black and white only, so please imagine this matrix forming some random pattern like a QR code which would be a good example.

Problem: Instead of drawing each black block individually, I want to determine how to draw all black blocks using as minimum calls to my draw black rectangle function as possible.

Question: Is there any existing process that I can refer to so as to make my drawing process as efficient as possible, or how would I logically go about tackling this conundrum?

Edit: Tried to produce some example code for us to play with

```
std::vector<std::vector<bool>> matrix;

int width = 100;
int height = 100;

matrix.resize(height);

for(int h = 0; h < height; h++)
{
    matrix[h].resize(width);
    for(int w = 0; w < width; w++)
    {
        matrix[h][w] = random 1/0
    }
}

void draw()
{
    .. draw matrix using a minimum amount of calls to draw_rectangle
}

void draw_rectangle(int x, int y, int width, int height)
{
    .. draws a set of black blocks
}

```

# Answer
> -2 votes
There are two really good tutorials on the internet about how to improve performance, both by a guy called ThinMatrix. The first is mostly what you are looking for, but if you want to make it SUPER efficient you can also take a look at second one:

First: https://youtu.be/X6KjDwA7mZg Second: https://youtu.be/Rm-By2NJsrc

---
Tags: opengl, c++, mathematics, matrix, logic
---


# Question
Title: Why is my depth buffer texture so bright?
https://www.youtube.com/watch?v=QuvAEqgHrMY&feature=youtu.be

https://www.youtube.com/watch?v=5ob1JsPIGAs&feature=youtu.be

```
gluPerspective(60, (float)CONTEXT_WIDTH / CONTEXT_HEIGHT, 0.1f, 1.f); //values used for first video
gluPerspective(60, (float)CONTEXT_WIDTH / CONTEXT_HEIGHT, 0.1f, 2000.f);//values used for second video, the further z clip value seems to improve the depth rendered, but far from example images below.

```

I set my projection matrix with gluPerspective.

This seems to happen when I try gluPerspective; when I set my projection matrix to first person.

The type of image I would like to get is

Is the visual result I am getting correct? Then are the listed examples of depth buffer images are merely a result of refining post rendering process, that are simply added in order for humans to see it better?

# Answer
Your depth buffer seems fine to me. The images you posted most likely have been normalized to make details more easily seen. This process consists of finding the maximum and minimum value of the depth buffer and remapping the color range onto that range. It is also linearized. Graphics debuggers have usually such an option to render the depth buffer (or even the stencil) like this.
> 1 votes

# Answer
The depth is stored from 0 to 1 (0 - closest, 1 - farthest) by default. Addition to that, depth in perspective projection is not linear, it looked something like this:

So it makes sense to me if it fades to white faster. Unless, you normalize it (see János Turánszki's answer).
> 4 votes

---
Tags: opengl, depth-buffer, depth
---


# Question
Title: How to stop reinitialization in Gamemaker Studio
**Situation:** This is a problem that I don't know if it is actually a problem yet: I've got initialization of variables like `food`, `stamina` and so forth, in an object called `obj_Global_Variables`, on its *Create Event*.

**Question:** How do I stop it from reinitializing said global variable each time the room is opened? (which, I assume, creates the objects in the room again).

# Answer
When you declare and initialize a variable in the *Create Event* of an object, such variable is not a **global** variable, but an **instance** one. That means, as it occurred to you, that every time the object is instantiated, its instance variables are set to their default value.

If you don't want such variables to be reinitialized every time the room starts, you can try two different approaches:

* **Global variables:** instead of having your `food`, `stamina`, and other variables declared in the *Create Event* of `obj_Global_Variables`, you can make them variables of the special object `global`. This way, they will be accessible by *any* instance of your application, and won't be reinitialized until you close and reopen your game manually, or the function `game_restart()` is executed. You can declare them in the *Game Start Event* of the very first instance created in the very first room ran in your game. Otherwise, you can put an instance in charge of declaring them in its *Create Event*, and make sure such code script is executed only once.
* **Persistent object:** you can make your object `obj_Global_Variables` persistent. A persistent object is not destroyed when moving from a room to another, thus restarting a room won't have such object being destroyed and instantiated once again. And that means its instance variables won't be reinitialized, and will store they current values until the instance is somehow destroyed. The `persistent` variable can be set both in the Object window and via GML code.

Both strategies are good enough for your goals, although many programmers discourage using global variables (not only in GM:S, but also in C, C++, Java, and many other programming languages) because of them being global. A global variable is accessible by *any* class or instance, and that means if you are not aware of code execution order among instances toward such variables, you may get unexpected results. On the other hand, if the only reason you are using global variables is not losing its value during execution, if only one instance at time is in charge of reading/writing such variables, then it would be acceptable to use them.

Also, never forget global variables in GM:Studio can't be deallocated, because you can't simply destroy the special instance `global`. So, make global as few variables as possible, or you'll be wasting memory space.
> 1 votes

---
Tags: game-maker
---


# Question
Title: Unity: When attaching my custom camera script camera shakes when player starts to move fast
Here is my player code.

```
Rigidbody rb;

Vector3 currMovement;
public float jumpSpeed = 10;
public float moveSpeed = 10;
public float rotSpeed = 180;

float distToGround;

public float posSmoothTime = 0.5f;
float currPos;
float targetPos;
float posVel;

public float rotSmoothTime = 0.5f;
float currRot;
float targetRot;
float rotVel;

void Start()
{
    rb = GetComponent<Rigidbody>();
    distToGround = GetComponent<Collider>().bounds.extents.y;
}

bool isGrounded() { return Physics.Raycast(transform.position, Vector3.down, distToGround + 0.1f); }

void Update()
{
    Move();
}

void Move()
{
    // Rotation smoothing.
    targetRot = Input.GetAxisRaw("Horizontal") * rotSpeed * Time.smoothDeltaTime;

    if (targetRot > 360)
        targetRot -= 360;
    if (targetRot < 0)
        targetRot += 360;
    currRot = Mathf.SmoothDampAngle(currRot, targetRot, ref rotVel, rotSmoothTime * Time.smoothDeltaTime);

    transform.eulerAngles += new Vector3(0, currRot, 0);

    // Movement smoothing.
    targetPos = Input.GetAxisRaw("Vertical") * moveSpeed;

    currPos = Mathf.SmoothDamp(currPos, targetPos, ref posVel, posSmoothTime * Time.smoothDeltaTime);
    currMovement = new Vector3(0, 0, currPos);
    currMovement = transform.rotation * currMovement;

    if (isGrounded())
    {
        if (Input.GetButtonDown("Jump"))
            rb.velocity += Vector3.up * jumpSpeed;
    }

    rb.position += currMovement * Time.smoothDeltaTime;
}

```

I have a Rigidbody attached to my player. I think the problem is with my camera script. Here is my camera script.

```
public Transform player;
Quaternion targetLook;
Vector3 targetMove;
public float smoothLook = 0.5f;
public float smoothMove = 0.5f;
public float distFromPlayer = 5, heightFromPlayer = 3;
Vector3 moveVel;

void LateUpdate()
{
    CameraMove();
}

void CameraMove()
{
    targetMove = player.position + (player.rotation * new Vector3(0, heightFromPlayer, -distFromPlayer));
    transform.position = Vector3.SmoothDamp(transform.position, targetMove, ref moveVel, smoothMove);

    targetLook = Quaternion.LookRotation(player.position - transform.position);
    transform.rotation = Quaternion.Slerp(transform.rotation, targetLook, smoothLook);
}

```

}

The player is not an parent of my camera. When I parent the player to my camera the shake stops. But I want a custom smooth camera movement with my custom scirpt, so I can't make the player a parent of the camera.

# Answer
> 1 votes
I fixed it :D. I just multiplied Time.deltaTime to smoothLook.

---
Tags: unity, c#, camera, movement
---


title: LWJGL Sys.getTimerResolution() value

text:
# Question
Title: LWJGL Sys.getTimerResolution() value
Tutorials wrote Sys.getTimerResolution() for LWJGL time method.

```
public long getTime() {
   return (Sys.getTime() * 1000) / Sys.getTimerResolution();
}

```

I thought Sys.getTimerResolution() is just 1000. So the shorter way gives same value.

```
// shorter way
public long getTime() {
   reutrn Sys.getTime();
}

```

Is Sys.getTimerResolution() value always 1000?

# Answer
After looking at the source code for LWJGL, the function `Sys.getTimerResolution()` is ***potentially*** different for every operating system. However, currently it is the same on every platform.

This function should not be assumed to be 1000 all the time as not every platform can provide the same time resolution as others (Although currently they do). To support future versions of LWJGL and cross-compatibility, you should use the first example you gave.

You are correct that the two values cancel each other out in the second example but as I said, this is done just in case the game runs on a platform with different time resolution in the future.

Currently, all platform implementations inherit `DefaultSysImplementation` which is where the value of *1000* is derived.
> 0 votes

---
Tags: lwjgl
---


# Question
Title: Libgdx change the image inside table dynamically
I am trying to draw a HUD that shows the score and time and image like loading but I want to update and change the image when the score get higher but I tried to do that but it is not working. I thought maybe I can define new table in the update method and put different image each time but I don't want to define new table each time. is there anyway to update the image only inside the table: this is the code:

```
public class Hud implements Disposable{

        public Stage stage;
        private Viewport viewport;
        private static Integer worldTimer;
        private float timecount;
        private static Integer score;
        Label countdownLabel;
        private static Label scorelabel;
        private Label timelabel;
        private Label levellabel;
        private Label worldlabel;
        private Label mariolabel;
        private Image loading;
        private Table table;
        public Hud(SpriteBatch sb)
        {
            worldTimer=40;
            timecount=0;
            score=0;
            viewport=new FitViewport(Fruits.V_WIDTH,Fruits.V_HIEGT,new OrthographicCamera());//2
            stage=new Stage(viewport,sb);//stage is as box and try to put widget and organize things inside that table
            table = new Table();
            table.top();//table at top of our stage
            table.setFillParent(true);//table is now fill all the stage
            countdownLabel=new Label(String.format("%02d",worldTimer),new Label.LabelStyle(new BitmapFont(), Color.BLACK));//label for gdx
            scorelabel=new Label(String.format("%02d",score),new Label.LabelStyle(new BitmapFont(), Color.BLACK));//label for gdx
            timelabel=new Label("TIME",new Label.LabelStyle(new BitmapFont(), Color.BLACK));//label for gdx
            levellabel=new Label("1-1",new Label.LabelStyle(new BitmapFont(), Color.BLACK));//label for gdx
            worldlabel=new Label("WORLD",new Label.LabelStyle(new BitmapFont(), Color.BLACK));//label for gdx
            mariolabel=new Label("Score"    ,new Label.LabelStyle(new BitmapFont(), Color.BLACK));//label for gdx
            loading = new Image(new Texture("10%.png"));
            //loading.setSize(40, 10);
            table.add(mariolabel).expandX().padTop(10);

            table.add(timelabel).expandX().padTop(10);
            table.add(worldlabel).expandX().padTop(10);
            table.row();
            table.add(scorelabel).expandX();

            table.add(countdownLabel).expandX();
            table.add(loading).width(50).height(10);

            stage.addActor(table);

        }
        public void update(float dt)
        {
            timecount+=dt;
            if (timecount>1)
            {
                worldTimer--;
                if(worldTimer>=0) {
                    countdownLabel.setText(String.format("%02d", worldTimer));
                    loading=new Image(new Texture("90.png"));
                }
                timecount=0;

            }
        }
        public static int getTime()
        {

            return worldTimer;
        }

        public static void addScore(int value)
        {
            score +=value;
            scorelabel.setText(String.format("%02d",score));
        }
        public static int getScore()
        {
            return score;
        }
        @Override
        public void dispose() {
            stage.dispose();
        }
    }

```

# Answer
Try changing the image using `setDrawable()` method:

```
loading.setDrawable(new TextureRegionDrawable(new TextureRegion(new Texture("90.png")));

```
> 1 votes

---
Tags: libgdx, textures, rendering, image
---


title: Touchpad Unity UI

text:
# Question
Title: Touchpad Unity UI
For my Unity game, I want a touch surface (UI Panel). I started implementing a MonoBehavious that should handle `touch-started`, `touch-ended`, `touch-moved/dragged` and `double-tap` with custom methods.

I read some forum posts and the scripting documentation, but I don't understand how have to do this.

Which base-class do I have to use? What methods should be implemented/ overridden?

# Answer
> 1 votes
Unity's standard UI elements respond to both touch inputs and mouse inputs.

If you want to implement custom events that trigger on touch, use the Input class. For instance, Input.touches returns all the touches that are currently happening at that instant.

---
Tags: unity, gui
---


# Question
Title: How to draw and give functions to multiple things at once?
I'm using plain JavaScript and I've bee coding a hardcore platformer game. I want there to be multiple enemies at once and before I write up the code I have a question. How do i approach that? Do I just have to draw and give function to the enemies each time or is there a easier way?

# Answer
> 2 votes
This is a very hard question to answer since there are many things which come into account when you have to deal with these things.

What I usually do, is that I set up an array for all my enemies. Each enemy is basically an object with values such as their coordinates, direction, sprites etc., and what's most important, a draw() and an update() function.

In my main game loop, I usually have two cycles. One for updating the behavior of the enemies based on the player's location for example, and the other to actually draw them onto the canvas.

```
//A simple enemy object
function simpleEnemy(){
    this.x;
    this.y;
    this.sprite;
    this.update=function(){
        //Any logic which decides where the enemy will be in the next frame
        //This, in the end, just updates the X and Y coordinates of this entity
    }
    this.draw=function(){
        ctx=gameArea.context;
        ctx.drawImage(this.sprite,this.x,this.y);
    }
}

//The main game loop
function updateArea(){
    gameArea.clear();
    //Any update and drawing function you have also comes here
    for(i=0;i<enemies.length;i++){
        enemies[i].update();
    }
    for(i=0;i<enemies.length;i++){
        enemies[i].draw();
    }
    requestAnimationFrame(updateArea);
}

```

---
Tags: javascript, rendering, jquery
---


# Question
Title: Texture Wrapping isn't being applied properly
I've debugged my application with codeXL and can verify that my texture is getting these attributes applied:

```
GL_TEXTURE_MIN_FILTER: GL_LINEAR
GL_TEXTURE_MAG_FILTER: GL_LINEAR
GL_TEXTURE_WRAP_S: GL_CLAMP_TO_EDGE
GL_TEXTURE_WRAP_T: GL_CLAMP_TO_EDGE
GL_TEXTURE_WRAP_R: GL_CLAMP_TO_EDGE

```

With the following UV data:

```
0, 0,
1, 0,
1, 1,
1, 1,
0, 1,
0, 0,
0, 0,
1, 0,
1, 1,
1, 1,
0, 1,
0, 0,
0, 1,
0, 1,
0, 0,
0, 0,
0, 0,
0, 1,
1, 1,
1, 1,
1, 0,
1, 0,
1, 0,
1, 1,
0, 0,
1, 0,
1, 0,
1, 0,
0, 0,
0, 0,
0, 1,
1, 1,
1, 1,
1, 1,
0, 1,
0, 1

```

Yet my cube still looks like this: https://i.stack.imgur.com/2FARE.jpg

The Front and Back are being mapped fine, but the sides and top/bot are all stretched. I've tried with `GL_REPEAT`, `GL_CLAMP_TO_EDGE/BORDER`, `GL_MIRRORED_REPEAT`, it's all the same result. I've tried only doing it with S and T. At this point I'm not sure what the problem is.

Vertex Shader + fragment + Buffers: (It's not that long)

https://ideone.com/5U39M3

I'm not really sure what it could be at this point. I thought my texture wasn't getting it's attributes applied correctly, but it is. Then i thought it was just my wrapping method, but all methods lead to the same result.

# Answer
> -1 votes
So turns out it was a problem with my UV coordinates.

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


# Question
Title: How do I change the sprite used for an object, while the game's running?
**Engine Used:** Gamemaker Studio

I want to be able to swap between two armors on the player character. They've each got their own unique animation / general sprite stuff. How do I "equip" the second armor while the game is running? Is there even a way?

Do I need to destroy the object, and instead replace it with a different object that just has a different sprite?

# Answer
Just change sprite by using:

```
sprite_index = spr_armor2;

```

Example, how it may be (`Step` event):

```
if armor_mode == 0 and sprite_index != spr_armor1
    sprite_index = spr_armor1;
else if armor_mode == 1 and sprite_index != spr_armor2
    sprite_index = spr_armor2;

```
> 1 votes

---
Tags: game-maker
---


# Question
Title: How to assign an instance of an object to an array?
**Game Engine**: Gamemaker Studio

I am making a game similar to bejeweled. I decided to use an array to control everything. Placing instances of objects themselves in to the array seems to be the best way to accomplish this because then I won't have to check where the square is in the room, and then compare it to where in the array that lines up, and so on and so forth.

However, I can't figure out how to do that. How do I do it?

# Answer
While languages such as C and C++ have pointers, Object-Oriented programming language like Java have instance identifiers to reference existing class instances.

Game Maker: Studio provides any existing instance with a built-in variable: `id`. An instance `id` is used to "talk to" a particular instance of an object among the others currently in the room.

I'm assuming that by assigning an instance to an array you mean to save a reference to a given object within an array. As you create your gems - for example in a `while` or `for` statement - you can add a line to the code block to save the id of the new instance:

```
var my_inst;
for (var i=0; i<n; i++)
{
    // Other code of yours //
    my_inst = instance_create(dx,dy,obj_Jewel);
    array_id[i] = my_inst.id;    // OR: array_id[i] = my_inst;
    // Even more code
}

```

Of course, you can expand this code to make it work with 2D arrays if you need to, even with data structures.

You can save an instance `id` by asking for its variable, but remember you get its `id` right when it is created by using the function `instance_create()`, as it is the return value of the function.

Once you get all your `id`s in the array, you can perform all the game logic as you will.
> 1 votes

---
Tags: game-maker
---


# Question
Title: What does this shader error in Löve2D mean?
What could I've done wrong to get the following error message when trying to create a GLSL shader in Löve2D?

I'm sincerely clueless of what the mistake could be, though I suspect the error being a compile-time error because it's happening during `love.load`, in which I require the shader from another file (and not during `love.draw`).

The full code can be found here.

# Answer
> 1 votes
That error means that you're trying to use (directly or indirectly) a fragment shader that has too many uniform variables. Specifically, your hardware or GL implementation has a upper limit of about 3.5k bytes of uniform storage per shader (3584 bytes is room for 896 4-byte floats or *224 4-component float vectors*).

Look through your shaders for one that declares a lot of uniforms and find a way to reduce the number of uniforms required (for example by moving the data into buffers of some sort).

# Answer
> 0 votes
> extern float perm\[512\];

Note that uniforms allocated in vectors, not in single floats.
This array of 512 floats actually takes 512 vectors, (2048 floats)
You could try to pack this data in vec4 first, you will fit in 128 vectors then.

---
Tags: shaders, glsl, lua, love2d
---


# Question
Title: How to check if a game object is inside another gameobject
My idea is that there is a plane which is more of a border at top of the screen and if a game object has no more space to fall and it collides with something while it is in that border, the game ends. How can I check if a gameobject is inside that plane?

Example:

# Answer
> 0 votes
Based on @Danoweb's answer, here is how I did it:

```
public class CubeInteraction : MonoBehaviour {
    private bool endGameBorderCollided;
    private bool cubeCollided;

    private void Update() {
    //Check if there is any space left for cubes to fall. If not - end the game
    CheckForCubeOverflow();

    // Controls touch inputs by the user
    RegisterTouchInputs();
    }

    // Check if a cube enters the end game border and if it collides with another cube at that time
    private void CheckForCubeOverflow() {
       if (endGameBorderCollided && cubeCollided)
           gameOverController.EndGame();
    }

    private void OnTriggerEnter2D(Collider2D collider2D) {
       if (collider2D.name == "End Game Border")
           endGameBorderCollided = true;
    }

    private void OnTriggerExit2D(Collider2D collider2D) {
       if (collider2D.name == "End Game Border")
           endGameBorderCollided = false;
    }

    private void OnCollisionEnter2D(Collision2D collision2D) {
       if (collision2D.collider.name.Contains("Cube"))
           cubeCollided = true;
    }

    private void OnCollisionExit2D(Collision2D collision2D) {
       if (collision2D.collider.name.Contains("Cube"))
           cubeCollided = false;
    }
}

```

# Answer
> 2 votes
This is a great use case for Colliders in Unity. http://docs.unity3d.com/ScriptReference/Collider.html

You would actually want to achieve your objective using 2 colliders. The first being your Border Collider, the second being the "Play Space" collider.

You would then want a script for your GameObjects (squares/rectangles) which checks their collisions, and using a few variables determine which state you are describing.

An example (psuedo code) would be something like this:

```
using UnityEngine;
using System.Collections;

public class falling_game_block : MonoBehaviour {

bool border_collide = false;
bool playspace_collide = false;

void OnCollisionEnter(Collision collision_info)
{
    if(collision_info.collider.name == "border_collider_name")
    {
        border_collide = true;
    }//END IF COLLISION.COLLIDER == "BORDER_COLLIDER_HERE"

    if(collision_info.collider.name == "playspace_collider_name")
    {
        playspace_collide = true;
    }//END IF COLLISION.COLLIDER == "PLAYSPACE_COLLIDER_HERE"

    print(gameObject.name + " in contact with " + collisionInfo.collider.name);
}//END FUNCTION ONCOLLISIONENTER

void OnCollisionExit(Collision collisionInfo) {
    print(gameObject.name + " No longer in contact with " + collisionInfo.collider.name);
}

void Update()
{
    if(border_collide == true && playspace_collide == true)
    {
        //DO stuff, explode, warn, cry, etc...
    }//END IF BORDER_COLLIDE == TRUE AND PLAYSPACE_COLLIDE == TRUE
}
}//END CLASS FALLING_GAME_BLOCK

```

You'll want to look at the "console" to see the print messages. Comment them out when you understand what is going on.

\*** Note this is just psuedo code, and is not fully tested... you may have to perform slight tweaks to address errors, and a few more tweaks to get it to handle your exact need, but this should provide a good starting point!!!

# Answer
> 0 votes
Physics2D.OverlapArea would be perfect for this use...

---
Tags: unity, gameobject
---


# Question
Title: How to correct this issue with a top-down aiming angle in Unity - 2D?
I'm trying to build my first project and I'd like some input for a math correction. The game is a top down 2D shooter, a bit like the iconic "chaos engine" from SNES.

The issue is that either the player (controller by mouse position) or the enemy don't aim accurately enough on certain angles. I'm using a formula that translates the coordinates of the target point into a rotation, so the sprite faces the target. The bullets are always shot straight. The problem is that they miss the target in certain orientations... it doesn't seem accurate enough. I've been looking for a best approach but so far I haven't found any. Can anyone help? Thank you in advance!

To rotate the enemy I'm using this:

```
 Vector3 currentPosition = transform.position;

 Vector3 nextPosition = target.transform.position;

 Vector3 directionOfTravel = nextPosition - currentPosition;

 float angle = (Mathf.Atan2(directionOfTravel.y, directionOfTravel.x) * Mathf.Rad2Deg) - 90;
 transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);

```

# Answer
> 0 votes
You can try something like this.

```
 float step = speed * Time.deltaTime;
 Vector3 newDir = Vector3.RotateTowards(transform.forward, directionOfTravel, step, 0.0F);
 transform.rotation = Quaternion.LookRotation(newDir);

```

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


title: AI parameters for Tetris like game

text:
# Question
Title: AI parameters for Tetris like game
I am building an AI to play a variation of Tetris. The rules are changed in that there are 19 different types of pieces, rotation is not allowed, and the pieces can be placed anywhere in a 10X10 grid. Also, a line is removed once it is full (all 10 cells contain some block). I was trying to figure out which parameters I might choose in order to optimise how the game is played. Some obvious parameters which I thought of:

a) A piece should be placed in a position where it forms the maximum number of full lines, as they can be removed in the next step.

b) A piece should be placed to minimise the 'bumpiness' or roughness of the topmost surface, i.e, it should be as level as possible.

c) This is arguable, but the AI should try to keep as minimum height as possible.

d) The number of columns containing atleast one block should be minimised.

But the AI is still not playing good enough and keeps getting stuck. I would like to know if there are some other important parameters which I may be missing?

# Answer
> 1 votes
Another strategical rule of Tetris you didn't mention is that it is crucial to avoid closing up holes.

```
    || Bad move!
    \/
    ##
   ##

###   ##### #
###  ###### #
### ####### # <-Creates a closed up hole on this row.
########### #

Place it somewhere on top instead!

```

When there is no way around it, it's better to create the hole in a row which already has one or more closed up holes instead of ruining another row.

Also, I understand where you are coming from with rule b), but avoiding bumpiness isn't always the best course of action. What's actually important is to keep the top in a shape which is able to accommodate a wide variety of possible tetrominios without creating holes. A perfectly flat surface isn't necessarily ideal for this. Especially in your variant where the T-, L- and J-tetrominios will not always occur in the rotation where they have a flat bottom.

Another thing to consider when you want to strengthen your AI: A good AI doesn't just think one turn ahead but several turns. It doesn't just need to consider how to place this piece, but also the next, the one after that, etc.

When the next piece is unknown, you can calculate the usefulness of each possible one after the move currently considered and pick the move with the best average rating for all possible follow-ups.

---
Tags: algorithm, ai, optimization
---