# Question
Title: How do I detect and handle collisions using a tile property with Slick2D?
I am trying to set up collision detection in Slick2D based on a tilemap. I currently have two layers on the maps I'm using, a background layer, and a collision layer. The collision layer has a tile with a 'blocked' property, painted over the areas the player can't walk on. I have looked through the Slick documentation, but do not understand how to read a tile property and use it as a flag for collision detection.

My method of 'moving' the player is somewhat different, and might affect how collisions are handled. Instead of updating the player's location on the window, the player always stays in the same spot, updating the x and y the map is rendered at. I am working on collisions with objects by restricting the player's movement when its hitbox intersects an object's hitbox. The code for the player hitting the right side of an object, for example, would look like this:

```
if(Player.bounds.intersects(object.bounds)&&(Player.x<=(object.x+object.width+0.5))&&Player.isMovingLeft){
        isInCollision=true;
        level.moveMapRight();
    }
    else if(Player.bounds.intersects(object.bounds)&&(Player.x<=(object.x+object.width+0.5))&&Player.isMovingRight){
        isInCollision=true;
        level.moveMapRight();
    }
    else if(Player.bounds.intersects(object.bounds)&&(Player.x<=(object.x+object.width+0.5))&&Player.isMovingUp){
        isInCollision=true;
        level.moveMapRight();
    }
    else if(Player.bounds.intersects(object.bounds)&&(Player.x<=(object.x+object.width+0.5))&&Player.isMovingDown){
        isInCollision=true;
        level.moveMapRight();
    }

```

and in the level's update code:

```
if(!Player.isInCollision)
        Player.manageMovementInput(map, i);

```

However, this method still has some errors. For example, when hitting the object from the right, the player will move up and to the left, clipping through the object and becoming stuck inside its hitbox. If there is a more effective way of handling this, any advice would be greatly appreciated.

# Answer
First, to get the properties from the Tiles, you need to loop through them when instantiating the TiledMap. Do not try to do read them during your update block since it's a very slow operation.

Inside your Map Class, add two attributes:

```
// This will keep a list of Tiles that are blocked
private boolean blocked[][];

// For collision detection, we have a list of Rectangles you can use to test against
private ArrayList<Rectangle> blocks;

```

Then, inside the Constructor, you can read the Tiles properties:

```
// This will create an Array with all the Tiles in your map. When set to true, it means that Tile is blocked.
blocked = new boolean[this.getWidth()][this.getHeight()];

// Loop through the Tiles and read their Properties

// Set here the Layer you want to Read. In your case, it'll be layer 1,
// since the objects are on the second layer.
int layer = 1;

for(int i = 0; i < this.getWidth(); i++) {
    for(int j = 0; j < this.getHeight(); j++) {

        // Read a Tile
        int tileID = getTileId(i, j, layer);

        // Get the value of the Property named "blocked"
        String value = getTileProperty(tileID, "blocked", "false");

        // If the value of the Property is "true"...
        if(value.equals("true")) {

            // We set that index of the TileMap as blocked
            blocked[i][j] = true;

            // And create the collision Rectangle
            blocks.add(new Rectangle((float)i * tileSize, (float)j * tileSize, tileSize, tileSize));
        }
    }
}

```

The blocked\[\]\[\] array will store which Tiles are blocked. Use this for further reference, instead of reading the Map Properties again.

**About handling the detections:**

If you want to check for collisions, just loop through the List of blocks and check if the Player intersects with them.

```

boolean isInCollision = false;
for(Rectangle ret in yourTiledMap.getBlocks()) {
    if(player.bounds.intersects(ret.bounds)) {
        isInCollision = true;
    }
}

```
> 1 votes

---
Tags: collision-detection, tilemap, slick, collision-resolution
---


# Question
Title: How far should I go in securing Groovy mod scripts?
I am developing a game in java and plan to embed the Groovy script engine to allow for more robust modding options. This comes at a price, of course. Groovy can access anything java can by default, making it something of a security risk. At the moment, this doesn't worry me all too much, as mods for many other single player games such as minecraft already provide this level of access.

However, while the game does not currently have multiplayer support, I would very much like to change that at some point after the initial release. In this case, I would like to be able to allow servers to supply required mod files directly to the client. Is it safe to allow this sort interaction in any case?

My current plan of implementation for this would be to have the server supply mod files to clients, then have the clients pass the name of the mod to a public server I'd host, receiving back from me the expected hash value of that mod to compare against a locally computed hash of the files received from the client. They'd also be given the public rating and description of the mod, and be prompted from there if they wished to keep the mod or discard it.

Obviously this would still require me hosting a mod validation server, so that mods not on the server would be rejected by default. And I'd likely have to provide the ability to download mods directly from this server for users looking to get these mods in the first place, but the purpose of this is to allow players to easily connect to servers without planning out ahead of time what mods they'd need to download, while also decreasing some of the bandwidth overhead I'd have to deal with by having servers host the files and myself simply serving up short blocks of text and hashes.

In summary: Is this complete overkill? Can I even trust servers to host safe content? Can I trust servers to host safe content without checking up on the files they send? Is this not enough security? Do I need to sandbox groovy, or would I be wasting my time?

# Answer
If the game downloads executable code of any fashion, you had better sandbox it completely. Many games don't, and as an ex-security guy, I give all such games an F.

I wouldn't worry about the server validating too much since the user has to make the option to trust any particular server in this instance.

You can get away with not sandboxing your scripts if you make sure you clearly inform users about the dangers of connecting to unknown servers and if you make it easy to opt-out of executing scripts after they've been downloaded (so users can easily check what scripts a server is sending without running them). Also, in this case, use end-to-end encryption (SSL/TLS) to prevent injection of malicious code.

It *probably* wont' matter in practice, but do you want to be responsible for stolen personal data? If you aren't going to put the user and their security and safety first, do *not* write networked code, or really any code at all for that matter. Don't be irresponsible just to save on some time and effort. Please.
> 3 votes

---
Tags: java, scripting, modding, security
---


# Question
Title: Let a time counter working when an app is closed?
Can we let a time counter working even if an app is closed? I would like to add a timer so that we have to wait XX seconds/minutes before a building is created in a game.

I don't want to use an internet connection, and if the user closes the app and just changes the time on his mobile, I cannot compare the 2 time values - before and after.

Would you know how to do this?

Thanks

# Answer
> 0 votes
Timestamp modification is a type of memory-modification cheating, as asked here. The solution is the same:

Is your game multi-player?

If **yes**, keep an authoritative timestamp on the game server that you already have.
If **no**, where's the problem? Your players are only cheating themselves.

# Answer
> 4 votes
If you're wanting to ensure the time is accurate, you should get the time from the internet or from the GPS on the device.

If the user closes the app, there is nothing left to run a timer with. Even services are paired with a process and will get cleaned up if not being used.

You can detect time changes when your app is running, but your app won't know what happened while it wasn't running.

Here's a strategy that may work. It *does* involve using the internet, but it limits the usage to times when the user should likely have a connection. This avoids the player not being able to play when there's no connection.

1. When the game is installed, connect to the internet and get the time you want to use, along with the device time.
2. Every time a building is built, record a timestamp to the file system. (If a connection is available, get the time from the internet to verify).
3. When/if the player submits their score the leaderboard, connect to the internet again and get the time you want to use. Ensure that all the buildings were built between the current time and the last valid time you have recorded. If it's impossible for the player to have built that many buildings in that time frame, invalidate the score.

It doesn't detect every case, but it should help a little.

# Answer
> 1 votes
can you not just log something in a file or something that says "pending event at time X". Then when the game is next loaded do the required "add building" if the time is passed?

Failing that, if the game is server based surely all that happens is when the game is next loaded the change is picked up because the server already did it.

It's more a case of ... Is the game running or not? If it is, then it likely has a UI, if it isn't then me as a user, i don't want that game doing stuff i'm not expecting. Seems suspicious when devs try to this sort of stuff.

---
Tags: android, unity, ios, timer
---


# Question
Title: How can shears/reflections/enlargements be represented by 4x4 matrices?
I understand that 4x4 matrices can represent transformations on a 3d point (represented as x, y, z, w)

Eg, a translation is

```
[1 0 0 0]
[0 1 0 0]
[0 0 1 0]
[x y z 1]

```

where x, y and z are the amount to move the point along each axis.

I know how to represent translations, scaling and rotations but how are other transformations such as shears (with any invariant plane and shear factor), reflections (in any plane) and enlargements (with any center and any scale factor) represented?

The end goal is to have c++ functions to create a translation matrix. Eg:

```
Matrix4x4.generateReflection(Vector3d planeNormal);
Matrix4x4.generateEnlargment(float centerX, float centerY,
                             float centerZ, float scaleFactor);

```

These would return an instance of a `Matrix4x4` class with the elements set such that multiplying it by a point returns the sheared/reflected/enlarged point.

# Answer
> 1 votes
If I understand your question correctly, you are looking for guidance on the construction of matrices for specific more complex transformations. The standard recipe for this is the following:

* Determine the translation to the new origin, and build the homogenous matrix for this translation.
* Determine where each basis vector (unit vector along each axis, relative to the new origin) will be mapped to relative to the new origin. These resultant vectors will be the columns of the resultant non-translational homogenous matrix component.
* Multiply the translational and non-translational matrices to obtain the net transformation matrix. Be careful to do this in the correct order, depending on whether your vectors are row vectors pre-applied to matrices, or column-vectors post-applied to the matrix.

---
Tags: 3d, matrix, transformation, scale
---


# Question
Title: Optimize a vertex buffer and generate its associated index buffer
I need to generate a 64\*64 grid with each cell being 32\*32 wide.

The following code works perfectly but I was wondering whether it can be further optimized when creating the index buffer for it.

I've been searching the web for an algorithm that would generate indices and optimize a buffer but without much success ...

```
var vector3s = new[]
    {
        new Vector3(0, 0, 0),
        new Vector3(1, 0, 0),
        new Vector3(0, 1, 0),
        new Vector3(1, 1, 0),
    };

List<VertexPositionTexture> positions = new List<VertexPositionTexture>();
for (int y = 0; y < 64; y++)
{
    for (int x = 0; x < 64; x++)
    {
        foreach (var vector3 in vector3s)
        {
            var translation = Matrix.CreateTranslation(new Vector3(x, y, 0));
            var transform = Vector3.Transform(vector3, translation);
            var multiply = Vector3.Multiply(transform, 32.0f);
            VertexPositionTexture vpt = new VertexPositionTexture(multiply, new Vector2(vector3.X, vector3.Y));
            positions.Add(vpt);
        }
    }
}

```

Output sample :

