title: Using shader for cubes

text:
# Question
Title: Using shader for cubes
I am trying to use a shader to get an effect like this. Notice how

* every cube has exactly the same lightning as every other no matter where it is on the screen
* if you look closely the lightning is making the *front face's* top parts darker, and the *front face's* lower parts lighter (about 20% difference at most)
* also more importantly the edges of the cubes are **smoothed** ( filleted ) and foggy looking

I am drawing my cubes like this with the default lightning.

```
        cubeEffect.EnableDefaultLighting();
        for (int i = 0; i < 10; i++)
        {
            for (int j = 0; j < 25; j++)
            {
                // apply the effect and render the cube
                foreach (EffectPass pass in cubeEffect.CurrentTechnique.Passes)
                {
                    cubeEffect.World = Matrix.CreateTranslation(-15.6f + i * 3.05f, 15.5f - j * 1.168f, 0.0f);
                    pass.Apply();
                    //draw
                    RenderToDevice(GraphicsDevice);
                }
            }
        }

```

This is how my cubes looks like with the default lightning... i am trying to achieve an effect like the first image. I have no experience with lightning effects and how to do something like this so, i'd appreciate any help on how to get started.

I used this http://blogs.msdn.com/b/dawate/archive/2011/01/20/constructing-drawing-and-texturing-a-cube-with-vertices-in-xna-on-windows-phone-7.aspx tutorial's help to draw this

# Answer
> 1 votes
I believe all you need for this is some ambient lighting (light that is allways there, even in the dark parts), and a diffuse light. Instead of enabling default lighting, call

```
cubeEffect.LightingEnabled = true;
cubeEffect.AmbientLightColor = new Vector3( 0.3f, 0.3f, 0.3f );
cubeEffect.DirectionalLight0.Enabled = true;
cubeEffect.DirectionalLight0.DiffuseColor = new Vector3( 0.7f, 0.7f, 0.7f );
cubeEffect.DirectionalLight0.Direction = new Vector3( 0, 1, -1);
for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 25; j++)
    {
        // apply the effect and render the cube
        foreach (EffectPass pass in cubeEffect.CurrentTechnique.Passes)
        {
            cubeEffect.World = Matrix.CreateTranslation(-15.6f + i * 3.05f, 15.5f - j * 1.168f, 0.0f);
            pass.Apply();
            //draw
            RenderToDevice(GraphicsDevice);
        }
    }
}

```

# Answer
> 1 votes
You need a directional lighting. Also disable specular lighting if you want screen position not to matter. This type of directional lighting is achieved by:

```
float lighting = saturate(dot(normal,lightDirection));

```

But you can enable it in a BasicEffect, too. If you want speculars gone, turn down the material's specular intensity to zero (you can also do it in the BasicEffect by setting SpecularColor to black).

Update:

You should try this if you are using built-in effects:

```
cubeEffect.DirectionalLight0.Direction = Vector3(1,1,1);
cubeEffect.SpecularColor = Color.Black.ToVector3();

```

If you want your faces to not be uniformly lit, you should have smoothed normals on the faces. You can achieve this, by having your vertex normals account for their adjacent faces. So each corner should have one normal which points outwards, not three normals for each face.

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


title: Format for storing quest data

text:
# Question
Title: Format for storing quest data
Are there any format for storing quest data that can be processed independently by third-party tools? I don't want to code quests in code, because it will be hard to update and extend them, so I just thinking about generic system that allows to submit to a task, track its stages and rules necessary to fulfill some quest conditions and completion of a quest by player.

Basically, I'd like a simple text file for the start, so that errors in description can be easily edited and committed to repository. But I also want to be able run complex queries against quest DB, such as - "for which quests this quest is prerequisite" or "in which quests this component is used" or "what quests are available for a given environment". So the structure of the field in the format is important. I can of course invent my own, but it would save me a lot of hours to start with something workable.

Is there something generic like that?

# Answer
> 1 votes
I am not aware there are specific formats for quests with specialized editors (there might be!).
But why dont you use XML? There are tons of parsers for every possible programming language. It is widely supported in various editors, it can store almost anything and it is human-readable so it is ideal - at least for prototyping/ debugging. Another, but similar alternative might be JSON.
Later on, when is everything debuged and working, you can move to own binary format to protect your resources (you can still have texts in separate strings.txt file to allow easy community localization).

# Answer
> 1 votes
There is no "standard" format. It all depends on the language and the game engine/framework if any is used. For example, Unity has its own way to do scriptable objects, and thus, potentially quests.

A real example is the way the Lineage 2 Server stores its quests on the server, and they are written in Jython and lately in pure Java (see https://bitbucket.org/l2jserver/l2j\_datapack/src/56cb39df68065d558986bd5f2a1a019b1353d743/dist/game/data/scripts/quests/, folders that start with "Q" have the quests written in Java)

The way it can be done without too much work, is simply to tap into bridging the quest scripts with the actual code, either via a language bridge (I think of SWIG or such) or the actual code. With languages like Java, C#, Python, it's very simple to road another module at runtime and execute its code. All you need is extract some common interfaces which can be used by the scripts code. That way, you don't need to mess with XML, JSON, or other "custom formats".

---
Tags: file-format, quests
---


# Question
Title: Can my cars in my game look like real cars?
We are making a game filled with thousands of cars. We were wondering if we need a licence to use body designs of lets say a Lamborghini, Ferrari, Impala. etc. We do not want to pay money to use the designs in our game, of course we are going to make our own car brands though. Can we use a similar body design??

# Answer
Technically, the design is owned by the company as well. Now, depending on how realistic the game is or how many details you can see about the care, it might not matter at all.

What is important is not to use any distinctive symbols that appear on the car, or any actual names. There are many games that make cars that only look like the original ones, but give them different qualities (like, top speed, sign, name) so that they won't infringe any copyrights or trademarks.

Here is also a nice article on this subject: http://www.giantbomb.com/fictional-car-brands/3015-5156/
> 0 votes

# Answer
One of the best seperators between real cars and toy cars, is in my experience the shaders.

I've spent quite some time with BMW, where we needed to hit the exact glossyness, reflection and feeling of one of their chrome textures.

Without it, the car looked like a small plastic toy, but once it got on, the whole imagry changed, and the car turned into a "believable" vehicle.

Also, use of camera is important here as well. Notice in both car games and especially car ads, how they portray the car to make it look big and robust. In reality, cars aren't that impressive in size, but they always manage to make that feel to it.

And last, but not least, make sure it FEELS like a car. The audio, the steering, the way it moves in place when you hit the brakes. The feel of an object is the final touch in making it feel believable.
> 0 votes

---
Tags: models
---


# Question
Title: How do I let a game support different rule sets?
I'm making a MUD game engine that supports D&D , Pathfinder and other tabletop-RPG rule sets. I am starting to build out how characters interact with the world (e.g. dialog, battle, searching for traps).

The engine is pretty loosely coupled, to facilitate swapping out components with downloaded plugins and I want to continue down that path with the rules. I've got an `ICharacter` interface and both a player and non-playable character interface that inherits from `ICharacter`. I feel that making a developer re-implement those interfaces when making a plugin because the developer is building a Pathfinder plugin instead of a D&D plugin is poor design. Instead, I want to allow them to specify at runtime (via an editor) what rules each character must abide by when performing specific tasks.

I was thinking I'd have a `RuleEngine` that would be provided an object and process a rule. Some pseudo code for this:

```
public void Attack(ICharacter target)
{
    IRuleResult result = RuleEngine.Process(
            RuleFactory.CreateRule("CharacterAttack"),
            this);
    // Check result to see what was given back like damage, hit/miss etc.
}

```

The user within my editor can specify that for `CharacterAttack` rule requests, uses `PathfinderAttackRule`, which would be a Type implementing `IRule`.

This approach feels like it might be to restrictive though. The interface would have to have some knowledge of D&D implementations, like critical miss, damage amounts etc. What if the user wants to build something that isn't D&D, but just a custom combat rule? The interface doesn't allow it and the engine would expect the interface properties to be usable.

Another option I was thinking about was having delegates perform the rule checks and process the attack.

```
public void Attack(ICharacter target)
{
    Func<ICharacter, IPlayer, bool> attackCheck =
            RuleFactory.CreateRule<IPlayer>("PreAttach");

    if (attachCheck(target, this))
    {
        // Invokes a delegate fetched by an internal factory.
        RuleFactory.Process<IPlayer>("AttachPlayer");
    }
}

```

This lets builders specify within the editor what custom delegates to use before an attack starts. (it would be a dropdown list of delegates supported, scanned from the assemblies loaded). The user might want a D&D rule delegate from a plugin they downloaded for pre-attack rule checks, then use a pathfinder rule for the actual attack from a 2nd plugin they downloaded.

Now that I've explained what I'm wanting to do, am I way off base here? Are both of the above examples horribly thought-out and/or is there a better approach to take that is loosely coupled and allows swapping rules out?

As a side-note, I chose player combat as the example, but rules are applied to more than just combat, and more than just players. Rooms, items and other objects will have rules. Some of the rules can be shared, some can not.

Where should I be going with this? I'm looking for general concepts and best-practices.

# Answer
The rules you speak of are basically character actions (or commands). The commands can be divided into several types:

* Self-targeted
* ally-targeted
* creature-targeted
* area-targeted

The main difference is, do we target someone or an area? You can write an abstract action type for these two kinds of actions. These actions will have access to the rules which is a service object that when given the situation and the action taken, can compute to probability of success, roll the virtual dies and also decide on the proper damage formula.

The issue is that the the action, needs to know and be compatible with the characters' attributes and the tools used in the action.

So in the general case, you need to allow others to input a list of attributes and compatible value ranges and distributions, representing a character and a tool. Allow actions to access that data and modify it. The commands or rules will need to be programmable items. It is very convoluted to describe how commands work without code and requires that you'll have predictive knowledge of everything that will ever be done with the system.

What you can do is make some basic types of actions and allow others to inherit from those base types to create their own. The issue there is that the computation of probability and damage output will change depending on the game play system.
> 1 votes

---
Tags: c#, architecture
---


# Question
Title: Why the triangulated body in box@d as a sensor is not treated as one but separate triangle bodies?
I am making simple game - kind of race game, where you see from the "sky" your sprites with circle Box2D bodies attached and they have to move along some path/track. My idea was to detect if they will go out of the path by detecting their contact with invisible body (**set as sensor**) covering the path. My code looks like that:

```
ArrayList<Vector2> UniqueBodyVertices = new ArrayList<Vector2>();
    UniqueBodyVertices.addAll((List<Vector2>) ListUtils.toList(new Vector2[] {
             new Vector2(-432, -95),
             new Vector2(-326, -22),
             new Vector2(-327, 17),
             new Vector2(-440, 96),
             new Vector2(-444, 238),
             new Vector2(-393, 290),
             ...
             new Vector2(-303, -279),
             new Vector2(-425, -285)

     }));

    List<Vector2> UniqueBodyVerticesTriangulated = new EarClippingTriangulator().computeTriangles(UniqueBodyVertices);

    float[] meshTriangles = new float[UniqueBodyVerticesTriangulated.size() * 3];
    for(int i = 0; i < UniqueBodyVerticesTriangulated.size(); i++){
        meshTriangles[i*3] = UniqueBodyVerticesTriangulated.get(i).x;
        meshTriangles[i*3+1] = UniqueBodyVerticesTriangulated.get(i).y;

        UniqueBodyVerticesTriangulated.get(i).mul(1/PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT);
    }

    Sprite bg = new Sprite(0, 0, 1024, 768, ResourceManager.getInstance().mBackGroundRegion, getVertexBufferObjectManager());

    Mesh mesh = new Mesh(0, 0, meshTriangles, UniqueBodyVerticesTriangulated.size(), DrawMode.LINE_STRIP , getVertexBufferObjectManager());

    mesh.setColor(Color.RED);

    Body meshBody = PhysicsFactory.createTrianglulatedBody(physicsWorld, mesh, UniqueBodyVerticesTriangulated, BodyType.StaticBody, PhysicsFactory.createFixtureDef(0f, 0f, 0f, true));
    physicsWorld.registerPhysicsConnector(new PhysicsConnector(mesh, meshBody, true, true));
    meshBody.setUserData("trasa");

```

I deleted some of the vertices just to shorten the code here. I also know that there should be `BodyType.Triangles` and not `BodyType.LineStrip` \- it is just for checking bodies behaviour and does not change anything. Anyway what I pasted here works, and my path is covered with body like I want to, but the problem is detecting the contact. I have another part of code for `ContactListener`:

**EDIT** Added full ContactListener code.

```
private ContactListener createContactLister(){
    ContactListener contactListener = new ContactListener() {

        @Override
        public void preSolve(Contact contact, Manifold oldManifold) {
            // TODO Auto-generated method stub

        }

        @Override
        public void postSolve(Contact contact, ContactImpulse impulse) {
            // TODO Auto-generated method stub

        }

        @Override
        public void endContact(Contact contact) {
            final Fixture x1 = contact.getFixtureA();
            final Fixture x2 = contact.getFixtureB();

            if(x2.getBody().getUserData().equals("kapselBialy")&&x1.getBody().getUserData().equals("trasa"))
            {

                if(contact.isTouching() == false){
                    mScene.setBackground(new Background(Color.RED));
                }
            }

            if(x2.getBody().getUserData().equals("trasa")&&x1.getBody().getUserData().equals("kapselBialy"))
            {
                if(contact.isTouching() == false){
                    mScene.setBackground(new Background(Color.RED));
                }

            }

        }

        @Override
        public void beginContact(Contact contact) {
            final Fixture x1 = contact.getFixtureA();
            final Fixture x2 = contact.getFixtureB();

            if(x2.getBody().getUserData().equals("kapselBialy")&&x1.getBody().getUserData().equals("trasa"))
            {
                if(contact.isTouching() == true){
                mScene.setBackground(new Background(Color.CYAN));
                }

            }
            if(x2.getBody().getUserData().equals("trasa")&&x1.getBody().getUserData().equals("kapselBialy"))
            {
                if(contact.isTouching() == true){
                    mScene.setBackground(new Background(Color.CYAN));
                    }

            }

        }
    };

    return contactListener;

}

```

The problem is that inside my track body there are a lot of trinagles and when my player body leaves one of them and goes inside another it is detected as leaving a sensor area. From outside the whole path is treated as one body. So if my player moves from outside the first triangle it contacts is treated as sensor, but when in the next move it goes to another triangle it is detected as leaving a track body and endContact\` fires up. I attach image from the project.As you can see there are triangles created by the triangulation. My sprite detects some of them as a body of the path, and some not. So how can I do that so all of the triangles are treated as one body? Just to add: If I swith the path body as not a sensor, and try to bounce my sprite from outside it works: the path body is solid from outside on whole length, but not inside of the path body. Hope it is more clear now.

# Answer
SOLVED! Ok so the idea to check if our player body left the body of our path is to count borders playerbody passes. So in contactlistener we make beginContact to add one to some int variable (lets say bordersPassed) and endContact subtracts one from it. So when our player is inside path this variable will always be bigger than 0. When it leaves path it will be 0. And thats what we check.
> 0 votes

---
Tags: collision-detection, box2d, andengine, triangulation
---


# Question
Title: Java game runs slower and slower as game runs longer
I know that this question may be considered off topic, but this is a significant problem.

## Problem:

I have in a java game that I am working on. The FPS counter starts at 250 FPS and in about 2-4 minutes, down to less than 10 FPS. These is too much code to put in this post, but ~~**does anyone know what might cause this?**~~ (Question has been mode to the edit.)

## Edit:

I have found the problem. In short, there are circles moving on a screen. The problem occurs when the program checks if the circle has reached the edge. When the circle reaches the edge, it is killed and particles are summoned. Here is the code for that part(`a` is a circle):

```
if(((Math.abs(a.pos.getX()) + a.radius) >= Game.maxDimention) || ((Math.abs(a.pos.getY()) + a.radius) >= Game.maxDimention)){
    a.die(); //Kill
    a.generateExplosion(); // Summon particles
};

```

When I remove this part, I do not have problems with the game slowing down. **What can I do to fix this?**

## Edit 2:

I have fixed it! The problem was that entities and particles were removed, but the list of particles/entities to remove wasn't being cleared. Thanks for pointing me in the right direction @Stephane Hockenhull!

**Thank you for your time.** *If you vote down, please tell me why so I can improve this question.*

# Answer
You probably have object leaks.

Objects that are still referenced somewhere in an array or list, creating more and more objects for the garbage collector to process as the game advances.

Or more and more AI objects that are off-screen but still active and processing on every frames.
> 4 votes

---
Tags: java, frame-rate
---


title: Should cooldown be time or tick based?

text:
# Question
Title: Should cooldown be time or tick based?
In the past I've done cooldowns as a specific time in ms, but I was thinking isn't having tick based cooldowns better. This would be more accurate and efficent(not sure).

The bad side I can think about is that if the tick rate is increased, it would affect the game logic. While having a base update rate and a multiplier(that can be applied to everything that is tied to tick rate) would probably fix this, I am not sure if this is a good approach.

# Answer
If your game logic is going to be tick based you do not change the tick rate.

Fixed tick-based logic update is useful when you need to easily insure game physic & logic is 100% reproducible as delta-time updates will cause different rounding errors depending on the time elapsed.

You can still use delta-times with tick-based updates for calculating the number of ticks for convenience.

And it's possible to mix both even if exact, reproducible game logic is needed: Use delta time for inconsequential things like particles & UI animations so long as they don't affect game logic.

If the need is simply to have a stable replay it's also possible to record the delta times along with the replay data to ensure the physics end up with the same rounding errors.
> 1 votes

# Answer
It depends on how the rest of your game runs. Either use ticks or time, but choose one and use it everywhere. I prefer using ticks, and setting a max framerate. If the game slows down, so be it. I don't want any quantum tunneling to happen. It's simpler, and i like it. But you could use delta time, and get different framerates with the same game speed. That's up to you to decide. But whatever you do, make the choice once, and use that in your entire game. If you add time based cooldowns in a tick based game and the game runs slow, the cooldowns are suddenly relatively shorter than they're supposed to be, and vice versa.
> 1 votes

# Answer
Anything that can affect the fundamental outcome of the game in this manner should be based on delta times.

Delta time ensures that the correct amount of actual time is perceived by the game logic, usually delta time is handled in ms.
> 0 votes

---
Tags: game-design, timer, logic
---


# Question
Title: Is it possible to use DirectX in pure C program?
I want to try something simple with Direct Sound. Just want to know if it's possible.

Or maybe I need some other API?

# Answer
> 5 votes
If you are for some reason dead set on C, OpenAL may be the audio API to choose as it is a pure C API. OpenAL is a very low-level API. I'm unsure how it compares to DirectSound as I'm used to working with more complete frameworks/engines/games which tend to use something like FMOD or Wwise rather than trying to roll their own high-level audio manipulation library. Depending on what you're trying to do, a library like one of those might be a better option for you, too.

There are ways to bind DirectSound to C, and there at one point was even an official C binding for many DX components (no idea if it's still maintained), but in general this is not the way to go.

Short version: use C++ or use OpenAL.

# Answer
> 8 votes
It's not only possible, it's actually been done.

More than once.

OK, I wouldn't go so far as to call out early id Software code as the epitome of good coding standards, but it does demonstrate that using DirectX in pure C isn't something that exists on a theoretical level, but rather something that has shipped in popular working commercial products.

Despite that you may have problems.

In the DirectInput example, typing out all of the wrapper macros can be a total pain-in-the-ass. In the DirectSound example, earlier versions of MSVC didn't have autocomplete on the lpVtbl member, which can also be a total pain-in-the-ass (I haven't bothered checking with more recent versions).

There are other places in other DirectX APIs where some C++ isms have crept in, notably in the D3DX math stuff, and which can be awkward (but not impossible) if you wish to use them from C.

Nonetheless, fundamentally DirectX is a COM-based API, and while COM may look on the surface as if it is C++ based, it's actually not - a COM interface isn't a class, it's a struct, and full C compatibility exists (COM as-designed is intended to be language-neutral). I suggest checking out the Wikipedia article on COM for further info.

# Answer
> 1 votes
Ofcourse. DirectX is written in plain C. Sure, there are some C++ extension libraries for help on math-related stuff (matrices, vectors etc), but those are typically not long-lived (early deprecated), and rightfully so. Hence you shouldn't even be using those C++ libraries; at least not if you want your code to become deprecated over time.

---
Tags: directx, c
---


# Question
Title: Resource not found: testdata/alphamap.png
I started a tutorial for java's slick 2d library, called SlickBlocks which is essentally a tetris clone. The problem is I have followed and typed in the code examples to the dot, yet when I run it I get the exception: Exception in thread "main" java.lang.RuntimeException: Resource not found: testdata/alphamap.png. I just started the tutorial and am up to "Making a cool effect with Image scale".

Any ideas?

**Edit:**

The error has occured at:

```
at org.newdawn.slick.util.ResourceLoader.getResourceAsStream(ResourceLoader.java:69)
at org.newdawn.slick.opengl.InternalTextureLoader.getTexture(InternalTextureLoader.java:169)
at org.newdawn.slick.Image.<init>(Image.java:196)
at org.newdawn.slick.Image.<init>(Image.java:170)
at org.newdawn.slick.Image.<init>(Image.java:158)
at org.newdawn.slick.Image.<init>(Image.java:136)
at org.newdawn.slick.tests.AlphaMapTest.init(AlphaMapTest.java:33)
at org.newdawn.slick.AppGameContainer.setup(AppGameContainer.java:390)
at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:314)
at org.newdawn.slick.tests.AlphaMapTest.main(AlphaMapTest.java:79)