```
{Position:{X:0 Y:0 Z:0} TextureCoordinate:{X:0 Y:0}}
{Position:{X:32 Y:0 Z:0} TextureCoordinate:{X:1 Y:0}}
{Position:{X:0 Y:32 Z:0} TextureCoordinate:{X:0 Y:1}}
{Position:{X:32 Y:32 Z:0} TextureCoordinate:{X:1 Y:1}}
{Position:{X:32 Y:0 Z:0} TextureCoordinate:{X:0 Y:0}}
{Position:{X:64 Y:0 Z:0} TextureCoordinate:{X:1 Y:0}}
{Position:{X:32 Y:32 Z:0} TextureCoordinate:{X:0 Y:1}}
{Position:{X:64 Y:32 Z:0} TextureCoordinate:{X:1 Y:1}}

```

For instance, positions at 1 and 4 are identical but their texture coordinates are not.

What are the options for optimizing it and how does one generate the associated index buffer ?

Should positions be separated from texture coordinates and each have an index buffer ?

**EDIT**

Actually texture coordinates are wrong but it's not really relevant for the question.

# Answer
> 2 votes
Depending on how it's textured you could wrap the texture, and use UV coordinates outside of the 0-1 range. That might allow you to avoid duplicating vertices due to UV mismatches.

You definitely want an index buffer - hardware runs much quicker when you have one due to the post transform cache. It's rare that you want to automatically generate one by looking for duplicated vertices though - normally you know during generation what's going to be duplicated.

Other than that the main thing to do is optimize for the pre and post transform caches in the hardware. There's a good implementation of the post transform cache optimization process at: http://home.comcast.net/~tom\_forsyth/papers/fast\_vert\_cache\_opt.html

For the pre transform cache simply reorder the vertex buffer and renumber the index buffer so that vertices are roughly linear in memory (i.e. the index buffer starts from zero and is mostly sequential).

---
Tags: c#, optimization, vertex, index-buffer
---


title: When do I need straight alpha?

text:
# Question
Title: When do I need straight alpha?
I am writing some alpha-blending code, and I realized that premultiplied alpha is enough for most cases.

So I thought about using only premultiplied alpha on my engine code to simplify the structure. Anyway premultiplication itself drops color information on low-alpha pixels, so it can be problematic if I need some kind of serious composition.

But in games, I can't figure out when I need that composition which needs straight alpha. Do you have have case we need straight alpha in trivial(?) game graphics?

# Answer
Using premultiplied alpha everywhere is a fine choice for composition. It allows you to include both additive and alpha-blended elements, as well as anything in between, and you can composite premultiplied-alpha images together using GPU hardware blend modes. In cases where alpha has the usual interpretation (opacity) I'm not aware of any reason *not* to use premultiplied alpha.

You would not, of course, use premultiplied alpha if the alpha channel represents something completely different, e.g. specular power packed in with the color or normal to save a texture lookup or something along those lines.
> 3 votes

---
Tags: alpha-blending
---


# Question
Title: DirectX D3DXVec3Normalize unresolved external symbol
I have simple DirectX project:

```
#include <d3dx10.h>
#include <d3dx10math.h>

#pragma comment(lib, "d3d10.lib")
#pragma comment(lib, "d3dx10.lib")

int main()
{
    D3DXVECTOR3 u(1.0f, 2.0f, 3.0f);
    D3DXVECTOR3 v(2.0f, 1.0f, 3.0f);
    D3DXVECTOR3 a, b, c, d, e;

    float l = D3DXVec3Length(&u);
    float s = D3DXVec3Dot(&u, &v);

    D3DXVec3Normalize(&d, &u); // <- problem is here

    return 0;
 }

```

I added "include" and "lib" directories in my project properties and everything works fine, except D3DXVec3Normalize line. When I run the program it says: "error LNK2019: unresolved external symbol \_D3DXVec3Normalize@8 referenced in function \_main".

Can anyone explain why D3DXVec3Length and D3DXVec3Dot functions work OK (without Normalize line) and D3DXVec3Normalize produces error?

P.S. I use DirectX SDK June 2010 and Visual Studio 2012.

# Answer
So, at first I included following directories into my project: ...\DirectXSDK\Include and ...\DirectXSDK\Lib\x64 (I thought it is OK because I use Windows 7 64 and Visual Studio 2012 64). Everything worked fine except D3DXVec3Normalize function. Then I started to experiment and found the following solution: I switched from x64 to x86 directory in the project properties and error has gone. Looks like my project is x86 application, so I should use x86 libs in that case (I am beginner in c++ and DirectX).
> 0 votes

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


# Question
Title: How to properly calculate y position when drawing from .fnt bitmap font?
I want to render text to bitmap to use it later as a decal texture. I've read through libGDX fonts drawing code and came up with this:

```
private void writeTextToPixmap(Pixmap destPixmap, Pixmap fontPixmap, BitmapFont.BitmapFontData fontData, int startX, int startY, String text) {
    int cursor = startX;

    char[] chars = text.toCharArray();
    for(int i = 0; i < chars.length; i++) {
        BitmapFont.Glyph glyph = fontData.getGlyph(chars[i]);
        destPixmap.drawPixmap(fontPixmap, glyph.srcX, glyph.srcY, glyph.width, glyph.height, cursor + glyph.xoffset, startY + glyph.yoffset, glyph.width, glyph.height);
        cursor += glyph.xadvance;
    }
}

```

The font was generated with Hiero using default settings.

But the result does not look as expected: https://i.stack.imgur.com/3zbAH.png

Usage:

```
    Pixmap pixmap = new Pixmap(1024, 1024, Pixmap.Format.RGBA8888);
    BitmapFont.BitmapFontData fontData = new BitmapFont.BitmapFontData(Gdx.files.internal("data/couriernew.fnt"), false);
    Pixmap fontPixmap = new Pixmap(Gdx.files.internal("data/couriernew.png"));
    writeTextToPixmap(pixmap, fontPixmap, fontData, 300, 400, "ga");

```

# Answer
> 1 votes
The problem was hidden in this line:

```
    BitmapFont.BitmapFontData fontData = new BitmapFont.BitmapFontData(Gdx.files.internal("data/couriernew.fnt"), true);

```

The second argument: font should should be inverted.

---
Tags: libgdx, fonts
---


# Question
Title: How to implement marching cube algorithm for rendering clouds
I would like to render clouds using C#, directX9.0

```
using Microsoft.DirectX.Direct3D;
using Microsoft.DirectX;

```

Now I have roughly add and render the vertex as per below:

As you can see, the vertex is added in a cubic structure. And what I need to do now is to change the cubic structure to curve structure so that the whole cubic structure should looks like a cloud.

I am not using any graphic library but to build this structure solely using `Microsoft.DirectX` and `DirectX.Direct3D`

I did some Google search, and it seems the cube marching algorithm is a useful method to be implemented on these kind of 3D rendering.

From what I researched, there are no ready source for C#, but only for C++ for cube marching algorithm.

So, I would like to ask, if I only want to do the cloud rendering, is the marching cube algorithm a must? Or are there other options to align the structure to let it look like a cloud?

I totally have no idea at all, hope could look for some snipshot of source code or any good reference in C# using DirectX.dll

# Answer
There is a reference implementation by Paul Bourke. It has been adapted to C# by johannes, and also copied on a russian blog.

You can use the C# code linked if understanding the algorithm is not important to you.

Basically marching cubes places a series of cubes (it "marches" them) into the voxel grid. If a cube straddles the isosurface, the cube is "cut" in one of 15 different ways:

Actually the 15th cut is a symmetrical image of the one directly above it (the 10th cut), but that's how the original paper described the possible cuts.

There are a total of 256 *possible* ways for the isosurface to cut the cube, but they all end up being symmetrical images of the above listed ones. For example, configuration 1 shown above (with 1 triangle generated at the corner) can happen in 8 different ways.

Anyway, if you're not interested in implementing this yourself (it takes a long time to sort out all the different configurations!), just copy the C# code at Johannes's blog.
> 3 votes

# Answer
To answer more specifically your question "is the marching cube algorithm a must?"

One of the problem of the marching cubes algorithm is that it can't reproduce sharp corners. I recommend the following reading: From Voxels to Polygons. It introduces another method called Dual Contouring which is more deeply described in this paper.

The idea is take account of the direction of the surface intersecting a voxel edge to create a more accurate shape. You might want to read this article too about this technique.
> 3 votes

# Answer
I am a bit curious, how will you render the geometry once you have it?

I ask because clouds are fuzzy and if you just render a bunch of polygons, the clouds will look opaque.

I suggest rendering with a volumetric raycasting shader. You can use your marching cubes geometry for the basic shape.

Basically, you can render the backface depths/positions to an offscreen buffer and frontface depths/positions to another, and then cast a ray from front to back, summing a noise function (like perlin). Adding lighting is important but can be very slow unless you find a good hack. It is a bit complicated, but it would produce better results than simply rendering the faces of a blobbly cloud shape.
> 1 votes

---
Tags: c#, directx9, marching-cubes
---


# Question
Title: How to play character animation when using A* pathfinding
Hi I am trying to make racing game. In which I am using mecanim animation system to animate my character. Here are the conditions for the animation to play

```
Speed --> 1       Run
Speed --> 0-0.5 - walk
Speed --> <-0.10   -walk back

```

if I set the speed to 1, my character will run i.e

```
anim.setFloat("Speed",1);

```

will run my character.

As it is a racegame I need to move the other characters from source to destination. For which I am using A\* Pathfinding project of arongberg. using the above algorithm I am getting the path and I am using `simpleMove` of character control to move the character. Now the problems comes here

1.As the character needs to play run animation while moving, which is not happening, if I set

```
anim.setFloat("Speed",1); it is not moving in the direction of path instead it is moving on its own direction

```
1. I have tried to apply run animation directly instead of animation controller, but the same Happening.
2. if I remove all the animation character reaching to destination without any animation.

Here is the question where I have posted the code, I am asking the same question again but I was stuck with from past4 days.

http://answers.unity3d.com/questions/495397/how-to-make-my-character-move-in-the-direction-of.html

# Answer
> 1 votes
Okay this a rough copy of your code from the other question but I would create a delegate to report the next point on the path to your CharacterControl components. Please note that this is completely untested and it will require your own tinkering to make sure it works in your project - such as the delegate reference to your AIPather component instance:

First the AIPather:

```
using UnityEngine;
using System.Collections;
public class AIPather: MonoBehaviour {

    //Delegate to pass next point out
    public delegate void ReportNextPathEvent(Vector3 pos);
    public event ReportNextPathEvent ReportNextPath;

    // Use this for initialization
    Seeker seeker;
    public Transform target;
    int currentWayPoint;
    Pathfinding.Path path;
    Animator anim;
    void Start() {
        seeker = GetComponent < Seeker > ();
        seeker.StartPath(transform.position, target.position, onPathCompleted);
        anim = GetComponent < Animator > ();
    }
    void onPathCompleted(Pathfinding.Path p) {
        if (!p.error) {
            path = p;
            currentWayPoint = 0;
        } else {
            Debug.Log(p.error);
        }
    }

    void FixedUpdate() {
        if (path == null) {
            return;
        }
        if (currentWayPoint >= path.vectorPath.Count) {
            return;
        }
        Vector3 dir = (path.vectorPath[currentWayPoint] - transform.position).normalized;

        //Report the path using the delegate
        ReportNextPath(dir);
    }
}

```