```

Also not that I am not using "alphamap.png" anywhere in the game, I think It is just referenced by the library itself.

# Answer
> 2 votes
it seems you're not the only with this problem :

http://slick.javaunlimited.net/viewtopic.php?p=24806

This exception occurred because there is a missing folder "testdata" and a file "alphamap.png". This file is used by test classes of Slick. Have you downloaded the full distribution or only the library? When i download the full distribution i can find a testdata folder inside the zip file. You can find it here:

http://slick.cokeandcode.com/

You can find a link to download the full distribution in the menu at the right of the page.

# Answer
> 0 votes
if yow saw this pop up while you start to run your code just click your main class which contains your main method

---
Tags: 2d, java, lwjgl, slick
---


title: Question about save games format

text:
# Question
Title: Question about save games format
my question is about save-games format.

Look at this screenshot:

On the left I made a "simple" fake savegame (Ini format) and on the right there is a "complex" TR2 save game.

I'm wondering how does the complex one work, and why.

I thought that it was made this way to prevent from cheating-editing values, and the format was just a "simple" save encrypted with a key (like aes does).

I'm sceptic though, I don't think every game has implemented an encryption algorithm to save some data. Maybe I miss something, or maybe it's done this way.

Do you have some informations about this ? Have you ever asked yourselves how does this works ? Thanks, have a good day !

# Answer
It is not so complex. A lot of times, the saved data is in *binary* format. In many oop (and not oop) programming languages, data objects can be serialized and dumped into a file. It is that simple (no encryption, just plain old binary data). When you want to load the saved state, you simply "read the objects" from the serialized data.

You need to think of memory and all objects residing inside it, as a big array of bytes. In fact everything in your computer's memory is binary data (1's and 0's) and the easiest way to store a state in a game, is often to simply dump that state composed of 1's and 0's into a file.

What you did with that text file is parse the binary data into ascii which is readable to humans and great for debugging but probably requires more work when and if you need to save more data. Dumping a bunch of objects that represent the state in the game, could be easier to maintain and extend. Using a protocol, that parses everything into a text file is possibly easier for others to interface with as the contents of the file serve also as documentation, since they are also human readable content.
> 1 votes

---
Tags: file-format, savegame
---


title: Problems with rendering a SkyBox

text:
# Question
Title: Problems with rendering a SkyBox
At the moment I'm writing an Android OpenGL ES 2.0 game but now I get stuck on rendering a SkyBox. Here is my (a bit simplified) code for the SkyBox:

```
float vertices [] = {-1,1,1,1,1,1,-1,-1,1,1,-1,1,-1,1,-1,1,1,-1,-1,-1,-1,1,-1,-1};
byte drawOrder[] = {1,3,0,0,3,2,4,6,5,5,6,7,0,2,4,4,2,6,5,7,1,1,7,3,5,1,4,4,1,0,6,2,7,7,2,3};

private final void bindTexture()
{
    int shaderTextureUnit = GLES20.glGetUniformLocation(shaderProgram, "u_TextureUnit");

    GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
    GLES20.glBindTexture(GLES20.GL_TEXTURE_CUBE_MAP, texture);
    GLES20.glUniform1i(shaderTextureUnit, 0);
}

public void draw(float[] viewMatrix) // viewMatrix = Camera = data array
{
    GLES20.glUseProgram(shaderProgram);
    bindTexture(); // Load Texture

    shaderPosition = GLES20.glGetAttribLocation(shaderProgram, "a_Position");
    shaderMatrix = GLES20.glGetUniformLocation(shaderProgram, "u_Matrix");

    // get handle to shape's transformation matrix
    GLES20.glUniformMatrix4fv(shaderMatrix, 1, false, vpMatrix, 0);

    // Prepare the triangle coordinate data
    GLES20.glEnableVertexAttribArray(shaderPosition);
    GLES20.glVertexAttribPointer(shaderPosition, 3, GLES20.GL_FLOAT, false, 0, vertexBuffer);

    // Draw the object to the screen GL_UNSIGNED_BYTE
    GLES20.glDrawElements(GLES20.GL_TRIANGLES, orderBuffer.capacity(), GLES20.GL_UNSIGNED_BYTE, orderBuffer);
    GLES20.glDisableVertexAttribArray(shaderPosition); // Free the position in shader
}

```

I think this code should be perfect because I got it from an OpenGL for beginners book. My problem now is that it looks like this if I render the SkyBox to the screen. I initialize my Camera with this code and here you have also the code for my touch event. If my considerations are right this should produce a circle around the origin so I can see all sides of the SkyBox.

```
private float angle = 90;

Matrix.setLookAtM(data, 0,   0, 0, 0,   0, 0, -1,   0, 1, 0); // the viewMatrix
// Z+ out of screen     Z- in screen

public void onTouch()
{
    angle += 2;

    float s = (float) Math.sin(angle * Math.PI / 180);
    float c = (float) Math.cos(angle * Math.PI / 180);

    Matrix.setLookAtM(data, 0,   0, 0, 0,   c, 0, -s,   0, 1,  0); // the viewMatrix
}

```

The draw Method from the SkyBox is called with the data Matrix from the camera (ViewMatrix) and with disabled depthBuffer. Do you have any ideas why the SkyBox is rendered so strange? What is wrong with my code? Only to be sure that all is right with my shaders here is the code from them:

**FragmentShader**

```
precision mediump float;

uniform samplerCube u_TextureUnit;
varying vec3 v_Position;

void main()
{
    gl_FragColor = textureCube(u_TextureUnit, v_Position);
}

```

**VertexShader**

```
uniform mat4 u_Matrix;
attribute vec3 a_Position;
varying vec3 v_Position;

void main()
{
    v_Position = a_Position;
    v_Position.z = -v_Position.z;

    gl_Position = u_Matrix * vec4(a_Position, 1.0);
    gl_Position = gl_Position.xyww;
}

```

# Answer
> 1 votes
Im not entirely sure about this myself, but maybe your problem is that you dont have one. From the looks of it, your skybox is rotating correctly. Question now: I see you are initializing and uploading the view-matrix correctly, but what about the projection-matrix, i dont see that one. My guess is that your code is alright so far, but since you havent specified it (the projection), OpenGL defaults to some sort of orthogonal projection, which is why it looks so weird when rotating. Maybe that solves your problem. Regards, Daniel

**EDIT**: Try using the `Matrix.perspectiveM()` method and upload the returned matrix to your shader, then multiply it by the view-matrix before multiplying the product of both by your coordinate vector. That should fix your problem, in case you are still waiting for an answer.

# Answer
> 0 votes
Before all I can defenetly say , that disabling ZBuffer is bad idea due perfomance issues, and it looks like for me it is issue. 1) try enable Zbuffer!! 2) check your model,view and project matrices

---
Tags: opengl, opengl-es, skybox
---


# Question
Title: How to add a scrolling camera to a 2D Java game?
I am attempting to create a game where the camera follows the player, always making sure the player is in the center of the screen. How would I go about this? This game is a 2D Java game, made with no engine.

I found an opensource game demonstrating what I want but I cannot work out how to add that to my game. The game is here, if you need it.

Thanks

# Answer
First, you need to define the size of the viewport (the camera resolution), for simplicity, let's assume the camera viewport is the size of the screen, we have a 800\*600 screen.

Next, you need to define the maximum and minimum offsets of your camera. Assuming you have a world with a size of 1600\*1200, the maximum offset would be 800 on X and 600 on Y and 0 on both axis for the minimum offsets. The general formulas to determine the offsets is:

```
offsetMaxX = WORLD_SIZE_X - VIEWPORT_SIZE_X
offsetMaxY = WORLD_SIZE_Y - VIEWPORT_SIZE_Y
offsetMinX = 0
offsetMinY = 0

```

Now, over frames, you need to calculate the actual position of the camera. A position that would make the player being centered on the screen. The position need to be calculated relatively to the player position.

```
camX = playerX - VIEWPORT_SIZE_X / 2
camY = playerY - VIEWPORT_SIZE_Y / 2

```

Don't forget to check if the camera position do not exceed the maximum and minimum offsets.

```
if camX > offsetMaxX:
    camX = offsetMaxX
else if camX < offsetMinX:
    camX = offsetMinX
if camY > offsetMaxY:
    camY = offsetMaxY
else if camY < offsetMinY:
    camY = offsetMinY

```

Now that you know the position of the camera, you will to *translate* the world to this position. When you open a plain window and start drawing stuffs, the area you see start at 0,0. To create the illusion of a camera following the player, you will need to set your drawing area position (the screen in your example) to the camera position.

I don't know what framework/engine you are using but the easiest way to do it is to translate the whole graphic context by the opposite of the current offsets. You will need to know how to access your graphic context and apply a translation to it.

In slick2d, it could look like this:

```
public void render(..., Graphics g) {
    g.translate(-cam.x, -cam.y)
    //render the rest of your game
}

```
> 9 votes

# Answer
I am by no means an authority on this, but one way I've figured out to do this is to create a camera object. The camera would have position, movement vector and dimension variables, along with functions to determine the local position and visibility of other game entities, and to move the camera itself.

Basically, each game entity has a position variable and a local position variable. Every frame, you check to see if the entities are visible, and if they are, get their local positions. (Look into QuadTrees to make this process more efficient.) Then you simply draw the visible objects at their local position.

The only other thing you have to do is create a way to control where and how the camera moves. For a 2D side scroller or and isometric game, just feed the cameras move function the player movement vector every frame to keep the player in the center of the screen.

Hope this helps, Peter
> 2 votes

# Answer
Have the position at which object is drawn offset by the x and y position of the player and minus half the screen width/height.

```
ob1.x -= player.x+screen.width;
ob2.y -= player.y+screen.height;

```

Loop that for every object
> 0 votes

# Answer
The way that I did it was by taking the player's x co-ord and y co-ord, made them negative and added them to screen width/height divided by two

```
FactoryWU.frame.GP.cam.locationX = (int) (-FactoryWU.world.player.getXInt()+((this.getWidth()/cam.zoomLevel)/2)-(10*cam.zoomLevel));
FactoryWU.frame.GP.cam.locationY = (int) (-FactoryWU.world.player.getYInt()+((this.getHeight()/cam.zoomLevel)/2)-(10*cam.zoomLevel));