Then listen for your delegate on your CharacterControl:

```
using UnityEngine;
using System.Collections;
public class CharacterControl: MonoBehaviour {
Animator anim;
private float swipeDistance = 0;
private bool swipeYN = false;
private Vector2 startPos;
private Vector2 endpos;
bool jumpYN = false;
static int jumpState = Animator.StringToHash("Base Layer.JumpSlide");
private float minSwipeDistance = 100;
private float maxSwipeDistance = 400;
float startTime;
float swipeDirection;
CapsuleCollider collider; // Use this for initialization
void Start() {

    // YOU MUST ASIGN YOUR DELEGATE TO YOUR AIPATHER COMPONENT:
    // <RefToPatherComponentObject += ReportNextPath;

    anim = GetComponent < Animator > ();
    anim.SetFloat("Speed", 1);
    collider = GetComponent < CapsuleCollider > ();
}

// Update is called once per frame
void Update() {
    //  anim.SetFloat("SwipeDirection",swipeDirection);
    anim.SetBool("Jump", false);

    // removed as now handled by delegate:
    //float accelarationx = Input.acceleration.x;
    //anim.SetFloat("Direction", accelarationx);

    AnimatorStateInfo currentState = anim.GetCurrentAnimatorStateInfo(0);
    if (Input.touchCount > 0) {
        Touch start = Input.GetTouch(0);
        switch (start.phase) {
        case TouchPhase.Began:
            startTime = Time.time;
            swipeYN = true;
            startPos = start.position;
            break;
        case TouchPhase.Moved:
            if (Mathf.Abs(start.position.y - start.position.y) > maxSwipeDistance). {
                swipeYN = false;
            }
            break;
        case TouchPhase.Stationary:
            swipeYN = false;
            break;
        case TouchPhase.Ended:
            float swipeTime = Time.time;
            swipeDistance = (start.position - startPos).magnitude;
            if (swipeYN && (swipeDistance > minSwipeDistance)) {
                swipeDirection = Mathf.Sign(start.position.y - startPos.y);
                anim.SetBool("Jump", swipeYN);
                jumpYN = true;
                anim.SetFloat("SwipeDirection", swipeDirection);
            }
            break;
        }
    }
    if (jumpYN) {
        Ray ray = new Ray(transform.position + Vector3.up, -Vector3.up);
        RaycastHit hitInfo = new RaycastHit();
        if (Physics.Raycast(ray, out hitInfo)) {
            // ..if distance to the ground is more than 1.75, use Match Target
            if (hitInfo.distance > 1.75f) {
                // MatchTarget allows us to take over animation and smoothly transition our character towards a location - the hit point from the ray.
                // Here we're telling the Root of the character to only be influenced on the Y axis (MatchTargetWeightMask) and only occur between 0.35 and 0.5
                // of the timeline of our animation clip
                anim.MatchTarget(hitInfo.point, Quaternion.identity, AvatarTarget.Root, new MatchTargetWeightMask(new Vector3(0, 1, 0), 0), 0.35f, 0.5f);
            }
        }
    }

    void ReportNextPath(Vector3 pos){
            Vector3 match = new Vector3(thisTransform.forward.x, 0.0f, thisTransform.forward.z).normalized;
            float deltaAngle = Vector3.Angle(pos, match);
            float neg = deltaAngle * Mathf.Sign(pos);
            anim.SetFloat("Direction", neg, 0.25f , Time.deltaTime);
    }
}

```

---
Tags: unity, path-finding
---


# Question
Title: How can I achieve smooth shading / glow from one tile to another?
I've been working on a tile-based game in which some areas may be *lit* (currently seen), some may be *black* (never seen) and some may be *dark* (previously seen, but not currently seen).