```

So all what you have to do is add all of your objects co-ords to the cam.locationX or Y
> 0 votes

---
Tags: 2d, java, camera
---


title: Could I use Direct3D to make 2D games?

text:
# Question
Title: Could I use Direct3D to make 2D games?
My goal is to make a completely 2D game using DirectX, but I'm new to it and I'm confused about all of the different APIs that are available.

From Wikipedia:

> **Direct3D is used to render three-dimensional graphics**, ... **Integration with other DirectX technologies enables Direct3D to deliver such features as** video mapping, hardware 3D rendering in 2D overlay planes, and even **sprites, providing the use of 2D and 3D graphics in interactive media ties.**

So I guess that I can use Direct3D to make HUD and GUI (2D) elements of the game using sprites, but can I use it for a completely 2D game or should I use Direct2D instead?

The reasons because I'd prefer to use Direct3D rather than Direct2D (please correct me if I'm wrong on any of this points) are:

* I don't want to use an API that abstracts me too much from what's going
* Direct2D uses Direct3D at the end
* I could find myself wanting to learn 3D programming in the future

And in case that I could use (and maybe choose) Direct3D, since it is such a massive API, which subset of it would someone need to make a 2D game?

I hope the question is not too broad, thanks in advance.

# Answer
> 4 votes
Remember that Direct3D is actually drawing everything in 2D as it's just pixels on the screen. The pipeline is sophisticated enough to handle 3D projection, but you don't have to use it to that.

Direct2D is best if you are drawing traditional vector-graphics like arcs, circles, styled-lines, etc. If you are just manipulating bitmaps (aka 2D sprites), then use `SpriteBatch` in the DirectX Tool Kit for Direct3D 11. It's shared source so you can dig into what it's doing.

# Answer
> 1 votes
The biggest difference between 2D and 3D is well.. one dimension. So just remove one of the dimensions! Imagine that 3D is just composed of a lot of 2D slices. So to draw just one slice you would draw everything of the third dimension on 1 value.

A 2D rectangle would be composed of the following points:

> (0,0,0).....(1,0,0)
> .
> .
> .
> (0,1,0).....(1,1,0)

---
Tags: directx
---


title: Designing a multi-level game

text:
# Question
Title: Designing a multi-level game
I want to know to code structure of a game that has different levels to choose from on the main screen. More precisely, I want to know how does the main loop hands off the rendering to another loop that exist in the level code.

I could think of a solution but I would like to know how this is done by game developers.

Solution:

```
// Level.cpp
void Level::LevelLoop() {
    while(LevelNotDone){
        handleInput();
        update();
        render();
    }
}

// Main.cpp
void MainLoop() {
    while(GameNotDone){
        handleInput();

        if (Condition to start level)
            level.LevelLoop();

        // wait until level loop exits

        update();
        render();
    }
}

```

# Answer
Lookup "data driven programming", "virtual functions" and "function pointers"

http://en.wikipedia.org/wiki/Data-driven\_programming

http://en.wikipedia.org/wiki/Virtual\_function

short virtual function example:

```
bool quit = false;

class GameMode {
public:
  virtual void Update() = 0;
};

class GameModePlatformer : public GameMode
{
public:
  virtual void Update() {
    // do stuff in platformer mode
  }
};

class GameModeMenu : public GameMode
{
public:
  virtual void Update() {
    // do stuff in menu mode
  }
};

GameModePlatformer game_mode_platformer;
GameModeMenu game_mode_menu;

void main()
{
  GameMode *current_mode = &game_mode_menu;

  while(!quit){
    current_mode->Update();

    render();
  }
}

```

An actual game would have init and free functions and other details such as a convenient way to switch modes but that's the gist of it.
> 2 votes

# Answer
This can be done with game states.

Pseudo-code example:

```
STATE = "Menu";
LEVEL_NUMBER = 0;
QUIT = false;
while(!QUIT) {
     if (state is "Menu"){
          Menu.update();
     }
     if (state is "Game"){
          Levels[LEVEL_NUMBER].tick();
     }
}

```
> 1 votes

# Answer
In my small game, I've done it this way: (init\_level() will start a new level)

```
srand(time(NULL));
Env e;
Game g(e);
g.init_window();
g.init();
bool exit1 = false;
for(int i=0;i<8;i++)
  {
    g.init_level(i);
    while(1) {
       SDL_Delay(10);
       bool b1 = g.step(); // next level if b1==false
       bool b2= g.event_handling();
       if (!b1) break;
       if (!b2) {exit1=true; break; }
     }
     if (exit1==true) break;
  }

```
> 1 votes

# Answer
We may be running into the XY problem here.

> More precisely, I want to know how does the main loop hands off the rendering to another loop that exist in the level code.

Most games don't do this. Whether you're in level 1 or level 2, the code rendering is the exact same. The only thing that changes is which objects are loaded up into the scene manager and where the current camera is looking.

Likewise, game logic doesn't necessarily change between levels, either. The actual game logic is generally identical and all that changes is which data is loaded up. If you make your game logic data-driven enough, you can even have vastly different types of levels without needing any specific code added for them.

Menus can also just be another type of level with menu objects instead of characters. Or they might be handled by an entirely different system like a third-party GUI library (which needs to be able to run at the same time as a level for pause and settings menus).

> I could think of a solution but I would like to know how this is done by game developers.

They wouldn't have per-level rendering, and probably wouldn't have per-level hard-coded logic.

However, hard-coded level logic is easier and a good first step for a beginner. This is how you should start. The other answers cover the details of how that is done.

I would definitely avoid per-level hard-coded rendering, at least outside of menus.
> 1 votes

---
Tags: game-loop, level-design
---


title: How to render apart blocks of a cone

text:
# Question
Title: How to render apart blocks of a cone
in OpenGL I want to render a cone in parts like on the image. My problem is to calculate the arc of each block in 3D space.

has someone an idea how to handle this?

# Answer
You should not do that manually. Get a 3D modelling app (there are plenty free apps available) and make the model there, then import it in your program and use it there.

If you need to hide parts of the model (alike the 90 degree section on you picture) then mark the blocks with e.g. different surfaces (tags) and choose to render or to skip them from render in your app depending on your conditions.
> 1 votes

# Answer
To calculate the arc of each block, do this:

```
float arcDegrees = 360 / number_of_blocks_in_a_cylinder;

```

In your image, for example, each "ring" of blocks is constructed of 12 blocks (the nearest three blocks aren't drawn in the image, but for the purposes of spacing, we pretend they're there)

This means that each block covers an arc of 360 / 12 == 30 degrees (π/6 radians). It doesn't matter how close or far from the center they are -- each block in the image covers an arc of exactly 30 degrees.

And that is how you calculate the arc of each block.
> 0 votes

---
Tags: opengl
---


# Question
Title: How to call a method from another c# script using invoke?
I want to call a method from another script in my script using Invoke(),but unable to run it.How can i achieve this ?

Following is my code -

```
void Start () {

    int randNum;
    randNum = Random.Range(0,2);

    Debug.Log("random number == " + randNum);

    if(randNum == 0)
        Invoke("PositionScript.instance.MAttack",5f);

    if(randNum == 1)
        Invoke("PositionScript.instance.SAttack",5f);

}

```

# Answer
> 1 votes
The first parameter in Invoke takes only the name of the method you wish to call.

Assuming `PositionScript.instance` is set to a MonoBehaviour component of some sort:

```
PositionScript.instance.Invoke("MAttack",5f);

```

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


title: Discard Transparent Pixels in Z-Buffer

text:
# Question
Title: Discard Transparent Pixels in Z-Buffer
I am building a 2D game using sprites. I'd like to use the z-buffer to aid with shading.

For that I need Unity to **write only opaque pixels** to the z-buffer (aka depth buffer). In Unity, sprites are built up of polygons, and it is writing these entire polygons, including the transparent pixels, to the depth buffer.

This is the shader I'm using (with some junk added while trying to get this to work) http://pastebin.com/khprCUA0

I have tried

* AlphaTest Greater 0
* alphatest:MyAlphaTestVar
* the `discard` keyword
* Cg's `clip` function
* I suspected that a lighting pass might be writing the depths so I added `novertexlights` and `noambient`

I would suspect that AlphaTest prevents transparent pixels from having *any* effect on the frame or depth buffer (as suggested here), but they still do write to the depth buffer!

The screenshot below shows the inaccurate shapes of objects in the Z-buffer. The king and tree have become blobs because even their transparent pixels were updated in the Z-buffer (drawn using http://willychyr.com/2013/11/unity-shaders-depth-and-normal-textures/):

Compare this to the "correct" shape of the objects in the regular view:

How do I get Unity to **not** write transparent pixels to the z-buffer?

**EDIT:**

Unity 5's frame debugger is turning out to be a miracle! Turns out the "Depth Texture" is actually rendered in a separate pass *before* all other geometry. And I'm having trouble finding out how to use **RenderType** to include/exclude certain objects from this pass.

# Answer
Found! (Thank you *Frame Debugger* !)

It turns out that **Unity renders the Depth Texture in a separate pass** before all geometry is rendered. It is hard to find how to include objects in this pass, and how to specify how they are drawn.

The documentation is kind of vague, but it tells you that the "RenderType" is important without specifying what it should be in order for objects to be included in this pass. I found out that a SubShader will render if it specifies

`"LightMode" = "ShadowCaster"`

So, my shader needed a *separate* SubShader that also **performs an AlphaTest** with this `LightMode` set. This in addition to the 'regular' SubShader which will draw the sprites; which might not even need an AlphaTest since the **zBuffer is not used for the DepthTexture** on my setup. The documentation suggests that some hardware/OS/rendering setups *will* use the zBuffer but it's not entirely clear.
> 2 votes

---
Tags: unity, shaders, depth-buffer, alpha
---


# Question
Title: How would you implement a simple strategy player controller in Unreal Engine 4?
All player controllers in the C++ game templates are not for strategy games. They all implemented so the player controls just *one* character. I'm not sure what approach to take when you want to control several units.

What comes in mind: The player should not have a mesh. He should be always in the center of the screen, he will never move. mouse will then control selection/edge-pan instead of him moving.

In the following image, I have a sphere, that's a "Planet", I wish to accomplish that the player to control the planet, produce units, and control them. I'm very new to UE4, using version 4.6.1, any help would be appreciated as I found little in other places.

Here's my current implementation. it's just the default top down template:

```
// StrategyAlphaCharacter.h
#pragma once
#include "GameFramework/Character.h"
#include "StrategyAlphaCharacter.generated.h"