Looking at the absolutely wonderful Pixel Dungeon that has a similar scheme, it has an effect where the dark/black tiles sort of "bleed" into lighter tiles (image from the game's Tumblr):

Look at `1` above - the area beyond the wall is dark, the wall itself it lit, but the darkness "glows" and creates a nice transition to light. There's also a slightly different "glow" from black tiles to light tiles, as seen at `2` \- it's darker (you can't even see the edge of the wall).

I'd be delighted to implement something similar, and if I just want the effect as seen at `1` and `2` I can just create appropriate overlays, something like: for shade-from-dark and for shade-from-black.

It's not that simple, however:

* For locations such as `3` I need black-to-dark shading.
* For locations such as `4` I need shading from 2 dark sides and two lit sides.
* For locations such as `5` I need shading from 2 black sides, 1 dark side and one lit side.
* For locations such as `6` I need shading from 1 black *corner*, 1 dark... hold on a minute, this gets insane!

**So I'm looking for some saner solution to achieve this lovely effect.**

So far I've had these ideas:

1. Generating textures at run-time given the "light status" of the 9 surrounding tile of the tile (and cache these textures).
2. Applying a shader when drawing these tiles to interpolate the shading required at each pixel from the surrounding tiles, using either bilinear or bicubic interpolation.
3. Changing the "dark" and "black" textures to actually be larger than a tile - containing the texture + bleed into adjacent tiles, something like:

And then let these textures overlay each other (but that's a *lot* of blending).
4. Byte56 suggests suggests setting the color per vertex for the underlying tile and it will blend with the texture, but that does not seem accurate enough - for example a dark tile surrounded by black tiles will be completely black, which isn't good. And what if in all the corners are black tiles and on all the sides are lit sides? I guess I could model this accurately by having 9 vertices for each tile instead of 4.

I'd be happy for some input about these proposals as well as any other ideas for achieving this.

I'm using Libgdx and Java, but I have a feeling an answer will not really depend on the framework being used.

# Answer
One method you could try:

Create a texture that has one pixel for every tile (visible on-screen). Then for each tile, set the corresponding pixel to black, 50% grey, or white, and finally, use that texture on a quad that covers the entire scene using a multiply blend. No need to worry about which corner has how many lit/dark neighbours, and OpenGL texture interpolation (make sure filtering is set to GL\_LINEAR, not GL\_NEAREST) will make the smooth transition for you.

The best part is that it also enables any kind of lighting you want, just in case you want a 75% grey area, or a bright green light somewhere.

If you have smooth scrolling, you will need to fiddle with either the texture coordinates of the quad, or move the quad itself, to account for the current sub-tile scrolling position.
> 1 votes

---
Tags: tiles, libgdx
---


title: Display CCSprites with a delay

text:
# Question
Title: Display CCSprites with a delay
I am a beginner in `cocos2d` and I wanted to display coin `CCSprites` as soon as it moves off the screen with a **5** second delay. So this is what I wrote in my main gameplay layer to add **7** coins in a row:

```
- (void)coinSidewaysRowOne {
        if (coinSide1 == FALSE)
        {
            coinSide1 = TRUE;
            NSLog(@"coinSide1 = TRUE");
            int originalX = 500;
            for(int i = 0; i < 8; i++)
            {
                CCSprite *coinHorizontal = [CCSprite spriteWithFile:@"bubble.png"];
                coinHorizontal.position = ccp(originalX, 150);
                originalX += 20;

                [self addChild:coinHorizontal];
                [coinArray addObject:coinHorizontal];
            }
        }
    }

```

And then, in my updateRunning method I added this, so when the coins spawn outside the screen, they move to the left and disappear:

```
// Move coins off the screen and make them move away
    for (CCSprite *coin in coinArray) {
        // apply background scroll speed
        float backgroundScrollSpeedX = [[GameMechanics sharedGameMechanics] backGroundScrollSpeedX];
        float xSpeed = 1.09 * backgroundScrollSpeedX;

        // move the coin until it leaves the left edge of the screen
        if (coin.position.x > (coin.contentSize.width * (-1)))
        {
            coin.position = ccp(coin.position.x - (xSpeed*delta), coin.position.y);
        }
    }

```

**Update:** What I've tried doing is adding this below the if statement above:

```
else {
        coin.visible = TRUE;
        coin.position = ccp(500, 150);
     }

```

So right now, when I run this, the coins move in from the right and move off the screen from the left. How do I make it so that when the coins move to the left and go off the screen, have a five second delay and then have new coins come back to the screen from the right like it originally did.

# Answer
I just put my logic.

You have `updateRunning` method, in this method you have a logic of move coin at right to left.

Here you need to use `CCMoveTo` Action,

```
// move the coin until it leaves the left edge of the screen
if (coin.position.x > (coin.contentSize.width * (-1)))
{
   [coin runAction:
     [CCSequence actions: // Here set MoveDuration as you need , may be "5";
      [CCMoveTo actionWithDuration:MoveDuration position:ccp(coin.position.x - (xSpeed*delta), coin.position.y)],
      [CCCallBlockN actionWithBlock:^(CCNode *node) {
         // Here do stuff when your action is performed.
     }],
      nil]];
}

```

And also call your `updateRunning` method with specific time by using `NSTimer` such like, call `updateRunning`

```
[NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(updateRunning) userInfo:nil repeats:YES]; /// Set Time interval as you need;

```
> 1 votes

---
Tags: 2d, ios, iphone, cocos2d-iphone, cocos2d
---


# Question
Title: How do I persist the states of distant objects?
How would one manage the state of static living things like trees in a large sandbox world? Trees in Minecraft, for example: They grow even when the player is far away.

One way is to save them with a timestamp as they go "out of range" and stop updating them in the usual way. Then re-instate them with a sensible state by running an update with a delta time of the time elapsed since that saved time.

I'm planning a new prototype but this has me a bit stumped.

# Answer
You can make fewer updates on the objects depending on the distance. For example near objects could be updated every 0.1 seconds, while objects that are a bit away could be updated every second (that's a speed up of about 10x already!), and very far away objects could be updated every 10 seconds (~100x speed up).

The small time steps in games are usually just so that the player doesn't notice them directly. Once you are outside of the view of the player you can simulate much more sparely and you will still get proper results. You can also approximate more, for example for the path-finding or the AI. The player won't notice.

Now, if you want to save memory it gets a bit more tricky, since in that case you want to approximate the state of the object too. That means that you would need two different ways to store your object, and approximate the values you haven't saved once the player approaches them.
> 1 votes

---
Tags: architecture, game-state
---


# Question
Title: How do I write a simple 2-player server?
I've recently started learning JavaScript and HTML and developed simple 2-player game such as tick-tack-toe, battleship, and dots & boxes. However, these 2P games can only be played on one computer (i.e. the 2 players must sit together).

I want them to be able to play with a friend on a different computer.

Would anyone have a general, simple working example of a web-game server?

# Answer
In just HTML5 and Javascript, it is almost entirely possible to accomplish this without any backend code (eg. PHP, Python, Ruby) thanks to some of the latest technologies that have come out. Using WebRTC, a peer to peer multiplayer experience is entirely possible, with your server only standing as a broker. To simplify things, there is a library for javascript called PeerJS that abstracts away from the lower level details of WebRTC and make your life much easier. The general idea is you have a Node.js server that will be the broker in establishing a connection between the two clients and once the clients are connected, they will only use peer to peer to communicate after that. Remember that you will need some way for each of the clients to verify the other clients moves are legal, since clients can and will be modified. But if this is just for your own learning experience, that shouldn't be too much of a problem.
> 7 votes

# Answer
Web browsers can't act as a server, so when you want networked multiplayer, you will need a central gameserver on the internet to handle the game state. This can not be done with pure HTML + Javascript. You will need server-sided programming for this. There is a myriad of different technologies to implement this. PHP, Ruby on Rails, JSP, ASP.NET, Node.js to just name a few. Which one to use is too subjective for the scope of this website and thus off-topic according to the FAQ.

Then you need to choose a way for the HTML+Javascript client to communicate with the server. Your options are:

* The oldschool variant with static pages. When a player makes a move, they get redirected to a new page (generated on the server) showing the new game-state. They need to refresh it to check if the other player made a move.
* AJAX (very well-supported by web browsers, but cumbersome when it comes to waiting for a move from the other player)
* WebSockets (faster and more suitable for waiting for events, but not as well-supported)
> 1 votes

# Answer
You don't actually need a central server. He/She could instead set it up so that the server is created on the host machine. This is not recommended though, as this is slightly insecure if not handled properly. (essentially you are sending the server code that you WOULD be running on the central server to the client. The only difference is that for a mainstream game, a main server would have to handle many players, while sending a server to be set up on the host would only need to support x players, where x is the maximum number)

You should read this: https://softwareengineering.stackexchange.com/questions/138561/pros-cons-between-emphasizing-client-side-or-server-side-processing
> 1 votes

# Answer
You can add multiplayer player support in your games in many ways. Firstly there is a WebRTC(Real-Time-Communication), where you can communicate peer to peer, but WebRTC is a work in progress project and only supported by new builds of Chrome and FireFox.

Then there is a second way by having a central server, through which the devices exchange information. In HTML5 you can use websockets at client side to send and receive messages. On server side, you can use any language like PHP, Node.Js, Ruby, etc and handle connection to those websockets. I won't recommend you to use AJAX as it will not give you a good real time experience. To host your game you can use any PaaS(Platform As A Service) service or even maintain your own server and host it there. But hosting your server involves a great cost and also need proper maintains.

There is also another way to achieve multiplayer game development. It's by using BaaS(Backend As A Service), where you don't need to buy a server. You don't even need to write server side code. These BaaS providers have SDKs for different platforms, where you can use multiplayer service by using their APIs. You only need to write multiplayer logic at client side only.

There are different options available, you should explore all of them, and according to your requirement, skill and resources you can should choose one.
> 0 votes

---
Tags: javascript, multiplayer, jquery
---


title: How important is online multiplayer?

text:
# Question
Title: How important is online multiplayer?
I am making a small game that has four players. It can be played with 1 or 2 players locally, with the remaining players controlled by AI.

I am considering online play, but it is an area I know very little about, so it will take a lot of study and work to put it in. I am using my own engine, so I would have to implement it myself, or at least search around for a free library, learn its API, and probably rearrange several of my data structures and methods to make it work. Then I would have to implement lobby screens and possibly backend stuff (I have a little php experience but not a lot).

My question is, is it really worth it? Of course it would be nice to have, but do players expect it these days? I imagine people expect it for big budget games, but how about small indie games?

# Answer
Online multiplayer is becoming an increasingly important factor in my decision to purchase games. While that may just be me, it appears that people overall like to play games with other people. Social media games are a good indicator of this, though, I don't really consider those *multiplayer* for the most part. They do indicate that people like being able to at least partially, share their gaming experience with each other.

When I'm looking for a new game, I'm interested in it being online multiplayer so I can play with my friends. I don't have friends over for LAN parties so much these days, so this is the best way I can connect with them. As the age of the average gamer increases (The average age of the most frequent game purchaser is 35 years old.), the likelihood of having friends over all the time (like we did back in our school days) decreases (or maybe that's just me again?). Online multiplayer allows us to stay connected. I'm all for sitting down and playing a single player game, but it's even better when I can invite a friend to play too.

It's not as if people *won't* buy your game because it has an online multiplayer option. If they're looking for the type of game you're making, and they're interested in your game, the multiplayer over the internet is not going to dissuade them.

Additionally, multiplayer over the internet means increased sales for you. Now instead of two people playing *one* copy of the game, you have two people playing *two* copies of the game together.

All in all, I think adding online multiplayer to a game is more likely to increase sales than adding any other single feature. With it's ability to double your sales for people buying together, and the option of adding bundle deals for multiple copies.

But is it worth it? That's up to you to decide. Perhaps for now you can keep online multiplayer in mind, and design as if it's there, but save it for later.

An article related to this topic: The Importance of Multiplayer Gaming

And the importance of local multiplayer too!: The importance of split-screen, co-op and basically all offline multiplayer games
> 9 votes

# Answer
It's always a question of which niche you want to target. Every niche has different needs.

Since your game is multiplayer already it would make sense to add a online option. There are a lot of people who want to play games together but don't have the time or money to meet regularly in real life. By having a multiplayer only game you have to be local for you are limiting yourself to a reeaaly small niche, probably too small to make a decent amount of money with.

Well... unless you are going for a true "social" experience... e.g. a party game. That is a completely different niche already, where the people have little use for a online mode.

For a single player game it would just be a waste of time, people will pay for it because it gives a good single player experience, not because it has a tacked on multiplayer part.

**Don't waste your time with implementing a feature just because it would be "cool to have",** it should be a vital component of your game. People won't buy your game just because it has feature X, but because it delivers a good experience.
> 1 votes

# Answer
Definitely Multiplayer games have large audience that's why several games with Multiplayer support keeps on releasing. In fact multiplayer games can keep players engaged to your game.

Multiplayer becomes more fun, when they are played over internet, because they can give a player more number of opponents and different level of competitions. And leaderboards can even more enhance game experience.

You don't need to write server side code and maintain servers. There are several Backend As A Service(BaaS) Cloud Providers, where you can implement multiplayer games without writing code for server. Simply register on them, and call their APIs through their SDKs on client. They make development of multiplayer very easy.

These Backend As A Services are perfect for Indie game developers as you don't have to buy or maintain server. These providers even have free plans.

If you are interested in Multiplayer gaming, then you should definitely checkout these services.
> 0 votes

---
Tags: multiplayer, online
---


# Question
Title: How can I import FBX animations using the FBX SDK?
I got the meshes loaded in correctly with all of their vertices, indices, UV's, and normals. I am just now trying to get the Animations working correctly. I have looked at the FBX SDK documentation with little help. If someone could just help me get started or point me in the right direction I would greatly appreciate it. I added some code so you can kinda get an idea of what I am doing. I should be able to place that code anywhere in the load FBX function and have it work.

```
//GETTING ANIMAION DATA
for(int i = 0; i < scene->GetSrcObjectCount<FbxAnimStack>(); ++i)
{
    FbxAnimStack* lAnimStack = scene->GetSrcObject<FbxAnimStack>(i);

    FbxString stackName = "Animation Stack Name: ";
    stackName += lAnimStack->GetName();
    string sStackName = stackName;

    int numLayers = lAnimStack->GetMemberCount<FbxAnimLayer>();
    for(int j = 0; j < numLayers; ++j)
    {
        FbxAnimLayer* lAnimLayer = lAnimStack->GetMember<FbxAnimLayer>(j);

        FbxString layerName = "Animation Stack Name: ";
        layerName += lAnimLayer->GetName();
        string sLayerName = layerName;

        queue<FbxNode*> nodes;

        FbxNode* tempNode = scene->GetRootNode();

        while(tempNode != NULL)
        {
            FbxAnimCurve* lAnimCurve = tempNode->LclTranslation.GetCurve(lAnimLayer, FBXSDK_CURVENODE_COMPONENT_X);

            if(lAnimCurve != NULL)
            {
                //I know something needs to be done here but I dont know what.
            }

            for(int i = 0; i < tempNode->GetChildCount(false); ++i)
            {
                nodes.push(tempNode->GetChild(i));
            }

            if(nodes.size() > 0)
            {
                tempNode = nodes.front();
                nodes.pop();
            }
            else
            {
                tempNode = NULL;
            }
        }
    }
}

```

Here is the full function

```
bool FBXLoader::LoadFBX(ParentMeshObject* _parentMesh, char* _filePath, bool _hasTexture)
{
    FbxManager* fbxManager = FbxManager::Create();
if(!fbxManager)
{
    printf( "ERROR %s : %d failed creating FBX Manager!\n", __FILE__, __LINE__ );
}

FbxIOSettings* ioSettings = FbxIOSettings::Create(fbxManager, IOSROOT);
fbxManager->SetIOSettings(ioSettings);

FbxString filePath = FbxGetApplicationDirectory();
fbxManager->LoadPluginsDirectory(filePath.Buffer());

FbxScene* scene = FbxScene::Create(fbxManager, "");

int fileMinor, fileRevision;
int sdkMajor, sdkMinor, sdkRevision;
int fileFormat;

FbxManager::GetFileFormatVersion(sdkMajor, sdkMinor, sdkRevision);
FbxImporter* importer = FbxImporter::Create(fbxManager, "");

if(!fbxManager->GetIOPluginRegistry()->DetectReaderFileFormat(_filePath, fileFormat))
{
    //Unrecognizable file format. Try to fall back on FbxImorter::eFBX_BINARY
    fileFormat = fbxManager->GetIOPluginRegistry()->FindReaderIDByDescription("FBX binary (*.fbx)");
}

bool importStatus = importer->Initialize(_filePath, fileFormat, fbxManager->GetIOSettings());
importer->GetFileVersion(fileMinor, fileMinor, fileRevision);

if(!importStatus)
{
    printf( "ERROR %s : %d FbxImporter Initialize failed!\n", __FILE__, __LINE__ );
    return false;
}

importStatus = importer->Import(scene);

if(!importStatus)
{
    printf( "ERROR %s : %d FbxImporter failed to import the file to the scene!\n", __FILE__, __LINE__ );
    return false;
}

FbxAxisSystem sceneAxisSystem = scene->GetGlobalSettings().GetAxisSystem();
FbxAxisSystem axisSystem( FbxAxisSystem::eYAxis, FbxAxisSystem::eParityOdd, FbxAxisSystem::eLeftHanded );

if(sceneAxisSystem != axisSystem)
{
    axisSystem.ConvertScene(scene);
}

TriangulateRecursive(scene->GetRootNode());

FbxArray<FbxMesh*> meshes;
FillMeshArray(scene, meshes);

unsigned short vertexCount = 0;
unsigned short triangleCount = 0;
unsigned short faceCount = 0;
unsigned short materialCount = 0;

int numberOfVertices = 0;
for(int i = 0; i < meshes.GetCount(); ++i)
{
    numberOfVertices += meshes[i]->GetPolygonVertexCount();
}

Face face;
vector<Face> faces;
int indicesCount = 0;

int ptrMove = 0;

float wValue = 0.0f;

if(!_hasTexture)
{
    wValue = 1.0f;
}

for(int i = 0; i < meshes.GetCount(); ++i)
{
    int vertexCount = 0;
    vertexCount = meshes[i]->GetControlPointsCount();
    if(vertexCount == 0)
        continue;

    VertexType* vertices;
    vertices = new VertexType[vertexCount];

    int triangleCount = meshes[i]->GetPolygonVertexCount() / 3;
    indicesCount = meshes[i]->GetPolygonVertexCount();

    FbxVector4* fbxVerts = new FbxVector4[vertexCount];
    int arrayIndex = 0;
    memcpy(fbxVerts, meshes[i]->GetControlPoints(), vertexCount * sizeof(FbxVector4));

    for(int j = 0; j < triangleCount; ++j)
    {
        int index = 0;
        FbxVector4 fbxNorm(0, 0, 0, 0);
        FbxVector2 fbxUV(0, 0);
        bool texCoordFound = false;
        face.indices[0] = index = meshes[i]->GetPolygonVertex(j, 0);
        vertices[index].position.x = (float)fbxVerts[index][0];
        vertices[index].position.y = (float)fbxVerts[index][1];
        vertices[index].position.z = (float)fbxVerts[index][2];
        vertices[index].position.w = wValue;
        meshes[i]->GetPolygonVertexNormal(j, 0, fbxNorm);
        vertices[index].normal.x = (float)fbxNorm[0];
        vertices[index].normal.y = (float)fbxNorm[1];
        vertices[index].normal.z = (float)fbxNorm[2];
        texCoordFound = meshes[i]->GetPolygonVertexUV(j, 0, "map1", fbxUV);
        vertices[index].texture.x = (float)fbxUV[0];
        vertices[index].texture.y = (float)fbxUV[1];

        face.indices[1] = index = meshes[i]->GetPolygonVertex(j, 1);
        vertices[index].position.x = (float)fbxVerts[index][0];
        vertices[index].position.y = (float)fbxVerts[index][1];
        vertices[index].position.z = (float)fbxVerts[index][2];
        vertices[index].position.w = wValue;
        meshes[i]->GetPolygonVertexNormal(j, 1, fbxNorm);
        vertices[index].normal.x = (float)fbxNorm[0];
        vertices[index].normal.y = (float)fbxNorm[1];
        vertices[index].normal.z = (float)fbxNorm[2];
        texCoordFound = meshes[i]->GetPolygonVertexUV(j, 1, "map1", fbxUV);
        vertices[index].texture.x = (float)fbxUV[0];
        vertices[index].texture.y = (float)fbxUV[1];

        face.indices[2] = index = meshes[i]->GetPolygonVertex(j, 2);
        vertices[index].position.x = (float)fbxVerts[index][0];
        vertices[index].position.y = (float)fbxVerts[index][1];
        vertices[index].position.z = (float)fbxVerts[index][2];
        vertices[index].position.w = wValue;
        meshes[i]->GetPolygonVertexNormal(j, 2, fbxNorm);
        vertices[index].normal.x = (float)fbxNorm[0];
        vertices[index].normal.y = (float)fbxNorm[1];
        vertices[index].normal.z = (float)fbxNorm[2];
        texCoordFound = meshes[i]->GetPolygonVertexUV(j, 2, "map1", fbxUV);
        vertices[index].texture.x = (float)fbxUV[0];
        vertices[index].texture.y = (float)fbxUV[1];

        faces.push_back(face);
    }

    meshes[i]->Destroy();
    meshes[i] = NULL;

    int indexCount = faces.size() * 3;
    unsigned long* indices = new unsigned long[faces.size() * 3];
    int indicie = 0;
    for(unsigned int i = 0; i < faces.size(); ++i)
    {
        indices[indicie++] = faces[i].indices[0];
        indices[indicie++] = faces[i].indices[1];
        indices[indicie++] = faces[i].indices[2];
    }
    faces.clear();
    _parentMesh->AddChild(vertices, indices, vertexCount, indexCount);
}

return true;
}

```

# Answer
The FBX documentation is painful at times, and this is definitely one of them.

There are two ways I've used to access animation data. The first is used in the ImportScene sample that comes with the SDK, and it's the way you seem to be trying to do things. In your sample, now that you have a valid lAnimCurve, you would need to query the number of keyframes that are stored in that curve, and then access them one at a time. It's a fairly complex process, I would refer you to the DisplayAnimation.cxx file in the ImportScene sample to see how they do it.

The problem with this is that you then will need to go through and determine any missing information. In the animation I'm working with, I have keyframe data for frame 0, 35, and 70. So now I would need to determine if the interpolation is linear or cubic, which involves more complicated and error-prone programming.

I also don't know at this point how fast the animation runs - 30fps, 24fps, 60fps, or some custom number - so even though I know I have 70 frames, I don't actually know how long the animation is supposed to last.

Instead, I would suggest digging into the KFbxAnimEvaluator class. This makes life much easier, because it will figure out all sorts of animation stuff for you. Really, that's the SDK page to keep an eye on.

So here's some sample code for how I break the times down. Assume lAnimStackCount is the number of animation stacks my file has.

```
for(i = 0; i < lAnimStackCount; i++) {
   KFbxTakeInfo* lTakeInfo = lImporter->GetTakeInfo();

   KTime start = lTakeInfo->mLocalTimeSpan.GetStart();
   KTime end = lTakeInfo->mLocalTimeSpan.GetStop();

   // now you know how many seconds the animation runs, and can figure out how many
   // keyframes you need. I usually export animations as 30fps
}

```

From here, you can use the GetNodeLocalTransform() function in KFbxAnimEvaluator to get the transform matrix at specific times. It will give you a final answer matrix that you can pull the TRS info out of.

I know that's vague, but my specific code is not on this computer. Hopefully it's high-level enough to help though.
> 8 votes

---
Tags: c++, directx11, fbx
---


# Question
Title: Changing the sprite position: Modify VBO data or translate it?
I am beginning with VBO and I want to know if it's better use `GL_STATIC_DRAW` to make a quad and them translate it, or use `DYNAMIC_DRAW` and modify the vertex position data directly.

Also when I modify the data of a static VBO the rendering really change! Why does this happen? It is supposed to make STATIC object right?

# Answer
Don't change the vertex buffer to translate, rotate or scale the object. For 3d graphics, this is typically done by multiplying every vertex with a transformation matrix in the vertex shader.

So if you don't want to modify the shape of the mesh, you should use `GL_STATIC_DRAW`. The other option `DYNAMIC_DRAW` is used to stream meshes changing other time.
> 0 votes

# Answer
In contrast to danijar's advice, I'm going to suggest modifying the buffer. For sprites, you can be much better off writing all your sprites into a single buffer. You then can't as easily apply a transformation matrix to them on the GPU (especially if you're targetting the Web or mobile platforms stuck with GLES 2, which does not having instancing support). It can be more efficient to stuff all the sprites' quads/tris, with pre-transformed vertices, into a single buffer you update each frame.

This of course also requires texture atlasing and can only be done for sprites using the same atlas and the same material/shaders, but in general this is a pretty safe requirement for most 2D sprite games.

Pre-transforming the vertices is super expensive when you have 3D meshes with thousands of vertices each (that may have much more than just a position to calculate) so in 3D you absolutely want to do as much as possible on the GPU, but doing it on the CPU for a couple hundred 2D rectangles is entirely reasonable, even on a cell phone.

If you do want to do it all the GPU, you really want to use *instancing*. In such a case you have just a single VBO for a quad. You then, each frame, fill in a dynamic VBO or texture with all the transformation matrices and UV coordinates and such for every sprite (which not much cheaper than just filling in the regular VBO for each sprite), and then let the GPU draw that same quad X times, once for each transformation matrix and other data.

Drawing each sprite individually, with its own transformation, is really bad. Your GPU has hundreds or even thousands of cores meant to process large volumes of data at once but you end up asking it to do a whole 4 vertices at a time. Not the best utilization. Batching your draws together can scale your performance by a very very large factor on modern hardware, again, even phones. It can be the difference between getting 40 FPS with two dozen sprites or 400 FPS with a thousand sprites. (Of course, profile your specific app and hardware to get an accurate measure of the speedup).

Instancing has historically been poorly supported by desktop GL drivers, so you might find it's faster overall to just pre-transform everything even if, in theory, it shouldn't be. Again, though, either method is much more efficient than drawing each sprite individually.

There are a number of articles on this site about instancing if you're interested in looking up more information on that.
> 2 votes

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


title: 2D Vector Compass Direction

text:
# Question
Title: 2D Vector Compass Direction
Relating to this question; What's the best way of transforming a 2D vector into the closest 8-way compass direction?

My query is if this would work in the following order(below) and if so, how would i achieve that?

```
 enum compassDir {
    S = 0, SE = 1,
    E = 2, NE = 3,
    N = 4, NW = 5,
    W = 6, SW = 7
};

```

# Answer
The unit vectors for the eight compass directions can easily be hardcoded into an array in the same order as your **enum**. Then one simply uses the dot-(or inner-)product of the given vector against the vector array. The closest compass direction will yield the maximal dot-product value.
> 0 votes

---
Tags: sprites, vector
---


# Question
Title: Why use matrix transform for 2D camera scrolling?
I am making a test game where I want the level to be constantly scrolling. To create this effect I have established a camera class which simply stores a vector2 position and an enum direction. It also contains a public method to 'move' which simply changes the position at a fixed rate. I then use this position when looping through my array of tiles when drawing. This all works fine.

However, I have been told that I should be using a Transform matrix to move the camera, and that I should provide this when I start the spritebatch. I am a little confused a.) how this works? as if I am only giving it when spritebatch begins how does it know to keep changing position? b.) Why do it as surely I still need the camera position for when I loop through tiles?