UCLASS(Blueprintable)
class AStrategyAlphaCharacter : public ACharacter
{
    GENERATED_BODY()

    /** Top down camera */
    UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
    class UCameraComponent* TopDownCameraComponent;

    /** Camera boom positioning the camera above the character */
    UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
    class USpringArmComponent* CameraBoom;

public:
    AStrategyAlphaCharacter(const FObjectInitializer& ObjectInitializer);

    /** Returns TopDownCameraComponent subobject **/
    FORCEINLINE class UCameraComponent* GetTopDownCameraComponent() const { return TopDownCameraComponent; }
    /** Returns CameraBoom subobject **/
    FORCEINLINE class USpringArmComponent* GetCameraBoom() const { return CameraBoom; }
};

// StrategyAlphaCharacter.cpp
#include "StrategyAlpha.h"
#include "StrategyAlphaCharacter.h"

AStrategyAlphaCharacter::AStrategyAlphaCharacter(const FObjectInitializer& ObjectInitializer)
    : Super(ObjectInitializer)
{
    // Set size for player capsule
    GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f);

    // Don't rotate character to camera direction
    bUseControllerRotationPitch = false;
    bUseControllerRotationYaw = false;
    bUseControllerRotationRoll = false;

    // Configure character movement
    GetCharacterMovement()->bOrientRotationToMovement = true; // Rotate character to moving direction
    GetCharacterMovement()->RotationRate = FRotator(0.f, 640.f, 0.f);
    GetCharacterMovement()->bConstrainToPlane = true;
    GetCharacterMovement()->bSnapToPlaneAtStart = true;

    // Create a camera boom...
    CameraBoom = ObjectInitializer.CreateDefaultSubobject<USpringArmComponent>(this, TEXT("CameraBoom"));
    CameraBoom->AttachTo(RootComponent);
    CameraBoom->bAbsoluteRotation = true; // Don't want arm to rotate when character does
    CameraBoom->TargetArmLength = 800.f;
    CameraBoom->RelativeRotation = FRotator(-60.f, 0.f, 0.f);
    CameraBoom->bDoCollisionTest = false; // Don't want to pull camera in when it collides with level

    // Create a camera...
    TopDownCameraComponent = ObjectInitializer.CreateDefaultSubobject<UCameraComponent>(this, TEXT("TopDownCamera"));
    TopDownCameraComponent->AttachTo(CameraBoom, USpringArmComponent::SocketName);
    TopDownCameraComponent->bUsePawnControlRotation = false; // Camera does not rotate relative to arm

}

// StrategyAlphaPlayerController.cpp
#include "StrategyAlpha.h"
#include "StrategyAlphaPlayerController.h"
#include "AI/Navigation/NavigationSystem.h"

AStrategyAlphaPlayerController::AStrategyAlphaPlayerController(const FObjectInitializer& ObjectInitializer)
    : Super(ObjectInitializer)
{
    bShowMouseCursor = true;
    DefaultMouseCursor = EMouseCursor::Crosshairs;
}

void AStrategyAlphaPlayerController::PlayerTick(float DeltaTime)
{
    Super::PlayerTick(DeltaTime);

    // keep updating the destination every tick while desired
    if (bMoveToMouseCursor)
    {
        MoveToMouseCursor();
    }
}

void AStrategyAlphaPlayerController::SetupInputComponent()
{
    // set up gameplay key bindings
    Super::SetupInputComponent();

    InputComponent->BindAction("SetDestination", IE_Pressed, this, &AStrategyAlphaPlayerController::OnSetDestinationPressed);
    InputComponent->BindAction("SetDestination", IE_Released, this, &AStrategyAlphaPlayerController::OnSetDestinationReleased);

    // support touch devices
    InputComponent->BindTouch(EInputEvent::IE_Pressed, this, &AStrategyAlphaPlayerController::MoveToTouchLocation);
    InputComponent->BindTouch(EInputEvent::IE_Repeat, this, &AStrategyAlphaPlayerController::MoveToTouchLocation);
}

void AStrategyAlphaPlayerController::MoveToMouseCursor()
{
    // Trace to see what is under the mouse cursor
    FHitResult Hit;
    GetHitResultUnderCursor(ECC_Visibility, false, Hit);

    if (Hit.bBlockingHit)
    {
        // We hit something, move there
        SetNewMoveDestination(Hit.ImpactPoint);
    }
}

void AStrategyAlphaPlayerController::MoveToTouchLocation(const ETouchIndex::Type FingerIndex, const FVector Location)
{
    FVector2D ScreenSpaceLocation(Location);

    // Trace to see what is under the touch location
    FHitResult HitResult;
    GetHitResultAtScreenPosition(ScreenSpaceLocation, CurrentClickTraceChannel, true, HitResult);
    if (HitResult.bBlockingHit)
    {
        // We hit something, move there
        SetNewMoveDestination(HitResult.ImpactPoint);
    }
}

void AStrategyAlphaPlayerController::SetNewMoveDestination(const FVector DestLocation)
{
    APawn* const Pawn = GetPawn();
    if (Pawn)
    {
        UNavigationSystem* const NavSys = GetWorld()->GetNavigationSystem();
        float const Distance = FVector::Dist(DestLocation, Pawn->GetActorLocation());

        // We need to issue move command only if far enough in order for walk animation to play correctly
        if (NavSys && (Distance > 120.0f))
        {
            NavSys->SimpleMoveToLocation(this, DestLocation);
        }
    }
}

void AStrategyAlphaPlayerController::OnSetDestinationPressed()
{
    // set flag to keep updating destination until released
    bMoveToMouseCursor = true;
}

void AStrategyAlphaPlayerController::OnSetDestinationReleased()
{
    // clear flag to indicate we should stop updating the destination
    bMoveToMouseCursor = false;
}

```

# Answer
Have you taken a look at the official UE4 Tower Defense sample/tutorial?

That sample demonstrates a UE4 project where the player is not associated with any one in-game character, instead providing building orders and high-level AI directives.
> 4 votes

---
Tags: c++, unreal-4
---


title: Mesh fading to transparent

text:
# Question
Title: Mesh fading to transparent
I have a 2D `Mesh` object generated at runtime painted all with uniform color. I want that mesh to have its color fade to transparent color close to the edges.

Despite I searched everywhere I could not find any solution. Unfortunately I'm not into `Shader` programming enough to build logically my solution.

**EDIT:According to @wondra's reply my mesh is not fan shaped. It has a non regular hole in it.**

How can I achieve this?

# Answer
The simplest and probably fastest option would be to iterate your mesh and set edges vertices transparency to 0 (or any other desired value). This assumes you v got (fan shaped)adjacency information:

```
foreach(Triangle t in mesh)
{
   for(int i = 0; i < 3; i++)
   {
      if(t.Adj[i] == - 1) // or ==null, either way, on the edge
      {
         t.Vert[i].a = 0.f;
         t.Vert[(i + 1) % 3].a = 0.f;
      }
   }
}

```

In case you have opposite adjacency, it is just another mod. If you dont have neither, you can compute it. You can also distribute the alpha to adjected triangles based on distance for more in-depth smoother fadeout(just another inner loop or stack).

Other approach would be to compute extremes(x,y min/max of mesh) and map x,y on some function, which simplest would be for example `if(vert.X is less than 10% of width near to extreme) vert.A = 0.f;`. Though this would work well only for convex-shaped mesh, best near-rectangle shaped.
> 1 votes

---
Tags: unity, shaders
---


title: Multiplayer game principles

text:
# Question
Title: Multiplayer game principles
I am developing game using libGDX libraries . I want to create multiplayer mode , where several players can play at the same time in the same room , each player can create his own room and other players can connect to the room they want , I thought a mechanism like this In this mechanism the left client is the one who has created the room and other 3 clients are connected to that room . The game physics runs on the room creator and sends the positions of physical bodies to the server , server sends that positions to other clients , other 3 clients send their input to the server and the server sends that inputs to the room creator and that inputs influence on the physic. But I think this cycle is not good because if the device of room creator runs slow then the game will start lagging and the fps will drop down and other clients will see the game with the same fps which is in the creators device . So can anyone offer me another mechanism for multiplayer game? I am using Node.js for server-side program and Java for client side .

# Answer
> 1 votes
I guess the reason why you were choosing this architecture was to keep the computation costs and computation effort low on the server, allowing it to be lightweight. (Another advantage of this approach is that the usually low upstream of the clients are relieved by a server acting as a broadcasting intermediator.) Of course the downfall is that it now depends on the clients performance. There is no way around this connection.

So you have to decide on what to prioritize:

* Better network performance of the hosting client.
* Better performance of the game on the hosting client.

If you have slow handheld devices which should act as clients you might prefer the first solution, using a strong, scalable server that hosts EVERY game/room. If you always have strong clients with a good connection you might keep your infrastructure low in cost by choosing the second.

Another solution would be to do peer-to-peer communication using the server only for initialization of a game, eg. register as hosting client. Thereby you are able to lower the impact on the bandwidth of the server and you don't have to limit the number of games because of a limited bandwidth: The clients do the work.

I would stick with your approach but with a dynamic part. Since every client can start a game/room in your approach it has the ability to run as hosting client. So why not let the clients provide information about their current performance (FPS/CPU/RAM/Bandwidth/Latency) on which the current host decides if another client is a better host. If this is the case the game migrates from the bad to the new, better host.

What you get is:

* Low impact of running games on the server in aspects of network, CPU and RAM.
* Much simpler and better scalable server implementation.
* Always get the best host for every game session, even if my client accidentally starts an antivirus scan or my damned brother a download of pr0n in the middle of the game.
* Low performance handheld devices profit from strong game partners.

As far as I know Awesomenauts uses such dynamic host approach in a peer-to-peer network.

# Answer
> 0 votes
It's usually not a good idea to couple the framerate to the update rate of the network. The internet is just too unreliable for this. Your clients will feel every single lag and jitter.

A better method is to have the server only send changes and have the clients interpolate with them.

So when an object is moving from position A to position B over the course of 50 game ticks, you don't send 50 messages with 50 intermediate positions. You only send two messages. When it starts moving, you send a message "Object O starts moving from position A into direction X with speed V" and when it stops the second message "Object O stops at position B".

This allows the clients to start showing a smooth movement the moment they receive the first message. Any short-time lags during the movement will be invisible. When there is a lag just when the object stops, they might experience a slight jump to the end position, but that's it.

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


title: Tiled Rendering - Projection matrix

text:
# Question
Title: Tiled Rendering - Projection matrix
I'm trying to figure out how to perform tiled rendering of my 3d scene (OpenGL). The motivation is to cut the scene up into several textures, combining them into a single image for saving at a very high resolution, or for printing.

I've done some reading on this and apparently I just need to put appropriate parameters into my projection matrix for each tile in the scene. This is where I'm failing (miserably). I can't see where or what to use for it.

My perspective projection matrix is pretty standard, like this:

```
const T fov2 = Math::Tan(fov / 2), extent = (farPlane - nearPlane);

assert(fov2 != 0);

Matrix4x4<T> r;

r.m11 = 1 / (aspect * fov2);    r.m12 = 0;          r.m13 = 0;                                      r.m14 =  0;
r.m21 = 0;                      r.m22 = 1 / fov2;   r.m23 = 0;                                      r.m24 =  0;
r.m31 = 0;                      r.m32 = 0;          r.m33 = -(farPlane + nearPlane) / extent;       r.m34 = -1;
r.m41 = 0;                      r.m42 = 0;          r.m43 = -(2.f * farPlane * nearPlane) / extent; r.m44 =  0;

return r;

```

I tried an implementation of glFrustum (no longer available as I'm using core profile of course) as follows:

```
Matrix4x4<T> r(InitialiseAs::InitialiseIdentity);

r.m11 = 2.0f * nearPlane / (right - left);  r.m12 = 0;                                  r.m13 = (right + left) / (right - left);                    r.m14 = 0;
r.m21 = 0;                                  r.m22 = 2.0f * nearPlane / (top - bottom);  r.m23 = (top + bottom) / (top - bottom);                    r.m24 = 0;
r.m31 = 0;                                  r.m32 = 0;                                  r.m33 = -(farPlane + nearPlane) / (farPlane - nearPlane);   r.m34 = -(2.0f * farPlane * nearPlane) / (farPlane - nearPlane);
r.m41 = 0;                                  r.m42 = 0;                                  r.m43 = -1;                                                 r.m44 = 0;

return r;

```

But, alas I'm not sure what parameters I need to use for left, top, right and bottom when iterating across the scene, viewport or screen.

Can anyone assist me?

**Edit:** I found this example (unfortunately D3D) of someone doing something similar. The author seems to be just multiplying \_11 and \_22 by the width (scale up) and then modifying \_31 and \_32 according to the current tile position - iterating through the whole grid.

I did try this but I got a black screen of doom.

# Answer
All you have to to is set glViewport then invert its transformation.

Create a matrix
`s= tilecount;
for(int x=0; x!=tilecount; x++)
 for(int y=0; y!=tilecount; y++)`
\[s 0 0 x\]
\[0 s 0 y\]
\[0 0 1 0\]
\[0 0 0 1\]

And multiply it * your modelviewprojection

However this only works directly for ortho, for perspective, you'll have to w divide manually then apply this matrix.
> 1 votes

# Answer
From Datenwolf in this answer on stackoverflow:

We can render tiles with a 2-loop:

```
for m in 0 to M:
    for n in 0 to N:
        render_tile(n, m)

```

where render\_tile(n, m) starts by setting the viewport to the surface size (render target):

```
glViewport(0, 0, W_t, H_t), for tile width and height W_t, H_t

```

Somehow we've to shift the projection along with the tile (n, m) in the projection plane. The projection plane is also known as the 'near' plane. The extents of the near plane are right - left and top - bottom, so we're splitting the near plane into tiles of size (right - left) / N×(top - bottom) / M so that's what we need to use as shift step size:

```
shift_X = (right - left) / N
shift_Y = (top - bottom) / M

glMatrixMode(GL_PROJECTION)
glLoadIdentity()

switch Projection:
    case Ortho:
        glOrtho(left + shift_X * n, left + shift_X * (n+1),
            bottom + shift_Y * m, bottom + shift_Y * (n+1),
            near, far)
    case Perspective:
        glFrustum( left + shift_X * n, left + shift_X * (n+1),
            bottom + shift_Y * m, bottom + shift_Y * (n+1),
            near, far)

render_scene()

```

How we get left, right, top, bottom for perspective is:

```
right = -0.5 * tan(fov) * near
left = -right;
top = aspect * right
bottom = -top

```
> 1 votes

---
Tags: opengl, rendering, tiles
---


# Question
Title: Why does this impulse not affect the body?
I'm just getting started with Box2d and I'm trying to apply an impulse to a circle but nothing really happens.

First I define `ball`:

```
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2);
ball = world.createBody(bodyDef);
CircleShape dynamicCircle = new CircleShape();
dynamicCircle.setRadius(50f);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = dynamicCircle;
fixtureDef.density = 0.5f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 0.6f;
ball.createFixture(fixtureDef);
dynamicCircle.dispose();

```

then I call this line from inside my `inputprocessor`

```
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    Gdx.app.log("input", "touchDown");
    ball.applyLinearImpulse(new Vector2(0f, 5000f), ball.getPosition(), true);
    return true;
}

```

Here's the render method:

```
public void render() {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    debugRenderer.render(world, camera.combined);
    world.step(1 / 60f, 6, 2);
}

```

I tried logging this and can confirm the `touchDown` event is triggered, but the impulse never applies.

Am I forgetting some call to make this work? What might be going wrong?

# Answer
> 1 votes
In this line

```
ball.applyLinearImpulse(new Vector2(0f, 5000f), ball.getPosition(), true);

```

I think the point where you put force it relative to object position, so you put impule in

```
ball.getPosition() + ball.getPosition()

```

Try to use

```
public void applyForceToCenter(Vector2 force, boolean wake)

```

or

```
ball.applyLinearImpulse(new Vector2(0f, 5000f), new Vector(0,0), true);

```

Didn't test.

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


title: Scene2d Stage Actor setup issues

text:
# Question
Title: Scene2d Stage Actor setup issues
I am creating a game using libgdx.

In the same each level has a class. I have stage as a member variable of the class. To this stage, I add actors.

Inside the levels class, I have attaced the input processor to the stage like below.

```
stage = new Stage();
sviewPort = new StretchViewport(OSR_Constants.VIEWPORT_WIDTH, OSR_Constants.VIEWPORT_HEIGHT);
OrthographicCamera camera = new OrthographicCamera(OSR_Constants.VIEWPORT_WIDTH, OSR_Constants.VIEWPORT_HEIGHT);
camera.position.set(0, 0, 0);
camera.update();
sviewPort.setCamera(camera);
stage.setViewport(sviewPort);

Gdx.input.setInputProcessor(stage);

```

The level object is instantiated in another class known as GameScreen. GameScreen implements the Screen interface.

I am unable to detect touch events on my actors in the stage. Each actor has also been given bounds as per the world coordinates. I have added the following code on each actor to detect touch

```
this.addListener(new InputListener(){
     public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
          System.out.println("touchdown at " + x + " " + y);
          return true;
      }
  });

```

# Answer
> 0 votes
You shouldn't create new InputListener, but you need to use one that you register in Gdx.input.setInputProcessor

```
this.addListener(stage)

```

Didn't test.

---
Tags: android, libgdx, scene-graph, scene2d
---


# Question
Title: How does rendering with Swing compare to rendering with openGL?
\[**summary**: Is the performance of Swing at least in the same dimension as openGL \[through LWJGL\]? If yes, what percentage would you give it? What possible other problems can I expect from Swing in the long run, that I would avoid with openGL?\]

---

So for quite some time I wanted to make my own simple java 2D game engine.

On my first try I was following a tutorial that used openGL (through LWJGL) Because said tutorial wasn't complete I was kind of lost at the end, which caused me to use code that was so inefficient that a simple pong game crashed after 10 seconds because the jvm ran out of memory.

On my second try I, quite successfully, used Swing to render to a jPanel, which significantly reduced the complexity involved (Why can't lwjgl have ANYTHING similar to JPanel.render(Image)?) and allowed me to create some simple games that so far don't seem to take up excessive memory / cpu.

Now my question is whether this could bite me in the ass in the long run, or if it eventually only comes down to a negligible performance hit that I would trade for a more intutive way to code. (Note that I don't care about 3D for now)

# Answer
OpenGL performance will outperform Swing quite heavily once you start doing something a little more advanced. I dont have hard numbers to back my claim, but I have experience. I too started out with pure Java2D, with BufferStrategy and the works. And it was ok for Pong, Snake, Tetris, and so on. But once venturing beyond in graphical effects (blending, lighting as examples), Java2D code started having both performance issues, but more pointedly it's just hard to do correctly.

If you think LWJGL is hard to learn, and you're not really interesting in learning all the gritty bits of OpenGL from the start, I recommend looking into Slick2D which is buildt on LWJGL, but made to create a more Java2D'ish experience. There is also LibGDX which has been gaining traction lately, and is a good alternative if you're also diving into the mobile world.
> 3 votes

# Answer
Like @Terje says, the short answer is "Yes, OpenGL can outperform Swing."

You've seen modern video games, you know current graphics hardware can do truly amazing things.

Pragmatically, what you can do is look at the CPU load of your current "Pong" game, or whatever it is. Based on the CPU percentage, and what your ultimate goal is, maybe Swing is just fine. If Pong takes 3% of the CPU, and your final intended game is equal to "Twenty pongs", then you're good to go.
> 1 votes

---
Tags: opengl, java, 2d, lwjgl, swing
---


# Question
Title: FXC: Error X3501: 'main': entrypoint not found
I am trying to compile a vertex shader using VS2013, but every time I try, FXC returns the following error:

> Error error X3501: 'main': entrypoint not found

I've reduced the vertex shader to its simplest form and yet I'm still getting the same result:

**DefaultVS.hlsl**

```
#include "Include.hlsl"

cbuffer CameraTransform {
    float4x4 ViewProjMat;
};

VS_OUT main(VS_IN input) {
    VS_OUT result;

    result.Position = mul(input.Position, mul(input.WorldMat, ViewProjMat));

    return result;
}

```

**Include.hlsl**

```
struct VS_IN {
    float4 Position : POSITION;
    float4x4 WorldMat : INSTANCE_TRANSFORM;
};

struct VS_OUT {
    float4 Position : SV_POSITION;
};