AT the moment I can't get it to work, but that's no surprise as I dont completely understand how it is meant to work. Currently in my attempt (code to follow) the tiles being drawn changes which means the cameras position is changing, but the position of the viewport remains unchanged (i.e. at the camera origin). I would really appreciate some advice/guidance on how its supposed to be used?

Camera:

```
 class Camera {

    // The position of the camera.
    public Vector2 Position {
        get { return mCameraPosition; }
        set { mCameraPosition = value; }
    }
    Vector2 mCameraPosition;

    public Vector2 Origin { get; set; }

    public float Zoom { get; set; }

    public float Rotation { get; set; }

    public ScrollDirection Direction { get; set; }

    private Vector2 mScrollSpeed = new Vector2(20, 18);

    public Camera() {
        Position = Vector2.Zero;
        Origin = Vector2.Zero;
        Zoom = 1;
        Rotation = 0;
    }

    public Matrix GetTransform() {
        return Matrix.CreateTranslation(new Vector3(mCameraPosition, 0.0f)) *
               Matrix.CreateRotationZ(Rotation) *
               Matrix.CreateScale(Zoom, Zoom, 1.0f) *
               Matrix.CreateTranslation(new Vector3(Origin, 0.0f));
    }

    public void MoveCamera(Level level) {
        if (Direction == ScrollDirection.Up)
        {
            mCameraPosition.Y = MathHelper.Clamp(mCameraPosition.Y - mScrollSpeed.Y, 0, (level.Height * Tile.Height - level.mViewport.Height));
        }
    }

```

Level:

```
 public void Update(GameTime gameTime, TouchCollection touchState) {

            Camera.MoveCamera(this);
 }

 public void Draw(SpriteBatch spriteBatch) {
        //spriteBatch.Begin();
        spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullCounterClockwise, null, mCamera.GetTransform());

        DrawTiles(spriteBatch);

        spriteBatch.End();
    }

```

Game - just calls the draw within level:

```
  protected override void Draw(GameTime gameTime)  {
        mGraphics.GraphicsDevice.Clear(Color.Black);

        //mSpriteBatch.Begin();

        // Draw the level.
        mLevel.Draw(mSpriteBatch);

        //mSpriteBatch.End();

        base.Draw(gameTime);
    }

```

I played around with the suggestion from craftworkgames. When I did draw all tiles, the fr tanked to around 15 from 30 - probably because the levels are pretty big.

So what I have done is apply the matrix and move in update (as suggested) but in draw I use the cameras position for looping through tiles (i.e. start counter at left and end at right tile). This all works well and I'm happy with it :-)

My new issue lies in the player. Obviously as I am now moving the camera rather than the level, the player gets left behind by the camer as its position stays fixed. I have thought of two solutions to this problem, the first is to simply consider the cameras position when drawing the player. I.e. in the draw funcion simply add the camera position to the player position. The second is to start a new sprite batch for the player which has no transform. i.e. end the spritebatch after drawing the tiles then start a new one when drawing the player. I know both will work, but I cant make heads of tails of which would be better in terms of performance/good coding? I am not sure what the performance implications are from starting the batch twice?

# Answer
> 15 votes
## Camera matrix transformations are easy

Creating a basic camera is easy. Below will get you started with the basics. Moving it around, rotating, and scaling. Moving every 2d sprite isn't much of an issues but if you factor in either scaling or rotation then it gets really hard to apply to every sprite individually.

```
class Camera2D
{
    public float Zoom { get; set; }
    public Vector2 Location { get; set; }
    public float Rotation { get; set;}

    private Rectangle Bounds { get; set; }

    private Matrix TransformMatrix
    {
        get: {
            return
                Matrix.CreateTranslation(new Vector3(-Location.X, -Location.Y, 0)) *
                Matrix.CreateRotationZ(Rotation) *
                Matrix.CreateScale(Zoom) *
                Matrix.CreateTranslation(new Vector3(Bounds.Width * 0.5f, Bounds.Height * 0.5f, 0));
        }
    };

    public Camera2D(Viewport viewport)
    {
        Bounds = viewport.Bounds;
    }
}

```

## It makes it really easy to convert between coordinate system definitions

To go from screen to world space simply. This is commonly used to get the location of the mouse in the world for object picking.

```
Vector2.Transform(mouseLocation, Matrix.Invert(Camera.TransformMatrix));

```

To go from world to screen space simply do the opposite.

```
Vector2.Transform(mouseLocation, Camera.TransformMatrix);

```

There is no draw back to using a matrix other than it takes a little learning.

## Its easy to get the visible area

```
public Rectangle VisibleArea {
    get {
        var inverseViewMatrix = Matrix.Invert(View);
        var tl = Vector2.Transform(Vector2.Zero, inverseViewMatrix);
        var tr = Vector2.Transform(new Vector2(_screenSize.X, 0), inverseViewMatrix);
        var bl = Vector2.Transform(new Vector2(0, _screenSize.Y), inverseViewMatrix);
        var br = Vector2.Transform(_screenSize, inverseViewMatrix);
        var min = new Vector2(
            MathHelper.Min(tl.X, MathHelper.Min(tr.X, MathHelper.Min(bl.X, br.X))),
            MathHelper.Min(tl.Y, MathHelper.Min(tr.Y, MathHelper.Min(bl.Y, br.Y))));
        var max = new Vector2(
            MathHelper.Max(tl.X, MathHelper.Max(tr.X, MathHelper.Max(bl.X, br.X))),
            MathHelper.Max(tl.Y, MathHelper.Max(tr.Y, MathHelper.Max(bl.Y, br.Y))));
        return new Rectangle((int)min.X, (int)min.Y, (int)(max.X - min.X), (int)(max.Y - min.Y));
    }
}

```

You can simply transform the cameras corners and get their location in world space. Min and max the x,y values and you can get a rectangle around the viewable space. Very useful for culling and optimizing draw calls.

# Answer
> 5 votes
Applying a matrix to your SpriteBatch transforms the entire draw call at once. This means you don't need to use your camera in your DrawTiles method at all.

It could become a lot simpler like so:

```
    // Loop through the number of visible tiles.
    for (int y = 0; y <= tiles.GetUpperBound(1); y++) {
        for (int x = 0; x <= tiles.GetUpperBound(0); x++) {

                // If the tile is not an empty space.
                if (tiles[x, y].Texture != null) {
                     // Get the position of the visible tile within the viewport by multiplying the counters by the tile dimensions
                     // and subtracting the camera offset values incase the position of the camera means only part of a tile is visible.
                     Vector2 tilePosition = new Vector2(x * Tile.Width, y * Tile.Height);
                     // Draw the correct tile
                     spriteBatch.Draw(tiles[x, y].Texture, tilePosition, Color.White);
                }
        }
    }

```

So the point of using a matrix is so that you don't have to think about it. Just draw things and move the camera around independently.

Also, your MoveCamera method looks a little strange. It's very unusual to have a camera class that takes a Level as a dependency. A more typical implementation would look like this:

```
public void MoveCamera(float deltaX, float deltaY) {
    mCameraPosition.X += deltaX;
    mCameraPosition.Y += deltaY;
}

```

Then in your Update method you might do something like this:

```
    if (Direction == ScrollDirection.Up)
    {
        mCamera.MoveCamera(mScrollSpeed.Y, 0);
    }

```

Overall, my suggestion is to keep it simple. Get it working the simplest way fist and build on it. Try not to write highly optimized code until you've got the basics working first. You may find that rendering every tile every frame is not so bad.

EDIT: For second part of question.

While it's true that you want to keep your batch count low, having 2 or 3 shouldn't be a problem at all. So if you have a good reason to create a second sprite batch just do it.

That said, there's probably not a good reason to use a second sprite batch in this case. More likely, you want to draw your player in the exact same way you draw tiles in the same sprite batch with the camera transform applied.

It's a little hard to tell why your player is getting left behind without looking at some code but it stands to reason that if you draw your player at the exact same position as a tile, he / she will appear at the same position with the same sprite batch.

For example, if you want the player to appear on tile 10, 10 you could do this:

```
var playerPosition = new Vector2(10 * Tile.Width, 10 * Tile.Height);
spriteBatch.Draw(player.Texture, playerPosition, Color.White);

```

Try to get into the mindset of thinking about drawing things where they are and the camera literally moves the entire "scene" into view. That's what your matrix transform is doing.

---
Tags: xna, c#, camera, monogame, side-scroller
---


# Question
Title: Game only runs at 60fps in windowed mode with a 120hz monitor?
In fullscreen the game will run at 120fps fine, the correct refresh rate for the monitor, but in windowed mode it only runs at 60fps. If I disable VSync then it runs at thounsands of fps so it's not a case of a lack of performance. I've correctly set the refresh rate in the ModeDescription.