```

And the properties of both files:

> /Zi /E"main" /Od /Fo"Path\To\Output\DefaultVS.cso" /vs"\_5\_0" /nologo
>
> /Zi /Od /Fo"Path\To\Output\Include.cso" /nologo

# Answer
> 2 votes
The problem is likely VS is trying to compile your `Include.hlsl` file which doesn't actually contain any functions.

Use `Include.hlsli` instead.

---
Tags: shaders, hlsl
---


# Question
Title: which is the best approach or algorithm to calculate real-time ranking
I want to know the fastest and most efficient way to compute points and ranking in real time.

I'm doing a betting football game (a game where users try to predict the outcome of a game before it). In my country is called "Quiniela".

Players put "predictions" just before the match starts. My question is: from the moment the game starts, which is the most efficient way (not just code level but to the database and server) to calculate the ranking for the players "real time" as their predictions regarding the actual outcome of the game.

For example:

If a Team1 vs Team2 plays, the user U1 predicted that the game would end 0-0, U2 predicted the game would end 1-0, U3 predicted the game would would end 1-1.

When starting the game, the U1 would be to first in the ranking because, if the match ends like this, his prediction would be correct, or at least the most accurate.

Then the score switches to 1-0, and the user U1 would be the last of the ranking (because his prediction is not possible anymore), U2 would be the first and U3 second.

If the score changes to 1-1, U2 would go first, U3 would be second (because he guessed part of the result) and U3 last.

I thought about creating a tree of possibilities with one level (0-0 first node, with 1-0 and 0-1 as child nodes) as you change the score, changes the Ranking "temporarily" and I would keep it in cache.

Once the game is over, I keep the latest Ranking in the database.

There is a more optimal way to solve this problem? It has been proposed before and already solved? I'm using MySQL for database, PHP (Cake Php) for the server and a bunch of mobiles who ask for the ranking once in a while.

# Answer
You could use a heuristic function that given a score and a prediction calculates the "value" of the prediction as an integer. This "value" could be the distance between the prediction and the score (a negative value means the prediction is impossible, 0 means it's an exact match and a positive value means it's still possible). Since the "value" of each prediction is an integer sorting is easy and finding the winner is even easier.

I have written a possible implementation of this heuristic function (for a gaming score with house and away scores) using Node.js along with a few tests (using your examples).

You can find the gist at https://gist.github.com/jparreira/081aeaddc592696c0222.

```
// Heuristic function to calculate the "value" of a prediction against a given score
// basically it measures the distance of the prediction to the given score as an integer number
// a negative scoring means that a match with this prediction is already impossible

function scoring(score, prediction) {
  res = 0;

  // calculates the diatance of prediction for the house result
  house_distance = prediction.house - score.house;

  if(house_distance > 0)
        res += Math.abs(house_distance);
  else
        res -= Math.abs(house_distance);

  // calculates the distance of prediction for the away result
  away_distance = prediction.away - score.away;

  if(away_distance > 0)
    res += Math.abs(away_distance);
  else
    res -= Math.abs(away_distance);

  return res;
}

// a series of score to test

scores = [
 { house:0, away:0 },
 { house:1, away:0 },
 { house:1, away:1 },
 { house:2, away:1}
];

// the predictions to evaluate

predictions = [
    { house:0, away:0 },
    { house:1, away:0 },
    { house:1, away:1 },
    { house:2, away:1 }
];

// iterate through the scores and evaluate each prediction

for(s=0; s < scores.length; s++) {
 console.log("******************************************");
 console.log ("CALCULATING HEURISTICS FOR SCORE: " + scores[s].house + "-" + scores[s].away);

 user_winner = null;
 winner_scoring = null;

 // iterate through the predictions
 for(i=0; i < predictions.length; i++) {
  user = i + 1;

  // calculate this prediction scoring
  prediction_scoring = scoring(scores[s], predictions[i]);

  console.log("   prediction of user U" + user + " " + predictions[i].house + "-" + predictions[i].away + " got scoring of " + prediction_scoring);

  if(prediction_scoring >= 0) {
   // prediction is an exact match or at least is still possible
   if(user_winner == null || prediction_scoring < winner_scoring) {
    // first evaluation or current prediction is better than the current winner
    user_winner = i;
             winner_scoring = prediction_scoring;
   }
        }
 }

 // shows the current winner
 console.log("CURRENT WINNER FOR THIS SCORE IS U" + (user_winner + 1));
}
```
> 0 votes

---
Tags: algorithm, ranking, realtime
---


# Question
Title: Maximizing efficiency on space distribution
Imagine you have a room **X** metres long. You have different parts **P** of diverse lenghts **L** and importances **I**. However, the quantity **Q** of each part is limited and different. You want to fit in as many of these parts as possible while also prioritizing those with higher importances. ¿How do you do it?

I've been trying to find a better way to resolve this than testing all combinations, but without success. ¿Any suggestions? (And by the way, if this kind of problem has a name, please post it as a comment or a reply)

> ## **Example:**
>
> *Lenth of room: 5m*
> *Number of parts: 4*
> *Part data:*
>
> > *Part 1: 0.75m, 1 Units, 2 Importance*
> > *Part 2: 1m, 3 Unit, 0.75 Importance*
> > *Part 3: 0.47m, 4 Units, 1 Importance*
> > *Part 4: 1.33m, 2 Units, 3 Importance*
>
> **Now as X, P, L, Q:**
> X = 5;
> P.Lenght = 4;
>
> P0.L = 0.75;
> P0.Q = 1;
> P0.I = 2;
>
> P1.L = 1;
> P1.Q = 3;
> P1.I = 0.75;
>
> P2.L = 0.47;
> P2.Q = 4;
> P2.I = 1;
>
> P3.L = 1.33;
> P3.Q = 2;
> P3.I = 3;

# Answer
One thing you didn't specify clearly: What is the measure of success?

* Number of Pieces?
* Total importance?
* Something else?

For so few pieces, an exhaustive search ("testing all combinations") is perfectly reasonable. Out of those 10 pieces, there's only a few hundred unique combinations to try.

I'll assume "Total importance" for now...

But more generally, these kind of optimization problems have many approaches, including advanced & exotic ones. Some easy ones include:

"Greedy" algorithm -- start with the best "bang for buck" piece (highest importance / length), and use them up first. Then go to the next.

Randomly iterate -- fill all your spots at random. Then, for a while, choose changes randomly (like swapping one piece for another that also fits) and if it makes the solution "better", keep it. Else, go back to the old one.

"Simulated annealing" -- like random iterations, but you start making "big random changes" and taper it down to smaller and smaller changes.

For the exact problem as written Greedy algorithm or Exhaustive search is probably sufficient.
> 0 votes

---
Tags: efficiency, distribution
---


# Question
Title: In Box2D, how do I make a flexible pole?
I would like to replicate the behavior of a flexible pole as used for pole vault.

Can somebody give me some inspiration how to simulate that with Box2D? Should I connect multiple objects with flexible joints, or is there another way?

# Answer
If you don't want to worry about the pole-vault colliding with anything during the vault, you can simulate it using a simple spring-mass-damper system, and you can just animate the pole deforming artificially. The pole can be considered to be a (very stiff) spring. The rest length of the spring is the length of the pole. This is actually a mathematical model

When the player is about to pole-vault, find a point on the ground in front of the player for the pole to attach to. Then, create a spring joint between the player and the ground point. If the player has enough forward momentum, he/she will vault through the air. Tune the stiffness of the spring until you get a result that you like.

As for animating the pole, you can check the length of the spring against its rest length. If the length is significantly shorter, then the pole is compressing, and you can draw a "compressed pole" sprite or curve. Otherwise, the pole is straight.
> 1 votes

# Answer
You can take a look at the cantilever demo in Box2D. If you use the same strategy you can definitely simulate a pole vault. You'll need pretty stiff revolute joints, and will probably want to set Box2D's iteration count fairly high. Try around 50 or so and lower the number until you see the simulation doesn't perform to your standards.

The idea is to just make a bunch of rectangles and link them together with revolute joints. The revolute joints need to be "soft joints", which means they will be solved as non-rigid. This will make the revolute joint act like a spring. However, since you want the spring to be really stiff for the pole vault you'll need to adjust the frequency and damping factor of the joint's spring. This is also why you'll want a high Box2D iteration count as well, to ensure your large link of rectangles converges properly.
> 1 votes

---
Tags: box2d, spring
---


title: Unity import text or json

text:
# Question
Title: Unity import text or json
Can't seem to find a definitive way to import text to C# in Unity3d. I'm looking to import either a lot of different text files or one large json file to represent all the text in the game.

Thanks for your help

# Answer
> 1 votes
The relevant keyword to lookup is TextAsset

When you drag a text file into Unity, it gets treated as a type 'TextAsset'. Actually load the data either by linking it through a serialized variable or by using Resources.Load (just like any other asset: image, prefab, whatever)

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


# Question
Title: Programmatically creating sprite animations in Unity
Some background: I have a set of animated gifs which I've converted to spritesheets, which are then imported into Unity as multiple sprites. The end result is that each spritesheet in the Unity editor contains a list of sprites named *xxxxxxx\_yyy\_zzz* -- for example:

1313000\_000\_000 to 1313000\_000\_014, followed by
1313000\_001\_000 to 1313000\_001\_008, followed by
1313001\_000\_000 to 1313001\_000\_031,
and so on.

Now, I would like to make simple sprite animations out of this spritesheet. In the example above, 1313000.anim should contain all sprites beginning with 1313000 played in numerical order, 1313001.anim should contain all sprites beginning with 1313001, etc. etc.

This isn't hard to do by hand -- highlight desired range of sprites, drag and drop -- but we're talking about a lot of animations. Creating an editor script which lets me right-click a spritesheet and generate a series of .anim files seemed the best solution, but I'm turning up conflicting info on the subject. Getting a sprite array from the spritesheet is simple enough, but programmatically creating an animation is something very few people seem to have discussed.

Essentially, **is it possible and practical to create and populate sprite animations from an editor script?**

# Answer
> 2 votes
I have a similar situation where I have numbers that animate on and off for a number puzzle game. I have a grid sprite sheet with each of these cells evenly spaced. I give each of these cells a number from 0 to X. From a cell number you can get a row and column like this:

```
row = cellNumber / cellsWide;
col = cellNumber % cellsWide;

```

Then I have an XML file that contains the cell numbers for each animation and other information about the sprite sheet. Like the width of a cell in pixels and the total width of the sheet. I load this info from the XML and store it in arrays for each animation.

The instead of using the built in sprite type in Unity, I build the sprite as a mesh that I create in code. Then all I have to do is alter the UV for this mesh to animate what cell is showing on the "sprite".

Actually in my case, I build all the sprites that are on the screen at any given time in a single mesh. This is a much more efficient way of rendering because all the sprites are rendered in a single draw call. Sort of like particles. That also means that my transform for the mesh is 0,0,0. I place each quad where it needs to go on screen.

The UV is calculated from the row and column, the width of the sprite cell, and the total width of the sprite sheet. The way I do it is to use one class to read the XML and create a copy of the unscaled, un-transformed quad. Then another class to get those quads and scale and move them to where they go as I make the full mesh. Then update that mesh each frame if things are moving.

So YES, it is completely possible and practice to create and populate sprite-TYPE animations using a script. But you have to decide which is more work. For me, I have the code down for creating meshes, reading in from XML, etc. And I have other needs that shy me away from the built in sprite system in Unity.

**Alternatively** you can just create sprite arrays and manually stick in each of the animation cells in there and access those programatically. But sound like that is what you are wanting to avoid.

With my above system you'll still have some manual inputting of animation cells, but it's sticking them in an XML document. Not sure which one will take less time.

There are a few options for replacements to the sprite system in Unity. There is one called Sprite Manager which is free and open source: https://github.com/Dkendal/SpriteManager.

There is also Sprite Manager 2 which is $150: http://www.anbsoft.com/middleware/sm2/

Or you can easily write you own like I'm doing.

---
Tags: unity, animation, sprites
---


# Question
Title: XNA - Drawing 2D Primitives (Boxes) and Understanding Matrices in Computer Graphics
I have two issues which I wish to solve by creating 2D primitives in XNA.

1. In my game, I wish to have a "debug mode" which will draw a red box around all hitboxes in the game (Red outline, transparent inside). This would allow us to see where the hitboxes are being drawn AND still have the sprite graphics being drawn.
2. I wish to further understand how matrices work within computer graphics. I have a basic theoretical grasp of how they work, but I really just want to apply some of my knowledge or find a good tutorial on it. To do this, I wish to draw my own 2D primitives (With Vertex3's) and apply different transormation matrices to them.

I was trying to find a tutorial on drawing primitives using Direct3D, but most tutorials are only for c++, and just tell me to use XNA's Spritebatch. I wish to have more control over my program than just with Spritebatch.

Any Help on using Direct3D or any other suggestions would greatly be appreciated.

Thank you.

# Answer
> 2 votes
If you are dead-set on using Matrix math and wanting a wireframe hitbox, DrawUserIndexedPrimitives is probably the way to go. (As Jonathan said)

However, the whole point of a debug mode is to be quick, with little overhead, is it not? I wish to suggest an alternative that I personally use in my game:

```
public void CollisionRectToDraw(GameObject G, int RedValue, int GreenValue, int BlueValue)
    {
        SpriteBatch.Draw(Pixel, new Rectangle((int)G.position.X - (int)G.center.X, (int)G.position.Y - (int)G.center.Y, G.sprite.Width, G.sprite.Height),
            new Color((byte)RedValue, (byte)GreenValue, (byte)BlueValue, (byte)120));
    }

```

Now, this will stretch a single-pixel Texture2D (that's a white pixel) to the size of your sprite's width and height. It will be solid, however. If you want to only draw the wire-frame of it (which may take more time) you simply need to make the stretched rectangle slightly larger, and use a Rectangular Region (which would be your Sprite.Position.X, Sprite.Position.Y, Sprite.Width, Sprite.Height) to "cut out" the part that overlaps your sprite.

This method is both quick, and accurate. While not as pretty as what I'm sure you're imagining in your head, it gets the job done and could be much less expensive than actually having to drawing many LineLists.

---

### EDIT:

This will draw four lines as Drackir suggested.

```
public void CollisionWireFrameToDraw(Gameobject G, int LineThickness, int RedValue, int GreenValue, int BlueValue)
    {
        Rectangle ObjectRect = new Rectangle((int)G.position.X - (int)G.center.X, (int)G.position.Y - (int)G.center.Y, G.sprite.Width, G.sprite.Height);

        game.SpriteBatch.Draw(Pixel, new Rectangle(ObjectRect.Left - LineThickness, ObjectRect.Y,LineThickness,ObjectRect.Height),
            new Color((byte)RedValue, (byte)GreenValue, (byte)BlueValue, (byte)255));//This is the line on the Left

        game.SpriteBatch.Draw(Pixel, new Rectangle(ObjectRect.Right, ObjectRect.Y, LineThickness, ObjectRect.Height),
            new Color((byte)RedValue, (byte)GreenValue, (byte)BlueValue, (byte)255)); //This is the line on the Right

        game.SpriteBatch.Draw(Pixel, new Rectangle(ObjectRect.X, ObjectRect.Top - LineThickness, ObjectRect.Width, LineThickness),
            new Color((byte)RedValue, (byte)GreenValue, (byte)BlueValue, (byte)255)); //This is the line on the Top

        game.SpriteBatch.Draw(Pixel, new Rectangle(ObjectRect.X, ObjectRect.Bottom, ObjectRect.Width, LineThickness),
            new Color((byte)RedValue, (byte)GreenValue, (byte)BlueValue, (byte)255)); //This is the line on the Bottom

    }

```

This draws a line on each of the four sides (left, right, top, bottom). You can change the thickness of the line by passing in a larger (or smaller) LineThickness.

The important thing to note here is that on the Left and Top line, you have to subtract the LineThickness from it's position. (X for Left, Y for Top).

But why?

Because if you don't, the line will "creep" on top of your source sprite. By subtracting your LineThickness, you move the line back out (by offsetting it, so the width of the line doesn't widen onto the sprite.

One thing to note here is that you will have a gap in the four corners where the lines don't meet up. You simply have to choose two lines (Left and Right, or Top and Bottom) and add an offset to them to make it a complete Wire Frame. If you need help with that, I can update my code - but I thought it would be fun for you to solve.

# Answer
> 0 votes
**Debug Drawing**

My suggestion is to create a simple "DebugDraw" class with a few methods for drawing lines, circles, and convex polygons. You can have two flavors of these methods: One for drawing outlines and the other for drawing solids.

The solid shapes would be stored in one set of vertex and index lists, and the outline shapes would be stored in the second.

All shapes should be converted to either line segments or triangles (depending on outline vs solid), and stored in the appropriate vertex or index list. When the lists get to their maximum size, automatically draw them using the BasicEffect with vertex coloring turned on.

I would use VertexPositionColor for the vertices, and I would allow the color of each shape to be specified when drawing ("myDebugDraw.DrawCircle(24, 128, 255, 0);" - where 24 is the number of sides).

I'll try to post an actual class later.

**Matricies**

I don't have any matrix resources, other than my math books. :)

I will say this though... Unless your doing something complex with matricies that no-one has thought of yet, as a game designer, you should probably just look at matrices as "black boxes"... It doesn't matter *how* they work, it just matters that you know when you transform a certain vector by a certain matrix, you get a certain result. Take a world space vector, multiply it by a view and projection matrix, and magically it's turned into a screen space vector. What more do you need to know?

# Answer
> 0 votes
If you are still looking for a simple way to draw shapes check this out:

http://drippingflames.com/xna/

# Answer
> 0 votes
I also use SpriteBatch to render 2D "hitboxes"; supply values for "\_" variables.

```
Rectangle rectangle = _absoluteBounds;
if (_drawBorder)
{
    SpriteBatch.Draw(WhiteTexture, rectangle, null, _borderColor, _rotation, Vector2.Zero, SpriteEffects.None, 0.0f);
    rectangle.Inflate(-2, -2); //<=== border thickness
}
if (_texture == null) SpriteBatch.Draw(WhiteTexture, rectangle, null, _backColor, _rotation, Vector2.Zero, SpriteEffects.None, 0.0f);
else SpriteBatch.Draw(_texture, rectangle, null, _backColor, _rotation, Vector2.Zero, SpriteEffects.None, 0.0f);

```

-WhiteTexture is a 1x1 Texture2D

1) Fills \_absoluteBounds with WhiteTexture using \_borderColor for the tint

2) Shrinks rectangle by border width

3) Fills new rectangle with either the face texture, if supplied (scaled to fit in the shrunken rectangle), or WhiteTexture using \_backColor for the tint

Swapping a repeating sequence of textures for \_texture can produce a few basic/dirty effects, like the border lighting up and scrolling while the hitbox is active/hovered.

Using a custom Effect with SpriteBatch enables further bling.

# Answer
> 0 votes
Extensive research on matrix math is often quoted and, probably, gets mostly ignored. You might read and read and read and still never get it. The important thing is that XNA/DirectX/video cards DO get it. Rather than learning how and why they work, you need to learn how and when to use them. In graphic programming, Matrices are primarily used to move "Object Space" coordinates to "Screen Space".

**It is important** to note that this IS math so standard order-of-operations applies with a few extras. In any space, matrix transforms are performed around the resulting coordinate system's (0, 0, 0), not the source's. If you **move** a coordinate away from (0, 0, 0), **then scale** the coordinate, it will move even further away. Usually, you want to scale **first**, then translate(move).

```
Coordinate * Scale * Translation != Coordinate * Translation * Scale

```

**In 3D games**, this happens in 3 phases and uses 3 matrices, World, View, and Projection. They are actually applied together, but it is easier to visualize their use one at a time.

The World matrix allows you to move and size geometry in the world. You can use geometry created with any actual scale/size/units, from any software. Object Space is typically, but not necessarily, centered at (0, 0, 0). Object Space units, axis angles, etc., are all user-defined. There is no software-defined upper or lower limits for coordinate values in Object Space.

```
ObjectCoordinate * Objects_WorldMatrix = WorldCoordinate

```

Once everything has been translated to World Space, the entire world acts as a single model, centered at (0, 0, 0). You can optionally move/rotate/scale the entire universe with an additional matrix. There is no software-defined upper or lower limits for coordinate values in World Space.

```
WorldCoordinate * Worlds_WorldMatrix = FinalWorldCoordinate

```

The View matrix typically represents the Camera. The View matrix moves, rotates, and scales the entire world into its' own coordinate system. The Camera's location becomes (0, 0, 0). View Space coordinates range from (-1, -1, -1) to (1, 1, 1). Values that are out-of-range, are not visible. Coordinates are not discarded whether they are visible or not.

```
FinalWorldCoordinate * View = ViewCoordinate

```

The Projection matrix specifies the portion of the Camera's 3D view volume to draw to the current Viewport, set on the current RenderTarget. By default, the entire "screen". The Projection matrix defines the distance at which "behind the camera" occurs, as well as how far into the scene to draw. Geometry that is behind the camera, too far away, too far left, etc., gets discarded.

```
ViewCoordinate * Projection = ViewportCoordinate

```

There are only a few more options to consider. By default, the "screen" is the background texture of a Windows.Forms.Form. You can specify another RenderTarget with a different size. Additionally, setting a Viewport specifies a portion of the current RenderTarget to move/scale draw calls to.

**In 2D games**, the same things happens, except you draw with ObjectCoordinates that are already in Screen Space **units**. A square, defined at (0, 0) with a width and height of 1, can be used to draw all squares by adding a "World" matrix. The World matrix scales the square to the correct size, then moves it into position. You can draw the one square over and over, supplying each of your object's World matrices, one per draw.

```
ObjectCoordinate_AlreadyInScreenSpace * World = ViewportCoordinate

```

---
Tags: xna, 2d, directx
---