# Answer
In windowed mode in Windows Vista and Windows 7, as well as OS X and many modern Linux desktop incarnations, the application has *zero* control over refresh. The application's front buffer is really just another off-screen surface used by a compositing system, like `dwm.exe` in Windows, which then composites the final full desktop image. It may run at a different frame rate than you want, and your application's rendering may be limited to that rate (since it has no reason or ability to worry about the monitor's native rate).
> 4 votes

---
Tags: directx11, slimdx, vsync
---


# Question
Title: Storing tile grid in a matrix: row major vs column major
I'm using a generic matrix container to store the tile grid for my RTS game.

This is where I am confused: a matrix is traditionally row major, i.e. matrix(0, 10) means 'at 0th row, 10th column.' A map on the other hand is 'column major,' i.e. grid(0, 10) intuitively means 'a tile at X=0, Y=10.'

This leads to a quite a few places where I need to swap X and Y to access proper element of the map.

I tried to make them both consistent (i.e. make a matrix column major or a grid row major) but that adds more confusion, maybe because I'm a slave of my habits.

How should I do this?

# Answer
> 2 votes
"Row-major" and "column-major" are describing the storage layout of the data, *not* the indexing API. What you have provided in your question is a decision between indexing a conceptual 2D grid as `(x, y)` pairs or as `(row, column)` pairs (essentially `y, x` pairs, since rows stack vertically).

You can implement either indexing interface regardless of the underlying storage layout. Consequently, it generally makes more sense to make the indexing APIs consistent.

It will be somewhat less error-prone and easier to maintain. An alternative is to make it very clear when you are doing `(row, column)` access by naming the function `getValueAtRowColumn` or something obvious like that.

# Answer
> 0 votes
I usually store the map in a 1D array and then have accessor-functions that take the intuitive (x, y) format:

```
// 0 = ground
// 1 = wall
// 3 = door
tiles = [ 0,0,0,0,0,0,0,
          0,0,0,1,1,1,1,
          0,0,0,1,0,0,0,
          0,0,0,1,0,0,0,
          0,0,0,2,0,0,0,
          0,0,0,1,1,1,1 ]

map_width = 7
map_height = 6

function validate_coordinates(x, y):
    if 0 < x < map_width or 0 < y < map_height:
        throw Error

function get_tile(x, y):
    validate_coordinates(x, y)
    return tiles[y * map_width + x]

function set_tile(x, y, t):
    validate_coordinates(x, y)
    tiles[y * map_width + x] = t

```

If you're using C++ you can even define the accessor functions with the preprocessor to avoid the overhead.

# Answer
> 0 votes
Not directly an answer but too large for a comment...

You actually want to break down a tile grid into smaller chunks.

Reasoning: say you are looking at a row-major matrix. If you are drawing just the visible section of the screen, how far away in memory is the first visible tile of the second row compared to the last visible tile of the first row? If you just have a huge row-major tile matrix, the answer is "the length of the row." That is rarely as efficient as it could be.

Break your world into smaller NxN chunks, where N is a relatively small number. At that point, row-major is certainly convention for tiles, but it really doesn't matter. Every tile on screen is relatively close to the tiles near it in memory.

Draw whole chunks at a time (rather than whole rows or columns at a time) to leverage this fact.

The end result is that your indexing API kind of becomes irrelevant; just pick whatever you want and know that locality of reference will usually be pretty high.

This also has advantages in data streaming from files or the network. You can more easily load just the nearby chunks and now worry about tile data far away. Maybe not super relevant for an RTS but handy in the general sense.

# Answer
> 0 votes
Here is an abstract base class for storing a grid of tiles ( from my HexgridUtilities library, hence the naming scheme:

```
  public abstract class BoardStorage<THex> : IDisposable {
    /// <summary>Initializes a new instance with the specified hex extent.</summary>
    /// <param name="sizeHexes"></param>
    protected BoardStorage(Size sizeHexes) {
      MapSizeHexes   = sizeHexes;
    }

    /// <summary>Extent in hexes of the board, as a <see cref=" System.Drawing.Size"/> struct.</summary>
    public          Size MapSizeHexes           { get; private set; }

    /// <summary>Returns the <c>THex</c> instance at the specified coordinates.</summary>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design",
      "CA1043:UseIntegralOrStringArgumentForIndexers")]
    public abstract THex this[HexCoords coords] { get; internal set; }

    /// <summary>Returns whether the hex with <see cref="HexCoords"/> <c>coords</c> is
    /// within the extent of the board.</summary>
    public          bool IsOnboard(HexCoords coords) {
      return 0<=coords.User.X && coords.User.X < MapSizeHexes.Width
          && 0<=coords.User.Y && coords.User.Y < MapSizeHexes.Height;
    }

    /// <summary>Performs the specified <c>action</c> serially on all hexes.</summary>
    public abstract void ForEach(Action<THex> action);

    /// <summary>Performs the specified <c>action</c> in parallel on all hexes.</summary>
    public abstract void ParallelForEach(Action<THex> action);

    #region IDisposable implementation with Finalizeer
    bool _isDisposed = false;
    /// <inheritdoc/>
    public void Dispose() { Dispose(true); GC.SuppressFinalize(this); }
    /// <summary>Anchors the Dispose chain for sub-classes.</summary>
    protected virtual void Dispose(bool disposing) {
      if (!_isDisposed) {
        if (disposing) {
        }
        _isDisposed = true;
      }
    }
    /// <summary>Finalize this instance.</summary>
    ~BoardStorage() { Dispose(false); }
    #endregion
  }

```

It is desired that the client application not care whether a row-major or column-major ordering has been used, as his is an implementation detail. In fact, as Sean notes, it is often desired to use a blocked storage. Here is a blocked implementation of the abstract class above:

```
/// <summary>A <c>BoardStorage</c> implementation optimized for large maps by blocking
/// 32 x 32 arrays of hexes for improved caching.</summary>
/// <remarks>This <c>BoardStorage</c> implementation stores the board cells in blocks
/// that are 32 x 32 cells to provide better localization for the Path-Finding and
/// Field-of-View algorithms.</remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design",
  "CA1034:NestedTypesShouldNotBeVisible"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "x")]
public sealed class BlockedBoardStorage32x32 : BoardStorage<THex> {
  const int _grouping = 32;
  const int _buffer   = _grouping - 1;

  /// <summary>TODO</summary>
  public BlockedBoardStorage32x32(Size sizeHexes, Func<HexCoords,THex> initializer)
    : base (sizeHexes) {
    backingStore  = new List<List<List<THex>>>((MapSizeHexes.Height+_buffer) / _grouping);
    for(var y = 0;  y < backingStore.Capacity;  y++) {
      backingStore.Add(new List<List<THex>>((MapSizeHexes.Width+_buffer) / _grouping));
      for(var x = 0; x < backingStore[y].Capacity; x++) {
        backingStore[y].Add(new List<THex>(_grouping*_grouping));
      }
    }

    Parallel.For(0, backingStore.Capacity, y => {
      var boardRow    = backingStore[y];
      for(var x = 0;  x < boardRow.Capacity;  x++) {
        var boardCell = backingStore[y][x];
        for (var i=0; i<_grouping; i++) {
          for (var j=0; j<_grouping; j++) {
            var coords = HexCoords.NewUserCoords(x*_grouping+j,y*_grouping+i);
            boardCell.Add(IsOnboard(coords) ? initializer(coords) : default(THex));
          }
        }
      }
    } );
  }

  /// <summary>TODO</summary>
  public override THex this[HexCoords coords] {
    get {
      var v = coords.User;
      return IsOnboard(coords)
        ? backingStore [v.Y/_grouping]
                       [v.X/_grouping]
                       [(v.Y % _grouping) * _grouping + v.X % _grouping]
        : default(THex);
    }
    internal set {
      var v = coords.User;
      backingStore [v.Y/_grouping]
                   [v.X/_grouping]
                   [(v.Y % _grouping) * _grouping + v.X % _grouping] = value;
    }
  }

  /// <inheritdoc/>
  public override void ForEach(Action<THex> action) {
    if (action==null) throw new ArgumentNullException("action");
    foreach(var hex in backingStore.SelectMany(lh=>lh).SelectMany(lh=>lh)) action(hex);
  }

  /// <summary>TODO</summary>
  public override void ParallelForEach(Action<THex> action) {
    Parallel.ForEach<THex>(
      backingStore.SelectMany(lh=>lh).SelectMany(lh=>lh).Where(h=>h!=null),
      hex => action(hex)
    );
  }

  List<List<List<THex>>> backingStore { get; set; }
}

```

More details, as well as a flat row-major implementation, are available here: Hexgrid Utilities for Board Game Implementations.

---
Tags: matrix, grid
---


# Question
Title: How can I use D3DXLoadMeshFromX with Direct3D 11?
I'm trying to write some class for loading meshes from X files.

But I can't use the function `D3DXLoadMeshFromX` because its third parameter is `LPDirect3DDevice9`.

In my D3D initialization code I don't have variable of this type. Did I initialize D3D incorrectly? How can I call this function?

# Answer
D3DXLoadMeshFromX is not supported in DirectX 11.

You will have to create your own model importer for a file format. Something simple like .obj would be a good place to start.
> 2 votes

# Answer
`LPDirect3DDevice9` is an alias for the type `IDirect3DDevice9 *`, which is a pointer to a Direct3D 9 device object. You are using D3D11, which means you have a completely incompatible device interface. Your device initialization is (probably) fine, you will just not be able to use `D3DXLoadMeshFromX` because it's only supported on an older version of Direct3D.

D3DX was deprecated after D3D10. The functionality you are looking for is no longer available as part of the core SDK, you will need to find it elsewhere.

You can either write your own, for any number of file formats including `.X` (`.obj` is popular and Google can help you find tutorials) or utilize a 3rd party library such as Assimp.
> 1 votes

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


title: Having 1 button for multiple purposes

text:
# Question
Title: Having 1 button for multiple purposes
Consider the following: you have a space invaders game. The 'hero' has 2 abilities - a normal attack which shoots standard bolts of whatever and a special attack which hits harder. The special attack can't be spammed.

There are a lot of ways to approach it: Number of times it can be used per level. It will use energy which is slowly regenerated and many more, but for our example let's consider that the 'hero' will not have any of those options and that the only possibilities are:

1) The ability must be charged

2) The ability has a cool down.

The question is: "What is the difference to the player when having 1 button per ability and multiple abilities per button?"

Of course, by this point I have to share that our imaginary game is not made for touch screens (Since if it was then it is pretty obvious that you want as little buttons as possible)

What I can think of is that when holding the button to "charge" it will give the player the impression that something strong is going to be unleashed. The downside of this is that this locks down the possibility to shoot the power up in the middle of combat.

# Answer
This reminds me of a fairly well known usability story, where a conference was disrupted because the projector had a single button. The button would move forward a slide if pressed for a short time, or back a slide if pressed for longer, but of course this was not obvious to the presenters. Source: here

Pros:

* It's just one button - nobody will complain that their fingers slipped and they couldn't understand your complex keymap (especially nice for those new to PC games)
* Personally I think it feels cool to have one button do multiple things

Cons:

* On almost anything games are developed for, using just one button for multiple functions which may not be obvious could seem like an unnecessary limitation - a cool factor that might not be worth the effort for players when two buttons would be so much simpler
* There are always going to be people who are less able to use a fast-paced-tap vs. hold distinction, as well as those with various disabilities, people who use keyboard helpers such as StickyKeys, etc - these people may only have easy access to one of the multiple abilities
* People don't always read/understand the manual or instructions, so making the distinction obvious using the gameplay only could be difficult
* As you said yourself, the abilities must not need to be performed at the same time, as this won't really be possible

I think you could potentially avoid most of the cons and maximise the pros by some visual indication of whether a given input was going to result in ability X or Y, perhaps X if released quickly, with a bar filling as they held the key longer and a blip when Y was ready. Making the Y ability available on another key by default, or having an option to do so, would mean that people with slower reactions or other obstacles could still play the game. On the point of performing ability X *while* 'charging' ability Y, I would suggest either timers which allow small breaks in the charging (to release it for no longer than n milliseconds, thus using the other ability), or a charge bar which goes down much slower than it goes up, allowing the button to be released, and charging resumed at the player's discretion. (These two solutions might only be semantically different.)
> 3 votes

# Answer
you can afford to use multiple buttons if you're explicitly avoiding touch screens

There are several understood ways to make 1 button do multiple things:

(on screen buttons)

* double clicking
* left vs right clicking
* holding down vs pressing

(keys)

* ctrl + key
* shift + key
* holding down vs pressing

You don't want users to accidentally or unintentionally release the special, so however you activate it, it has to be very explicit.

I think multiple buttons (but as few as possible, in this case 2)

button1 could be used to spam the normal attack, and button2 to fire special
> 2 votes

---
Tags: game-design
---


# Question
Title: Trying to convert as3 Matrix to C++ glm matrix
I am trying to convert a library called DragonBones to C++ Opengl which allows you to use Flash based skeletal animation. I'm almost done but I am running into a problem. I am trying to transform the parent bone with the child bone when I load in the data. The as3 code(Im using hardcoded numbers to factor out any other problems) is

```
var matrix:Matrix = new Matrix();

    matrix.a =  1 * Math.cos(120);
matrix.b =  1 * Math.sin(120);
matrix.c = -1 * Math.sin(120);
matrix.d =  1 * Math.cos(120);
//Parent Point
matrix.tx = 10;
matrix.ty = 10;

var _helpPoint:Point = new Point();

//Child Point
_helpPoint.x = 40;
_helpPoint.y = 50;

matrix.invert();

var newPoint:Point = new Point();

newPoint = matrix.transformPoint(_helpPoint);

trace(newPoint.x)
trace(newPoint.y)

```

It comes out with x being 47.64987648428943 and y being 15.148903294693044

Now for GLM here is the code:

```
float a =   1 * cos(120);
float b =   1 * sin(120);
float c =  -1 * sin(120);
float d =   1 * cos(120);
float tx =  10;
float ty =  10;

glm::mat3 parentMatrix = glm::mat3(a,b,0,c,d,0,tx,ty,1);
glm::vec3 childPoint = glm::vec3(40,50,0);
parentMatrix = glm::inverse(parentMatrix);
glm::vec3 finalpoint = parentMatrix * childPoint;
printf("Final Point is %f, %f \n", finalpoint.x, finalpoint.y );

```

Which comes out to be X:61.597794 Y:17.484602

I think there is something wrong when I am multiplying the parentMatrix and childPoint because if you set the tx and ty to 0 in the as3 code it comes out with the same output as anything you put in tx and ty for glm. So for some reason the tx and ty in glm is not factoring into the equation. Does anyone know what I am doing wrong? Thanks in advance

# Answer
> 0 votes
3 by 3 Matrix can't handle translations.

You need to use a 4 by 4 matrix

```
float a =   1 * cos(120);
float b =   1 * sin(120);
float c =  -1 * sin(120);
float d =   1 * cos(120);
float tx =  10;
float ty =  10;

glm::mat4 parentMatrix = glm::mat4(a,b,0,0,c,d,0,0,0,0,1,0,tx,ty,0,1);
glm::vec4 childPoint = glm::vec4(40,50,0,1);
parentMatrix = glm::inverse(parentMatrix);
glm::vec4 finalpoint = parentMatrix * childPoint;
printf("Final Point is %f, %f \n", finalpoint.x, finalpoint.y );

```

This code should return the expected results ;)

---

Edit: I tested to verify my hypothesis just in case... and it returns

> Final Point is 47.649876, 15.148905

So it should solve your problem.

---
Tags: c++, mathematics, actionscript-3, matrix, glm
---


# Question
Title: How do I make an equipped item affect the equipper?
I'm making a small text-based adventure in Objective-C. I have a `Player` class with four properties which represent the player's attributes (`strength`, `agility`, `stamina`, and `intelligence`). I also have a `Weapon` class. My goal is to put a weapon in the game that will increase the player's stats as long as it is equipped. How can I achieve this in an object-oriented fashion?

I could add a method to the `Weapon` class that will increase the player's attributes, and call the method only when a flag is set to true (which I would set to true when initiating this particular weapon, and leave false for all other weapons I create), but that seems a bit messy and not particularly object-oriented. I recently learned about the decorator design pattern. Would I be able to accomplish my goal using decorators?

# Answer
> 2 votes
Using decorators is not a good idea in this case, because you also want to un-equip items. When you wrap decorators in decorators in decorators and then want to remove a specific one inside that stack, it's a quite messy operation (especially because an object shouldn't be aware that an object it uses is just a decorator wrapping something else).

What you could do instead is have an abstract base class `StatModifier` with a modifier function for each stat a player can have. These modifiers receive a value (base value) and return a value of the same type (modified value). The default implementation in the base class would just return the value unchanged.

The Player class would then have a vector of `StatModifier`s which represents the currently active modifiers (equipment, buffs etc.). When, for example, the method `Player.getStrength()` is called, the implementation would call the modifyStrength method of each StatModifier to "filter" the result value.

I don't know objective-c, so this example should be considered pseudocode:

```
List<StatModifier> modifiers;

int getStrength() {
    int strength = this.baseStrength;
    foreach (modifier in this.modifiers) {
        strength = modifier.modifyStrength(val);
    }
    return strength;
}

```

# Answer
> 1 votes
I would make a base class for weapons/armor in which all weapons/armor inherit and have the base class include the stats so you don't need to access a specific weapon/armor. Then when you need the stats just add up the weapon/armor stats and the players.

---
Tags: objective-c, text-based, gameobject
---


# Question
Title: How to make an event appear after one event has been activated on RPG MAKER VX ACE?
I am trying to create my first RPG, and I having some difficulty to make an event appear after an event had been activated, and then disappear later, only to reappear after the player activated an event (to cut off an area during certain times).

How would I do this in RPG Maker?

# Answer
There are two ways that you can go about this, you can use a switch, or you can use a variable.

A Switch has an on-off state, you set it to on and then you set one of the pages in the event manager to check the state of the switch. If the switch is in the proper position then you can make the person say something else.

Variables can store different values. But the way that you would go about it is the same as a switch would be. You store a value with the variable, check it with one of your pages and then display different informations based on what comes up.

Alternatively, IIRC, you can also put a check for the state of a switch or the value of a variable in the event-logic-flow-window-thing (I don't remember what it's called). That should let you do the same thing.
> 3 votes

---
Tags: rpg, rpg-maker-vx
---


# Question
Title: How would I make an event option change after an event is used on RPG MAKER VX ACE?
I am trying to make my first RPG, and I am trying to make someone say something talking to someone once, but then when talking them to a second time, they something else.

How would I do that?

# Answer
Check this answer for a bit of information on how you can use switches and variables.

To achieve this, you are also going to use a switch. But you can be a bit more efficient (and not waste global switch/variable space) by using a local one for it.

It should be on the right pane of the event manager (I think they are labeled A, B, C, D). Basically you would set it to true after you've spoken to the person, then on another page check to see if it was set and output different dialog if it was.
> 2 votes

---
Tags: rpg, rpg-maker-vx
---


# Question
Title: Using two shaders instead of one with IF statements
I've been working on porting a relatively large opengl ES 1.1 source to ES 2.0.

In OpenGL ES 2.0 (which means, everything uses shaders), I want to draw a teapot three times.

1. The first one, with a uniform color (ala the old glColor4f).
2. The second one, with a per-vertex color (the teapot has its array of vertex color as well)
3. The third one, with per-vertex texture
4. And maybe a fourth one, with both per-vertex texture and color. And then maybe a 5th one, with normals as well..

There are two choices I have with implementation, as far as I know. The first is to make a shader that supports all of the above, with a uniform that is set to change the behavior (e.g use the singular color uniform, or the per-vertex color uniform).

The second choice is to create a different shader for each situation. With some custom shader preprocessing, it's not that complicated to do, but the concern is the performance cost in switching shaders between drawing objects. I've read that it's not trivially small.

I mean, the best way to go about this is to build both and measure, but it'd be good to hear any inputs.

# Answer
The performance cost of branching can be not trivially small too. In your case all vertices and fragments being drawn will be taking the same path through your shaders, so on *modern desktop* hardware it would not be as bad as it could be, but you're using ES2 which implies that you're not using modern desktop hardware.

The worst case with branching will go something like this:

* both sides of the branch are evaluated.
* a "mix" or "step" instruction will be generated by the shader compiler and inserted into your code to decide which side to use.

And all of these extra instructions will be run for each vertex or fragment that you draw. That's potentially *millions* of extra instructions to be weighed against the cost of a shader change.

Apple's "OpenGL ES Programming Guide for iOS" (which can be taken as representative for your target hardware) has this to say about branching:

> **Avoid Branching**
>
> Branches are discouraged in shaders, as they can reduce the ability to execute operations in parallel on 3D graphics processors. If your shaders must use branches, follow these recommendations:
>
> * Best performance: Branch on a constant known when the shader is compiled.
> * Acceptable: Branch on a uniform variable.
> * Potentially slow: Branching on a value computed inside the shader.
>
> Instead of creating a large shader with many knobs and levers, create smaller shaders specialized for specific rendering tasks. There is a tradeoff between reducing the number of branches in your shaders and increasing the number of shaders you create. Test different options and choose the fastest solution.

Even if you're satisifed that you're in the "Acceptable" slot here, you still need to consider that with 4 or 5 cases to select between, you're going to be raising the instruction counts in your shaders. You should be aware of the instruction count limits on your target hardware and ensure that you don't go above them, quoting again from the Apple link above:

> OpenGL ES implementations are not required to implement a software fallback when these limits are exceeded; instead, the shader simply fails to compile or link.

None of this is to say that branching is *not* the best solution for your need. You correctly identified the fact that you should profile both approaches, so that's the final recommendation. But just do be aware that as shaders become more complex, a branching-based solution may well give much higher overhead than a few shader changes.
> 11 votes

# Answer
The cost of binding shaders may not be trivial, but it's not going to be your bottleneck unless you're rendering thousands of items without batching all the objects that use the same shaders.

Though I'm not sure if this applies to mobile devices, but GPUs aren't horrendously slow with branches if the condition is between a constant and a uniform. Both are valid, both have been used in the past an will continue to be used in the future, pick whichever one you think would be cleaner in your case.

Additionally, there are a few other ways to accomplish this: "Uber-shaders" and a little trickery with the way OpenGL shader programs are linked.

"Uber-shaders" are essentially the first choice, minus the branching, but you'll have multiple shaders. Instead of using `if` statements, you use the preprocessor - `#define`, `#ifdef`, `#else`, `#endif`, and compile different versions, including the proper `#define`s for what you need.

```
vec4 color;
#ifdef PER_VERTEX_COLOR
color = in_color;
#else
color = obj_color;
#endif

```

You can also break the shader up into separate functions. Have one shader that defines prototypes for all the functions and calls them, link a bunch of extra shaders that include the proper implementations. I've used this trick for shadow mapping, to make it easy to swap out how filtering is done on all objects without having to modify all the shaders.

```
//ins, outs, uniforms

float getShadowCoefficient();

void main()
{
    //shading stuff goes here

    gl_FragColor = color * getShadowCoefficient();
}

```

Then, I could have multiple other shader files that define `getShadowCoefficient()`, the necessary uniforms, and nothing else. For example, `shadow_none.glsl` contains:

```
float getShadowCoefficient()
{
    return 1;
}

```

And `shadow_simple.glsl` contains (simplified from my shader that implements CSMs):

```
in vec4 eye_position;

uniform sampler2DShadow shad_tex;
uniform mat4 shad_mat;

float getShadowCoefficient()
{
    vec4 shad_coord = shad_mat * eye_position;
    return texture(shad_tex, shad_coord).x;
}

```

And you could simply choose whether you wanted shading or not by linking a different `shadow_*` shader. This solution may very well have more overhead, but I'd like to think that the GLSL compiler is good enough to optimize away any extra overhead compared to other ways of doing this. I haven't ran any tests on this, but it's is the way I like to do it.
> 4 votes

---
Tags: opengl-es, glsl
---


# Question
Title: Should I render all of my HUD views to a single SurfaceView?
I'm using a `SurfaceView` and canvas to implement a game HUD, title screens etc., by overlaying standard Android view widgets over my `SurfaceView`. This works reasonably well and maintains an acceptable frame-rate, but it is a simple game with little happening on or off screen.

I have handlers flinging messages around and `runOnUiThreads` everywhere. Quite cumbersome. Can I draw all my views to the one `SurfaceView`, controlled by the main game thread? Is there an advantage to this?

# Answer
actually you could draw all that staff on your canvas but you need to handle that ui things from strach, like getting user touch points and detecting whether user touched a button or not
> -1 votes

---
Tags: android, html-canvas, gui
---