# Question
Title: Running a WindowsGL MonoGame release on end Machine
Can anyone tell me what is required of a PC to run a released MonoGame. I mean what software the PC needs to have installed to run the games. I have some problems running my released games on other PC's than my developer machine. They simply stops responding when I try to run them.

# Answer
> 1 votes
**Assuming you are using the exact same setup of VS2010/VS2012 as myself.**

Ensure all art/sound/effect assets File Properties are set properly.

*a. Build Action should be set to Content*

*b. Copy To Output Directory should be Copy if newer or Copy Always*

Using VS201X's Publish will provide an easy to use installer.

*a. The Setup.exe file will install .Net4.0 on the users machine if it is missing.*

*b. YourGame'sName.application will install the game.*

User will need to install OpenAl

---
Tags: monogame, release
---


title: Can't Build Cocos2Dx emscripten project

text:
# Question
Title: Can't Build Cocos2Dx emscripten project
I need to port a Cocos2D-x project to Web (JS+HTML5). I'm trying to compile cocos2D-x samples using the emscripten project for cocos2d-x, and I've followed this tutorial http://www.cocos2d-x.org/projects/cocos2d-x/wiki/Emscripten\_usage without success.

First, I followed the emscripten-specific guide using Linux Mint 15 with this tutorial: https://github.com/kripken/emscripten/wiki/Tutorial

And also on Windows 7 64-bit following this another tutorial: https://github.com/kripken/emscripten/wiki/Using-Emscripten-on-Windows

The emscripten samples worked ok. Then, I downloaded the Cocos2D-x project:

```
git clone https://github.com/cocos2d/cocos2d-x.git
git submodule update --init --recursive

```

This version from github, has the "proj.emscripten" project. But, when I try to compile the cocos2D-x project and samples with:

```
make -f Makefile.emscripten -j 8

```

...after compiling several modules, it stops at "cocos2d-x/extensions/proj.emscripten" with this error:

```
mingw32-make[1]: Leaving directory `c:/dev/GitHub/cocos2d-x/CocosDenshion/proj.emscripten'
mingw32-make -C extensions/proj.emscripten all
mingw32-make[1]: Entering directory `c:/dev/GitHub/cocos2d-x/extensions/proj.emscripten'
makefile:12: *** recipe commences before first target.  Stop.
mingw32-make[1]: Leaving directory `c:/dev/GitHub/cocos2d-x/extensions/proj.emscripten'
Makefile.emscripten:21: recipe for target `all' failed
mingw32-make: *** [all] Error 2

```

This happens on both systems: Windows and Linux. I've installed the same version of the required dependencies that apears on those tutorials. Does anybody know what I'm doing wrong? Is there any easier way to get cocos2D-x running on the web without using the cocos2D-x proj.emscripten?

**EDITED: There is an error on cocos2d-x/extensions/proj.emscripten/Makefile file.** Changing the line 11 from this:

```
-I../network

```

...to this:

```
-I../network \

```

...solves this problem. Now compiles some more modules, but now I'm getting compiler errors, like

```
error: no member named 'bind' on namespace 'std'

```

could be a problem with the C++ compiler standards C++0x, C++11...?

# Answer
> 2 votes
I solved it!

Mainly there was a problem of typing errors in some files, and the need to specify the C++11 standard in the compile commands. I think that this will be fixed oficially as the project get updated.

These are the steps I done (I asume that previously you have followed the original tutorial from http://www.cocos2d-x.org/projects/cocos2d-x/wiki/Emscripten\_usage):

1. Once you have Cocos2D-x downloaded using git, and Emscripten up and runing with all of its dependencies installed, copy all contents from the emscripten folder to (cocos2d-x-root)/external/emscripten
2. Copy the truetype font Arial.ttf (download it, or search it from within your system) to the folder: /Library/Fonts/Arial.ttf (it will not work if you don't have it in that place)
3. Edit cocos2d-x/extensions/proj.emscripten/Makefile

* Change line 11 from:

-I../network

* to:

-I../network \
4. Edit cocos2d-x/cocos2dx/proj.emscripten/Makefile

* Change line 145 from:

CXXFLAGS += -Wno-sequence-point

* to

CXXFLAGS += -Wno-sequence-point -std=c++11
5. Edit cocos2d-x/samples/Cpp/TestCpp/proj.emscripten/Makefile

* Add this new line at 474:

CXXFLAGS += -std=c++11
6. Edit cocos2d-x/cocos2dx/textures/CCTexture2D.cpp

* Change line 810 from:

ccTexParams texParams = {m\_bHasMipmaps?GL\_NEAREST\_MIPMAP\_NEAREST:GL\_NEAREST,GL\_NEAREST,GL\_NONE,GL\_NONE};

* to:

ccTexParams texParams = {(GLuint)(m\_bHasMipmaps?GL\_NEAREST\_MIPMAP\_NEAREST:GL\_NEAREST),(GLuint)GL\_NEAREST,(GLuint)GL\_NONE,(GLuint)GL\_NONE};

* and line 830 from:

ccTexParams texParams = {m\_bHasMipmaps?GL\_LINEAR\_MIPMAP\_NEAREST:GL\_LINEAR,GL\_LINEAR,GL\_NONE,GL\_NONE};

* to:

ccTexParams texParams = {(GLuint)(m\_bHasMipmaps?GL\_LINEAR\_MIPMAP\_NEAREST:GL\_LINEAR),(GLuint)GL\_LINEAR,(GLuint)GL\_NONE,(GLuint)GL\_NONE};

In my case I've got an additional problem (out of memory) when linking the TestCpp project. As I don't need it for now, I simply comment this line at the file cocos2d-x/Makefile.emscripten:

```
#   +$(MAKE) -C samples/Cpp/TestCpp/proj.$(PLATFORM) $@

```

Then, when you run:

```
make -f Makefile.emscripten -j 8

```

inside the cocos2d-x folder, it should compile without any errors, and you will have the .http, .js and .data files in cocos2d-x/samples/Cpp/HelloCpp/proj.emscripten/bin/release:

```
HelloCpp.data
HelloCpp.data.js
HelloCpp.js
index.html

```

Remember to copy those files to some web server and run from there, because It will not work in local. And that's all!

---
Tags: c++, javascript, html5, cocos2d-x
---


# Question
Title: System.Random giving duplicates in runtime
Normally, when I call this method of mine

```
    public static int Randomize(int min, int max)
    {
        Random r = new Random();
        return r.Next(min, max);
    }

```

I get a completely different number everytime.

But as soon as I start to use this method during runtime (60fps / 16 updates per ms), this method gives me almost only duplicates.

I can understand that `Random` could have not enough time to shuffle a random number, but how could I achieve a reliable random-method for ingame-runtime use?

# Answer
> 4 votes
Random doesn't need "time" to shuffle a random number. The algorithm generates a new number each time it's called, based on the current state (which changed during each call). Like any mathematical function, given input `A` will always produce the same output `B`. If you keep resetting `A` to the same value (by reinstantiating `Random` every time you use it) then of course you will keep getting the exact same "random" output `B`.

A very simple way to picture it is that it does something like:

```
class Random:
  int state = 0x718AE8F2 // or whatever default number
  int Next(int min, int max):
    int num = (max - min) * (this.state / INT_MAX) + min
    this.state = AdvanceState(this.state)
    return num

```

The actual algorithm in `AdvanceState` being used (could be one of many) does a lot of complicated bit manipulation/math when changing the state in order to make it seem random to a casual observer.

Creating a new Random() of course means you're always starting out with the same default seed/state and hence you always get the same number.

The advantage is that you can intentionally reset the state of `Random` (seeding it) if desired to get the same sequence of "random" output, which is handy for testing or sharing a randomly generated level with just a single number (the seed).

---
Tags: c#
---


title: Third person camera xna

text:
# Question
Title: Third person camera xna
I'm trying to create a third person camera in my XNA game. I'm able to move the model I have and the camera at the same time, although the camera is not "following" the model. The model moves faster than the camera. Ultimately, I want the camera to rotate with the model with the left and right keys, and move the model with forward and back.

This is in my update method

```
    if (keyState.IsKeyDown(Keys.D))
        {
            camera.Rotation = MathHelper.WrapAngle(camera.Rotation - (rotateScale * elapsed));
        }

        if (keyState.IsKeyDown(Keys.A))
        {
            camera.Rotation = MathHelper.WrapAngle(camera.Rotation + (rotateScale * elapsed));
        }

        if (keyState.IsKeyDown(Keys.W))
        {
            camera.MoveForward(moveScale * elapsed);
            player.Position += new Vector3(0.1f, 0f, 0f);
        }

        if (keyState.IsKeyDown(Keys.S))
        {
            camera.MoveForward(-moveScale * elapsed);
            player.Position += new Vector3(-0.1f, 0f, 0f);
        }

```

player is the model I'm using. Currently the A and D keys don't do anything with the model.

```
    public class Camera
{
    private Vector3 position = Vector3.Zero;
    private Vector3 lookAt;
    private Vector3 baseCameraReference = new Vector3(0, 0, 1);

    private bool needViewResync = true;

    private float rotation;

    public Matrix Projection { get; protected set; }
    private Matrix cachedViewMatrix;

    public Vector3 Position
    {
        get
        {
            return position;
        }

        set
        {
            position = value;
            UpdateLookAt();
        }
    }

    public float Rotation
    {
        get
        {
            return rotation;
        }

        set
        {
            rotation = value;
            UpdateLookAt();
        }
    }

    public Matrix View
    {
        get
        {
            if (needViewResync)
                cachedViewMatrix = Matrix.CreateLookAt(Position, lookAt, Vector3.Up);

            return cachedViewMatrix;
        }
    }

    public Camera(Vector3 position, float rotation, float aspectRatio, float nearClip, float farClip)
    {
        Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, nearClip, farClip);
        MoveTo(position, rotation);

    }

    private void UpdateLookAt()
    {
        Matrix rotationMatrix = Matrix.CreateRotationY(rotation);

        Vector3 lookAtOffset = Vector3.Transform(baseCameraReference, rotationMatrix);
        lookAt = position + lookAtOffset;
        needViewResync = true;
    }

    private void MoveTo(Vector3 position, float rotation)
    {
        this.position = position;
        this.rotation = rotation;
        UpdateLookAt();
    }

    public Vector3 PreviewMove(float scale)
    {
        Matrix rotate = Matrix.CreateRotationY(rotation);
        Vector3 forward = new Vector3(0, 0, scale);
        forward = Vector3.Transform(forward, rotate);
        return (position + forward);
    }

    public void MoveForward(float scale)
    {
        MoveTo(PreviewMove(scale), rotation);
    }
}

```

I also want to offset the camera for obvious reason, but changing the values in the variable baseCameraReference doesn't change what I want it to

# Answer
> 1 votes
If I understand your requirements, you want your camera to always be behind your player (but maybe offset slightly) and move and rotate with the player. The camera should stay in the same location and orientation (rotation) relative to the player.

Then all the rotation and movement code for updating your camera can be eliminated, it is just doing the same movement and rotation as you want the player to do anyway. Why do it twice? Spend all your coding effort moving and rotating the player only.

After that, simply send the updated players matrix to the camera update method after the player is moved and rotated and use the positional and rotational info from that player's matrix to build the camera.

```
Public void CameraUpdate(Matrix playerMatrix)
{
  camPosition = playerMatrix.Translation + (playerMatrix.Backward * trailingDistance);
  camTarget = playerMatrix.Translation;

  view = Matrix.CreateLookAt(camPosition, camTarget, Vector3.Up);
}

```

That's all you need to update the camera. If you want to offset the camera's position (say, to position it over the player's shoulder or something), you can add more offsets when setting the position, like this:

```
camPosition = playerMatrix.Translation +
                (playerMatrix.Backward * trailingDistance) +
                (playerMatrix.Up  * verticalOffset) +
                (playerMatrix.Left * lateralOffset);

```

same with the target if you want it to seem as if it's looking past the player instead of at him:

```
camTarget = playerMatrix.Translation + (playerMatrix.Up * someOffset);

```

# Answer
> 0 votes
This is the part of my player class that I'm looking at

```
    public void Render(Matrix view, Matrix projection)
        {
            foreach (ModelMesh mesh in mymodel.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    //effect.EnableDefaultLighting();
                    effect.World = transforms[mesh.ParentBone.Index]
                        * Matrix.CreateScale(Scale)
                        * Matrix.CreateRotationY(MathHelper.ToRadians(RotationY))
                        * Matrix.CreateRotationX(MathHelper.ToRadians(RotationX))
                        * Matrix.CreateTranslation(Position);

                    effect.View = view;
                    effect.Projection = projection;
                }
                mesh.Draw();
            }
        }

```

What you're saying is to use the matrix "transforms\[\]" while passing in the camera method?

```
    camera.CameraUpdate(player.transforms)

```

and then update that matrix based on input?

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


# Question
Title: Libgdx: Am I abusing Vector2? Is there a better way to do my position updates and rendering?
I'm simulating hair in a game. Currently I have a HairField object, which has a position defined by a Vector2. Each HairField has multiple Hair objects in a list, each with a position defined by a Vector2. Each hair has multiple HairParticle objects in a list, each with a Vector2 position. Like so:

```
HairField class
    Vector2 pos;  //  In world coords
    List<Hair> hairs;

Hair class
    HairField hairField;
    Vector2 pos;  //  Relative to parent HairField
    List<HairParticle> hairParticles;

    public Vector2 getWorldPos() {
        return pos.cpy().add(hairField.getWorldPos());
    }

HairParticle class
    Hair hair;
    HairParticle parent;
    Vector2 pos;  //  Relative to parent HairParticle

    public Vector2 getWorldPos() {
        return pos.cpy().add(hair.getWorldPos());
    }

```

My hair physics/rendering loop looks like the following:

```
for each (Hair h : hairField):
    HairParticle parent = null;
    for each (HairParticle p : h):
        if (parent==null) continue;
        //  get position info from each HairParticle's getWorldPos()
        //  update p, constraining to certain distance from parent
        //  render line from parent --> p

```

You can see that I'm calling a metric buttload of getWorldPos() methods on the particles, all so I can have information for updating/rendering the particle. Each of these calls involves multiple Vector2.cpy() calls and some vector math.

My question is, am I abusing Vector2's? They make for easy math, but I'm wondering if there's some more primitive (but faster) way I should be doing things. I've heard about transformation matrices, but don't know much about them yet (been reading). Does Libgdx expose some quicker way to be doing this math for updating/rendering that I should be using instead?

# Answer
> 1 votes
One of the problems that could be impacting performance is the fact that you're copying your position vector whenever you want a world position. It would be better for you to just have a field for the world position as well, and then you just alter both when you call setPosition.

```
Hair class
    HairField hairField;
    Vector2 pos;  //  Relative to parent HairField
    Vector2 worldPosition;  //  Relative to the world
    List<HairParticle> hairParticles;

    public Vector2 getWorldPos() {
        return worldPosition;
    }

    public void setPos(Vector2 pos) {
        this.pos = pos.cpy();
        this.worldPosition = pos.cpy().add(hairField.getWorldPos());
    }

```

It's not wrong to use Vector2, they're very helpful objects, but if you don't need all the added functionality, it might just be better to have a float x, y instead of a Vector2 object.

# Answer
> 3 votes
Did you find out which part of your game loop is it slowing down on android? Is rendering or logic, or both? You should profile exactly which part is slowing down and narrow it down.

Assuming you profiled every damned part of your code and you can't find what's making it slow. Then, on andorid, one possibility is garbage collector is taking a chunk of time per frame. GC slow downs can be fairly sporadic and hard to catch through only profiling time. If you're generating out tons of garbage every frame then GC might be slowing it down. GC is slow in general on Android (especially on older devices). So trace your code to see if all the Vector2 copies you made are tossed away(not referenced anymore) as fast as they are generated. You can check out how often and how long it took GC to collect garbage through DDMS view (google it up, I forgot specifics).

Further assuming that GC is your problem, then one way I know is to use an object pool. See https://code.google.com/p/libgdx/wiki/MemoryManagment

---
Tags: libgdx, vector, opengl-es2
---


# Question
Title: Creating big scene and little size chasing camera
I would like to create a climb based game, so I need to have a big scene and a camera that cover only a little part of it and chase my player. This image explains easier what I want:

How can I do it? I'm trying to resize my camera size only, but I don't get the desired result.

Thank you. s.

# Answer
Your idea is correct. The scene can be as big as you want. In fact, you don't need to bound it. You just create the correct camera and then set `camera.setChaseEntity(mainEntity);`

But you are not creating the camera correctly. Look at the constructor:

```
public BoundCamera(final float pX, final float pY, final float pWidth, final float pHeight, final float pBoundMinX, final float pBoundMaxX, final float pBoundMinY, final float pBoundMaxY) {
    super(pX, pY, pWidth, pHeight);
    this.setBounds(pBoundMinX, pBoundMinY, pBoundMaxX, pBoundMaxY);
    this.mBoundsEnabled = true;
}

```

In your case you need to set:

`new BoundCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, SCENE_MIN_X, SCENE_MAX_X, SCENE_MIN_Y, SCENE_MAX_Y);`

This example is doing exactly what you want (and more).
> 3 votes

---
Tags: 2d, camera, andengine, scene
---


title: AndEngine: edit elasticity on action

text:
# Question
Title: AndEngine: edit elasticity on action
I'm making a game for Android with AndEngine.

It's going quite well, but now I'm stuck on something. My main character has a elasticity set in its fixturedef so it bounces around throughout the game. Now i want the user to be able to not let the player bounce when he does a control.

So my question: how can I modify the elasticity of my character? Because I saw you can adjust the setDensity and setFriction, but I cant see the setElasticity....

Thanks in advance!

# Answer
Following way you can change the restitution or elasticity of any body in box2d.

```
ArrayList<Fixture> fixtureList = body.getFixtureList();
    for (Fixture fixture : fixtureList)
        fixture.setRestitution(0.5f);

```
> 1 votes

# Answer
This is because elasticity is expressed as a coeficient of **restitution**. Look for `setRestitution (float restitution)`.
> 0 votes

---
Tags: android, box2d, andengine
---


# Question
Title: How to handle scripted events in a 2d java game?
I'm in the planning phases of a 2D java game. The game is a tile-based platformer with some action-y parts to it, like a Metroidvania formula game.

The static portion of each stage is expressed as an x y grid of tiles - tile IDs correspond to drawable resources, and a boolean for collision (sky / air space doesn't cause collision with the player, but the ground or an elevated platform would for example)

Additionally, the game uses actors for dynamic things in the game - these could be monsters, boss mobs, moving platforms, checkpoints, powerups - anything that isn't a static tile.

I want to implement a java class ScriptedEvent, and include in each Level a linked list of scriptedevents for the stage.

ScriptedEvent may include a bool hasBeenActivated, bool canBeRepeated (for puzzle-like activities that may be re-ran by the player). I want each instance of ScriptedEvent to do an action, like MovePlayerTo(x,y), or combination of actions - SpawnEnemy(ID,x,y). Scripted events might also change the ID of a ground block to air, allowing the player to fall into a hidden room.

How do you accomplish this task in java? One thought would be to do eval() and have each event contain a string of steps. The steps then could be parsed out one by one from this large string, and interpreted as java code, handled by the main game logic.

Say a very simplfied example constructor might look like:

```
  ScriptedEvent ev1 = new ScriptedEvent("MovePlayer(200,0); PlaySound('teleport.wav'); SpawnItem(20,205,0);");

```

Where each function listed in the string would make the game logic do something.

Is there a better way to go about scripted events or should I roll with this solution? I don't really want to hard-code each event into a stage if I can avoid it.

# Answer
Separate the actual code and the events completely. I'd recommend using XML to describe the event. Create a schema that will be able to desribe any event and then implement a parser of the events.

For the parser, I'd recommend using XMLReader and it's method setContentHandler. Your own content handler can then implement methods like:

```
public void startElement(String uri, String localName, String qName,
        Attributes atts) throws SAXException {
    if("playSound".equals(qName)) {
        playSound(atts.getValue("soundName"));
    }
}

```

And your XML event will contain:

```
<playSound soundName="ding.wav"/>

```

If you want to use more powerful scripting, you can add some scripting language support. One of the easiest is DeeLang.
> 1 votes

---
Tags: java, 2d, scripting
---


# Question
Title: Move from point a, to point b, and determine the accuracy
Let's say I have a circle at point a (0,0), and I wish to move it to point b (23,58), whatever, how can I accurately do this with a speed variation if I wanted. (I'm doing this in javascript).

Every attempt I make ends up causing it to shake (as the accuracy is off) someone suggested clamping but I have no idea how to do this or where to even look to figure out how.

Any sources, examples, references, guides, tutorials... that correctly explain it regardless if it's one piece of the puzzle is appreciated.

If it helps, I'm using mouse clicks to determine the position where I should move the object to (Top-Down):

```
if (char.end.x != char.start.x || char.end.y != char.start.y) {
    char.distance = {};
    char.distance.x = char.end.x - char.start.x;
    char.distance.y = char.end.y - char.start.y;

    char.distance.hypot = Math.sqrt(
        char.distance.x * char.distance.x +
        char.distance.y * char.distance.y
    );

    char.distance.moves = char.distance.hypot / char.speed;
    char.start.x += Math.floor(char.distance.x/char.distance.moves);
    char.start.y += Math.floor(char.distance.y/char.distance.moves);
}

```

# Answer
> 2 votes
This is one way how you can do it: What you need is to parametrize the trajectory. This will be your parametrized line:

`y = m * x + b;`

Where `m` is the "slope", or how fast your trajectory grows, and `b` in your case is the `y` of the starting point (0) - so we can ignore it.

1) `y = m * x` for `x` from `[0, 23]`, where `m` in your case is `58/23`.

For speed variation you need another function that will give you `x` . Most simple one is of course linear function `x = minX + t * (maxX - minX)`, where `t` is time (in half time, travel half distance etc). But you can have arbitrary function. Let's consider a more complex function:

2) `x = minX + sqrt(t) * (maxX - minX)`, where `t` from `[0, 1]` (one second)

In you game loop to determine the position of the sprite, you simply need to get the `x` from second function (t is the time elapsed from the start of movement) and calculate `y` from the first function. If you use exactly these two functions, your circle will go very fast in the beginning and slow down until 0 speed at the end.

Note that I've made a lot of simplifications like I don't consider that you can move from right to left etc.

# Answer
> 0 votes
In the function that determines the varied speed you're moving at, add a check to see if the current displacement value + the current position are equal to or more than the target coordinates. If the displacement is greater than the distance between the target and current positions, set it to be exactly the difference. If not, leave it the way it is

# Answer
> 0 votes
Alright, so me and sm4 were on the right track with the flooring, the actual problem with the shaking can be solved by flooring the `character.distance.moves` and ceil the additions:

```
if (char.end.x != char.start.x || char.end.y != char.start.y) {
    char.distance = {};
    char.distance.x = char.end.x - char.start.x;
    char.distance.y = char.end.y - char.start.y;

    char.distance.hypot = Math.sqrt(
        char.distance.x * char.distance.x +
        char.distance.y * char.distance.y
    );

    char.distance.moves = Math.abs(Math.floor(char.distance.hypot / char.speed)) || 1;
    char.start.x += Math.ceil(char.distance.x/char.distance.moves);
    char.start.y += Math.ceil(char.distance.y/char.distance.moves);
}

```

---
Tags: 2d, mathematics, javascript, html-canvas
---


# Question
Title: Line draw on “even-q” vertical flat topped hex grid
I'm trying to implement a Line Draw or Line of Sight algorithm for my hex boardgame. Upon reading several different solutions from most common places like the Hex Bible, none of the algorithms adapted to my grid config (even-q as stated in Hex Bible) work.

Reference image:

What I want is an algorithm that given hex A and hex B returns all hexes that would be crossed by a line going from the center of A to the center of B, and in case of diagonal, going right through a division it selects both sides of it. As in A(0,1) and B(2,1) =\> {\[0,1\]\[1,1\]\[1,0\]\[2,1\]} for horizontal and A(1,0) B(0,2) =\> {\[1,0\]\[0,1\]\[1,1\]\[0,2\]} for diagonal.

An in-game example: character in A(0,1) shoots arrow towards B(6,1), the arrow will check for collision in Step 1: \[1,1\]\[1,0\], Step 2: \[2,1\], Step 3: \[3,1\]\[3,0\], Step 4: \[4,1\], Step5: \[5,1\]\[5,0\], Step 6: \[6,1\]

After a sleepless night I have come up with 3 different solutions: two adapted and one of my own. None of them gives perfect results because the math is flawed, so I would like some help.

All three solutions can be found and tested by downloading \[my git project\]\[3\]. The class is found at com.wartricks.tools.MapTools.java

Algorithm 1 as per hex bible:

```
public Array<Pair> getLOSCells(int x, int y, int x0, int y0) {
    final Array<Pair> highlights = new Array<Pair>();
    // PROBLEM! my offset system has 0,0 on the bottom left and is flat-top
    // coord2Offset gives valid results, but they don't translate well
    // for example my 0,1 should be 0,1,-1 but gets 0,-1,1 instead
    // this causes problems with rounding that make the line break
    final int[] cubeCoordsOrigin = MapTools.coordOffset2Cube(x, y);
    final int[] cubeCoordsDestination = MapTools.coordOffset2Cube(x0, y0);
    final int dx = cubeCoordsOrigin[0] - cubeCoordsDestination[0];
    final int dy = cubeCoordsOrigin[1] - cubeCoordsDestination[1];
    final int dz = cubeCoordsOrigin[2] - cubeCoordsDestination[2];
    float distance = Math.max(Math.abs(dx - dy), Math.abs(dy - dz));
    distance = Math.max(distance, Math.abs(dz - dx));
    if (distance > 0) {
        int[] previousCoord = new int[3];
        for (float i = 0; i <= distance; i++) {
            final float currentX = (cubeCoordsOrigin[0] * (i / distance))
                    + (cubeCoordsDestination[0] * (1 - (i / distance)));
            final float currentY = (cubeCoordsOrigin[1] * (i / distance))
                    + (cubeCoordsDestination[1] * (1 - (i / distance)));
            final float currentZ = (cubeCoordsOrigin[2] * (i / distance))
                    + (cubeCoordsDestination[2] * (1 - (i / distance)));
            final int[] currentCoord = roundCubeCoord(currentX, currentY, currentZ);
            if (!currentCoord.equals(previousCoord)) {
                final int[] offsetCoord = MapTools.coordCube2Offset(currentCoord[0],
                        currentCoord[1], currentCoord[2]);
                highlights.add(new Pair(offsetCoord[0], offsetCoord[1]));
                previousCoord = currentCoord;
            }
        }
    }
    return highlights;
}

public static int[] coordOffset2Cube(int x, int y) {
    final int[] coord = new int[3];
    coord[0] = x;
    coord[2] = y - ((x + (x % 2)) / 2);
    coord[1] = -x - coord[2];
    return coord;
}

public static int[] coordCube2Offset(int x, int y, int z) {
    final int[] coord = new int[2];
    coord[0] = x;
    coord[1] = (z + ((x + (x % 2)) / 2));
    return coord;
}

public static int[] roundCubeCoord(double x, double y, double z) {
    float rx = Math.round(x);
    float ry = Math.round(y);
    float rz = Math.round(z);
    final int s = (int)(rx + ry + rz);
    if (s != 0) {
        final float x_err = (float)Math.abs(rx - x);
        final float y_err = (float)Math.abs(ry - y);
        final float z_err = (float)Math.abs(rz - z);
        if ((x_err > y_err) && (x_err > z_err)) {
            rx -= s;
        } else if (y_err > z_err) {
            ry -= s;
        } else {
            rz -= s;
        }
    }
    return new int[] {
            (int)rx, (int)ry, (int)rz
    };
}

```

This one is a mess, it doesn't behave as expected at all:

Algorithm B as per Bresenham's Line Draw:

```
public Array<Pair> getLOSCellsPlanB(int y1, int x1, int y2, int x2) {
    // Works with errors, probably due to being swapped with x and y
    // !!!Designed for even-r pointy-tops
    final Array<Pair> highlights = new Array<Pair>();
    int i; // loop counter
    int ystep, xstep; // the step on y and x axis
    int error; // the error accumulated during the increment
    int errorprev; // *vision the previous value of the error variable
    int y = y1, x = x1; // the line points
    int ddy, ddx; // compulsory variables: the double values of dy and dx
    int dx = x2 - x1;
    int dy = y2 - y1;
    highlights.add(new Pair(y1, x1)); // first point
    // NB the last point can't be here, because of its previous point (which has to be verified)
    if (dy < 0) {
        ystep = -1;
        dy = -dy;
    } else {
        ystep = 1;
    }
    if (dx < 0) {
        xstep = -1;
        dx = -dx;
    } else {
        xstep = 1;
    }
    ddy = 2 * dy; // work with double values for full precision
    ddx = 2 * dx;
    if (ddx >= ddy) { // first octant (0 <= slope <= 1)
        // compulsory initialization (even for errorprev, needed when dx==dy)
        errorprev = error = dx; // start in the middle of the square
        for (i = 0; i < dx; i++) { // do not use the first point (already done)
            x += xstep;
            error += ddy;
            if (error > ddx) { // increment y if AFTER the middle ( > )
                y += ystep;
                error -= ddx;
                // three cases (octant == right->right-top for directions below):
                if ((error + errorprev) < ddx) {
                    highlights.add(new Pair(y - ystep, x));
                } else if ((error + errorprev) > ddx) {
                    highlights.add(new Pair(y, x - xstep));
                } else { // corner: bottom and left squares also
                    highlights.add(new Pair(y - ystep, x));
                    highlights.add(new Pair(y, x - xstep));
                }
            }
            highlights.add(new Pair(y, x));
            errorprev = error;
        }
    } else { // the same as above
        errorprev = error = dy;
        for (i = 0; i < dy; i++) {
            y += ystep;
            error += ddx;
            if (error > ddy) {
                x += xstep;
                error -= ddy;
                if ((error + errorprev) < ddy) {
                    highlights.add(new Pair(y, x - xstep));
                } else if ((error + errorprev) > ddy) {
                    highlights.add(new Pair(y - ystep, x));
                } else {
                    highlights.add(new Pair(y, x - xstep));
                    highlights.add(new Pair(y - ystep, x));
                }
            }
            highlights.add(new Pair(y, x));
            errorprev = error;
        }
    }
    // assert ((y == y2) && (x == x2)); // the last point (y2,x2) has to be the same with the
    // last point of the algorithm
    return highlights;
}

```

The problem with 2 is that it adds extra squares where it shouldn't because it's calculating for pointy-top hexes.

Algorithm 3 as I like it. It uses some magic numbers because of some offsets in the render system.

```
public Array<Pair> getLOSCellsPlanC(int x1, int y1, int x2, int y2) {
    final Array<Pair> highlights = new Array<Pair>();
    final int dx = x2 - x1;
    final int dy = y2 - y1;
    final FloatPair origin = this.world2window(x1, y1);
    final FloatPair destination = this.world2window(x2, y2);
    final float dpx = destination.x - origin.x;
    final float dpy = destination.y - origin.y;
    final float distance = 2 * Math.max(Math.abs(dx), Math.abs(dy));
    if (distance > 0) {
        for (int i = 0; i <= distance; i++) {
            final float currentX = ((origin.x + ((dpx * i) / distance)));
            final float currentY = ((origin.y + ((dpy * i) / distance)));
            float posx = ((currentX) / gameMap.colSize);
            float posy = (((currentY) - ((gameMap.rowSize * (posx % 2)) / 2)) / gameMap.rowSize);
            final Pair targetHex = new Pair((int)posx, (int)posy);
            highlights.add(targetHex);
        }
    }
    return highlights;
}

```

Results from A3:

Errors from A3: jumps and inconsistent move ambiguities, only one diagonal behaves the way I want.

# Answer
In algorithm 1, you're using “even-q” but you should use “odd-q” instead. Your grid is flipped upside down relative to the one on my page, so you want to shift every odd column up instead of every even column down. Change `+ (x % 2)` in `coordOffset2Cube` and `coordCube2Offset` to use `- (x % 2)` instead.

Also, on diagonals, the line drawing algorithm will not hit both sides of the line. It only picks one side. This Stackoverflow question shows the problem on square grids. You can modify hex-rounding to return both sides when x\_err, y\_err, z\_err have a tie (I haven't tried this). Or you can at each step add offsets in various directions and then round, so that if there's a tie, the offsets will end up finding multiple hexes (I've tried this and it seems to work, but I haven't written it up yet).
> 7 votes

---
Tags: algorithm, line-of-sight, hexagonal-grid
---


# Question
Title: "Non-additive" alpha blending in OpenGL ES 2.0, Android (AndEngine)
I have several monochromatic sprites and I render them with alpha = 0.25 (all of them the same value). I want to "paint" with them, so when they overlap, the alpha won't be added. I am not sure if I can express myself properly in English - here is an image of what I want to achieve (background visibility is important).

Is this achievable in OpenGL ES 2.0? I was trying to figure out the different modes of alpha blending, but without success. Also if anyone can tell me, how is this called, I can continue my search.

---

If this is not possible, I was thinking maybe I can somehow render the monochromatic sprites (alpha = 1) to a texture and only then render this texture on screen. How can this be done in AndEngine?

# Answer
You can not achieve it in OpenGL, neither in DirectX, by changing blending equation.

To do that, you should render 4 circles into a separate texture with alpha = 1, then render that texture over former background with alpha = 0.25.
> 3 votes

# Answer
Two approaches come to mind.

1. As you say, render your sprites to a texture and then render that texture on top of the background. Note that you don't need to specifically use alpha 1.0: you could also use an alpha test (implemented in your fragment shader) and no blending, which would allow you to have sprites with different transparency levels (which overwrite each other).
2. Use a depth buffer and enable depth testing. Since all your sprites are probably already drawn at the same depth, this will make sure that overlaps are hidden. (In general 3D, this is a recipe for terrible z-fighting, but since your perspective is orthogonal there are no numerical issues to worry about.)
> 2 votes

---
Tags: android, andengine, opengl-es2
---


title: HTML5 tags on my website?

text:
# Question
Title: HTML5 tags on my website?
I'm not here to ask about the merits of HTML 5, CSS 3, Javascript, etc. as game development tools. Lord knows how many people have asked about that already. No, what I'm curious about is what kind of browsers different types of gamers tend to have. I'm starting a game development studio, and I want to use some HTML 5 and CSS 3 features on my website. I know where to look for browser compatibility, but I'd like to know how old a browser I should cater to. My target audience is primarily teenagers through young adults. **Is there any risk of alienating potential players with fancy HTML 5 features, or is it safe to assume their browsers are reasonably up to date?**

# Answer
Yes. There is always a large risk in what you can support and what you can't on the web. The best web developers will develop fallbacks for older web browsers that can't parse the new tags. However, if you're looking into just using things like canvas you'll probably be fine. Examining the list of browsers people are using indicates that this element is particularly widespread. Markets will vary but for the consumer web it's a pretty safe bet these days. In the corporate world, it's a whole other ballgame and some companies are still trying to slug past IE6...
> 1 votes

# Answer
If you already have a website you should look at your analytic s and see the browser distribution of your users. The news website that I work for averages 1.8 million visits a day, of which about 65% is from browsers that wouldn't support many HTML5 APIs that I'd use in a quality game. See what your users use, then make a decision based on that. Obviously we'd losing way too many users if we ignored those with unsupported browsers in our case. However, this may or may not be the case for you. Only you (and your logs) can answer your question with any sort of confidence and reliability.
> 2 votes

# Answer
I would just go for it and use all the HTML 5 that I can. I think that if the website is designed as a gaming site, people that come to the site with a browser that doesn't run your games would have no problem coming back with a compatible browser if they have to.
> 2 votes

---
Tags: html5, web
---


# Question
Title: Calculating impulse propagation through a rigid body after a collision
I'm working on a game. I need to work out what the impulse is at different points on a body as a result of a collision.

For example, in the following diagram, if there is a collision that results in an impulse being applied to the body at A, what will the resulting impulse be at B? I know the mass, center of mass and dimensions of the body.

# Answer
> 4 votes
An impulse is an instantaneous change in velocity. You can calculate the velocity of a point before and after an impulse has been applied to the body. The velocity of a point is:

```
V = Vcm + omega cross r

```

V is the velocity of a point on a rigid body. Vcm is velocity at the center of mass. Omega would be angular velocity, and r is the vector from center of mass to a particular point on the body.

A simple way to perform your needed operation is to record the velocity before and after an impulse is applied and look at the difference.

# Answer
> 0 votes
A rigid body is generally defined as one which has a fixed shape. This means that its center of mass moves at a certain speed, and additionally the object may be rotating around its center of mass. The net impulse because of the latter term is zero (impulse is a vector field; opposite values cancel.)

Note that the impulse of a single point is zero, unless you have point masses. The impulse of an object is the volume integral of its mass multiplied by its local speed.

# Answer
> 0 votes
The simplest model retaining a physical sensibility would be to regard each collision as instantaneous, with momentum (linear and angular) conserved and energy conserved but with an **inelastic** loss simulated by a percentage calculated form the properties of the colliding objects.

For two objects such as hard ball bearings a loss of perhaps 0.5% to 1% is probably realistic.

This of course assumes that both objects in collision are rigid, and the very small collision time frames are not of interest.

---
Tags: physics, collision-resolution, rigid-body-dynamics
---


# Question
Title: In Box2D, how can I get the compression force on a specific body?
I'm using Box2D. As you can see, there are three dynamic bodies connected to each other (think of it as a table from front view). LEG1 and LEG2 are connected to the static body (it's the ground body). Another dynamic body is falling onto the table.

*I need to get the compression in the LEG1 and LEG2 separately.*

Joints have a `GetReactionForce()` function which returns a `b2Vec`, which in turn has `Length()` and `LengthSqd()` functions. This will give the total sum of the forces in any taken joint. But what I need is forces in individual bodies that are connected with joints. Once you connect several bodies with a single joint it again will show the sum of forces which is not useful. Here's the case I'm talking about:

# Answer
> 2 votes
Both the distance joint and weld joints have local anchors within them. Each anchor is relative to one of the bodies connected by the joint. You can find your compression of an individual joint by finding the distance between the two anchor points in world space.

You can use these functions to retrieve them:

```
joint->GetLocalAnchorA( );
joint->GetLocalAnchorB( );

```

To transform these points to world space you can use the function on each body called:

```
body->GetWorldPoint( v ); // Get the world coordinates of a vector given the local coordinates.

```

The weld joints (or distance joints) should be using soft constraints, otherwise the error will mostly be negligible anyway.

---
Tags: collision-detection, ios, box2d
---


# Question
Title: Is it possible to get the colliding sides using the separating axis theorem?
The title says it all, is it even possible to get the colliding sides?

I'm checking for collisions between two OABBs, which works fine using SAT. Now I want to set the moving object's velocity to the reflection vector of it's velocity, but for that I need the normal of the surface it collided with.

**Edit:**

I guess it's better if I add a bit of context. Using SAT with unaligned boxes, I check for collisions on the two axes of each object, i.e. four in total. For each axis, I determine the minimum and maximum projection of both objects on that axis and then see if they overlap. If they overlap on every axis, it's a collision.

To resolve collisions, I used a somewhat hacky approach: I'm keeping track of the overlap on each axis, then move the moving object out on the axis with the smallest penetration. Strictly speaking, that's not correct, but it works pretty well in practice so far.

What I do now is use the inverted, normalised penetration vector as my unit normal and apply the law of reflection. It works surprisingly well, but it's even wronger.

So, is there a proper way to get the colliding sides or their normals using SAT? Or should I switch to a different approach to do it properly?

# Answer
Box2D Lite has a good example of an OBB to OBB collision test. To answer your question, yes it's possible and that's the entire reason SAT is used.

A slightly new and more optimized approach to implementing the SAT is to make use of the idea of support points. See Dirk Gregorius's 2013 GDC slides for implementation details (hosted on Box2D.org as well).

I also implemented the SAT for generic 2D convex polygons and have an example open source physics engine here: http://www.randygaul.net/impulse-engine/
> 1 votes

---
Tags: collision-detection, physics, collision-resolution
---


# Question
Title: What is the best method to update shader uniforms?
What is the most accepted way for keeping a shader's matrices up to date, and why?

For example, at the moment I have a `Shader` class that stores the handles to the GLSL shader program & uniforms. Every time I move the camera I then have to pass the new view matrix to the shader, then every different world object I must pass it's model matrix to the shader.

This severely limits me as I can't do anything without having access to that shader object.

I thought of creating a singleton `ShaderManager` class that is responsible for holding all active shaders. I can then access that from anywhere and a world object wouldn't have to know about what shaders are active just that it needs to let the `ShaderManager` know the desired matrices but I'm not sure this is the best way and there's probably some issues that will arise from taking this approach.

# Answer
Use *uniform buffers* (ie *constant buffers* in D3D lingo).

So long as all your shaders agree on the layout and binding point of each such buffer then updating becomes a breeze. Models have no need to know anything about shaders at all. They need only update the model-view matrix in their constant buffer and the rendering pipeline will use it automatically.

At a minimum I would argue you should have two such buffers. The first should store your projection matrix, camera matrix, the concatenated camera-projection matrix, viewport information, frustrum details, and matrix inverses. You only need to update this buffer once per scene.

Then give each model another buffer to store its model-view matrix, normal matrix, inverses, and material properties. This is updated once for each model and can be done in a different update pass (if/when appropriate). The material information can/should be moved to a third material-specific buffer if you have the ability to share materials between multiple objects.

In a forward-shading setup it makes some sense to put all the lights in another buffer and in deferred-shading it likewise makes sense to use a per-light buffer for the light pass (in place of a model/material buffer used in the geometry pass).

Note that you need a moderately up-to-date version of GL to use uniform buffers at all (3.1 or an extension; common enough today except on some older but still-in-service laptops) and you need a fairly recent version to be able to bind uniform buffers to specific binding locations from inside the shader code (4.2; still uncommon but getting better) otherwise you have to do more work in your CPU-side code to set things up (your CPU code needs to know the right binding points anyway, so it's more of an API smell than a serious issue). OpenGL|ES didn't add uniform buffers until 3.0 which is still unsupported on most popular mobile platforms, unfortunately.

If buffers aren't an option then you will need some global place to store index locations for the active shader. You can use `glGetUniformLocation` after loading your shader to find the indices for well-known names (like `ModelViewMatrix` or the like) then store these indices. Your render can map enum values like `MODEL_VIEW` passed to a `SetUniform` wrapper function to look into the bound shader, find the index, and call `glUniform` properly. It's not a particular huge change in client code usage from buffers other than needing to set each uniform individually if you get it all wrapped up nicely.

See GLSL Inteface Blocks and Uniform Buffer Objects.
> 12 votes

# Answer
The simplest way to do this is to just standardize uniform names between your shaders and just send all the data over right before you draw. The overhead isn't insane, but you can optimize it later to not always send lesser-updated uniforms.

The way I do this in my game is that I have an abstract `Material` class. Materials act as a bridge between the game and shaders. Each `Material` has a `Shader` and various properties that can be set, including textures. When it's time to draw an object, its `Material` is bound. The `Bind` method has a `GraphicsState` parameter that contains all the current graphics state - matrices, lights, etc. The `Bind` method binds the shader and textures and sets all the uniforms, using whatever it needs from the `GraphicsState`.
> 4 votes

---
Tags: opengl, shaders, glsl
---


# Question
Title: simple adventure game mechanics stored in database
I plan to code a little adventure-like game. To be able to build multiple episodes without deploying new code I want to store any information possible in the database.

This includes stuff like

> if player examines item \[cell phone\], the contact \[xxx\] is added into his phone book and the item \[cell phone\] is replaced by \[old nokia phone with scratches\]

So something like "SCUMM lite".

Of course, \[cell phone\], \[xxx\] and \[old nokia phone with scratches\] are objects that already exist in the database. But while \[cell phone\] is of type \[inventory-item\], \[xxx\] is of type \[contact\], so there can't just be no simple link between some database-tables

I got a very basic idea about how I could achieve this but wonder if anyone has done that before and can give me a hint or even best practice

# Answer
> 3 votes
The general solution you're looking for is commonly referred to as *triggers*. There are many ways to design these, but doing so in a database-friendly way is not hard.

The basic idea is that you do something in response to an *event* after testing it against a number of *filters*.

Filters can be as simple or complex as you want/need them to be. One possibility might be to make triggers be a simple attribute/constant comparision. For instance, `HP<=100`. You can store the attribute name, comparison operator, and constant in three columns in a SQL database.

Your triggers would then be another table that maps event type to trigger *action*, which will be one of a predefined set of enumerations (like `kill`, `damage`, `teleport`, etc.). You can optionally add a data column to supply to the trigger action like the amount of damage to do.

All of this can be extended to use equations or more flexible semantics in place of just constants, of course. You may need to do all the actual processing work outside of the database in this case, if that's ok for your game.

```
CREATE TABLE triggers(UNIQUE INT id, EVENT_TYPE event, ACTION_TYPE action);
CREATE TABLE filters(UNIQUE INT id, INT trigger_id, VARCHAR(16) attribute, COMPARISON_OP op, INT data);

-- kill the player if he steps on tile (10,20)
INSERT INTO triggers(@trigger = next_id(), 'MOVED', 'KILL');
INSERT INTO filters(next_id(), @trigger, 'position', '==', encode_vec2(10, 20));

```

---
Tags: architecture, databases
---


# Question
Title: Java game: jumping glitch on multiple collisions
I need help with checking for intersections in a game I'm creating. When a character collides with a single obstacle on the screen everything works as intended, but when multiple obstacles are added to the screen the character can only jump off of the last obstacle that is being checked for collision. The character still collides properly with the other obstacles (doesn't fall through, cant walk through) but can't jump off of them.

My intersection checking code follow, `obs` is an `ArrayList` of obstacles, `ground` is the boolean that determines if the character is allowed to jump. The obstacle and character have a hitbox created by 4 rectangles.

```
public void checkIntersect(ArrayList<Obstacle> obs){

    for(Obstacle a: obs){

        if(a.getLeft().intersects(this.getRight())){
            if(getDx()>0){
                sidecollision=true;
                setDx(0);
                this.x-=1.5f;
            }
        } if (a.getRight().intersects(this.getLeft())){
                sidecollision = true;
                setDx(0);
                this.x+=1.5f;
        } if((a.getTop()).intersects(this.getBottom())){
            ground=true;
            setDy(0);
            this.y-=.10f;
        } else if(!(a.getTop()).intersects(this.getBottom())){
                ground = false;

                //return ground;
        } if(a.getBottom().intersects(this.getTop())){
            ground=false;
            setDy(0);

            this.y+=.1f;
        }

    }
}

```

And this is how collision is being checked on the game component:

```
bg.update(quote);
win.fill(clear);
bg.drawBG(win);
for(Obstacle o: obs){
    o.draw(win);
    o.update(bg);
}
if(quote.isVisible()){
    quote.movedrawProtag(win, keys);
    quote.checkIntersect(obs);
}

```

# Answer
> 1 votes
To answer your question, if you only reference the sides and collision boolean variables when the object is moving in that direction, it should help.

I.e. (pseudo-code):

```
if(moving right AND NOT collision on right){
    move right.
}

```

Or:

```
if(collision on right AND Dx > 0){
    Dx = 0.
}

```

Right now what you're doing wont allow you to move at all if there's a collision.

For example, it seems like if the player is standing on a platform, he can move left and right, but not up and down. However, if the player runs into a wall, every frame, collisions to the left or right will register true and prevent movement along the x axis as well.

# Answer
> 1 votes
You are setting `ground` to false in the wrong place. You should set `ground` to false at the beginning of the method. Here is the modified code:

```
public void checkIntersect(ArrayList obs) {

    ground = false;

    for (Obstacle a : obs) {

        if (a.getLeft().intersects(this.getRight())) {
            if (getDx() > 0) {
                sidecollision = true;
                setDx(0);
                this.x -= 1.5f;
            }
        }
        if (a.getRight().intersects(this.getLeft())) {
            sidecollision = true;
            setDx(0);
            this.x += 1.5f;
        }
        if ((a.getTop()).intersects(this.getBottom())) {
            ground = true;
            setDy(0);
            this.y -= .10f;
        } else if (!(a.getTop()).intersects(this.getBottom())) {

            // return ground;
        }
        if (a.getBottom().intersects(this.getTop())) {
            setDy(0);

            this.y += .1f;
        }

    }
}

```

---
Tags: java, game-mechanics, jumping
---


title: MMORPG server-side java architecture

text:
# Question
Title: MMORPG server-side java architecture
I am currently making a MMORPG game, which is turn-based. The client is supposed to run on Android. Now, my friend is doing the graphics, and I have been doing the game classes (player, weaponry, etc.). Now, if the fight is started, the classes can be manipulated by interfaces (actually for my partner, it is like working with pure interfaces, he does not need any access to the implementaton classes).

Now we need to introduce a game server to allow for multiple players. And a few very important questions arise:

1) Shall I copy the game model to the server completely, leaving no classes on the client or is it better to have 2 copies of the model - 1 on the server and 1 on the device and to complete periodic synchronization between those?

2) Which method of connection to choose between the client and the server (client in sight is android phone)? As for the server - I am turning towards java cause I have some experience with it. But now the questions is - is it better to use sockets for this task or I can use REST services, or it is even possible to connect it somehow to Java EE server which is cool from my point of view cause it removes a lot of programming complication? Even though the game is multiplayer, it is turn based, so it does not need to be renewed very often.

3) What about threading? Should every client have his own thread(in case of sockets)?

4) Are there any books on REAL MMORPG server game programming out there???

# Answer
Do not copy the entire game model to the server, you wouldn't like to load all the textures and detailed meshes on your server. Keep it as simple as possible, handle all the important processes like the location, health, any movement but do not load everything. - NEVER TRUST THE CLIENT.

There are many books, along with multiple wiki's. Every engine supplier like IdeaFrabrik, Epic Games, Exitgames, Unity (also supports mmo's) has very good documentation for their products. Most of that stuff is public so you got access to complete solutions and you can actually find out how stuff works.

The easiest way to find a book you need is to search Amazon for MMORPG, then go to the book category and choose the "programming" sub category. If you google it you will get unwanted results...

> Here is the list of books I found

I haven't gone deeply into server programming, but as the matter of fact, I was close to choosing the Unity+Photon Cloud engine solution for my MMORPG project. (HeroEngine won) The server side is done in this one in C# and one thing I strongly remember is the way things were explained in the tutorials.
> 7 votes

# Answer
> 1) Shall I copy the game model to the server completely, leaving no classes on the client or is it better to have 2 copies of the model - 1 on the server and 1 on the device and to complete periodic synchronization between those?

Agreed with Mikolaj do not copy everything. Send as few data as possible. You can have same classes (representing just the data model, not other assets) in client and server, but do not send them over the net. You want to serialize them on server and deserialize on client. Client should send only commands to server.

> 2) Which method of connection to choose between the client and the server (client in sight is android phone)? As for the server - I am turning towards java cause I have some experience with it. But now the questions is - is it better to use sockets for this task or I can use REST services, or it is even possible to connect it somehow to Java EE server which is cool from my point of view cause it removes a lot of programming complication? Even though the game is multiplayer, it is turn based, so it does not need to be renewed very often.

You are planning a turn-based MMORPG (no idea how that would work though). So speed is not much of a problem. You can use any kind of service, REST might be good, it's simple. Usually MMORPGs use UDP (not secure, smaller, faster) for things like movement updates where a lost packet or two doesn't matter and TCP (secure, overhead) for secure communication. Most of the games probably use some kind of encrypted, compressed custom protocol over UDP and TCP to make it fast and hard to crack.

> 3) What about threading? Should every client have his own thread(in case of sockets)?

Typically you want to have a thread pool. Each thread from the pool services one request, then gets recycled. When you don't have enough threads, you can consider blocking or allocation of more threads.

> 4) Are there any books on REAL MMORPG server game programming out there???

Mikolaj already googled that for you...
> 4 votes

---
Tags: java, mmo, server, client-server
---


title: GWT for cross device game development

text:
# Question
Title: GWT for cross device game development
How does Google Web Toolkit do in deploying to browsers as well as mobile devices, tablets, televisions, etc.? Would a game targeting specific devices be optimized significantly for the device even when using GWT?

**Edit**

More specifically, I'm asking **how would a game written in GWT perform on a limited system (phone, tablet, tv, etc.)?** Are the general optimizations it does for different browsers good enough for other devices?

# Answer
The GWT compiler tries to create browser-specific code, not device specific code. I haven't worked with it much lately, so I'm not sure what all the browsers it supports these days. Maybe it produces code especially for \[desktop\] chrome as well as \[mobile\] chrome. Since mobile is such a big focus these days, I'm sure the GWT compiler is also keeping those mobile browsers in mind.
> 3 votes

# Answer
GWT is basically a compiler from Java to JavaScript. Instead of compiling Java to JVM Byte Code and running it in JVM, you get JavaScript which you run in (typically) browser. I worked with GWT for couple of years and performance-wise in browser it is ok, but you can write your own Javascript which will be more elegant, readable and little bit faster. The obvious advantage of GWT is that you don't have to write JavaScript, you don't even have to know it. Now your question is reduced to "how does JavaScript perform". And that of course solely depends on the JavaScript interpreter performance on the device in question.

Maybe you have already looked at playn, which is using GWT. Note that graphics are usually done using OpenGL anyway and that means using native code.
> 3 votes

---
Tags: mobile, cross-platform
---


title: MonoGame WP custom vertex decleration

text:
# Question
Title: MonoGame WP custom vertex decleration
How do I go about implementing and using a custom vertex deceleration in monogame for windows phone 8. I want to be able to store a position, a colour and a normal?

# Answer
I ended up using a cross breed of the following two tutorials:

http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series1/Terrain\_lighting.php

and

http://msdn.microsoft.com/en-us/library/bb976065(v=xnagamestudio.40).aspx
> 1 votes

---
Tags: xna, c#, monogame, vertex, windows-phone-8
---


# Question
Title: A motion blur technique which can cover curve movement path?
I am looking for a motion blur technique for real-time games.

I know two techniques, velocity map and accumulation buffer. Velocity map shows very good quality, but doesn't work correctly if objects are moving along curvy path. Accumulating frame-buffer does work, but consumes too much power to get acceptable quality.

Is there any other motion blur technique which can cover this situation?

# Answer
A potential solution is to use a visualization technique involving the rendering of pathlines, streamlines and streaklines. You're interested in rendering pathlines.

Unfortunately, I can't show you a picture of how to achieve this, but I'll explain it shortly:

1. you need to keep track of the trajectory your sword or swinging object leaves behind. You should record an array of positions (you usually can have a pre-recorded data collection from your animation system): `pathPositions[N]`
2. for each segment of your path, `pathPositions[k] -> pathPositions[k+1]`, you must *build* a quad that's best facing your camera. You must *best align* this quad by alowing it to rotate against the axis defined by that segment mentioned above.
3. Now apply a texture onto each quad. The texture should be artistically tweaked to have fading borders so that its middle is solid, highlighting your sword's trajectory.

Of course, you can achieve better results using either spline interpolation or using a higher number of samples.

This way of drawing trails is known in the gaming community as ribbon trails, but the guys in the visualization realm usually refer to it as stream ribbons .
> 3 votes

---
Tags: post-processing
---


# Question
Title: How good do I have to be at Math to create a 3D game using three.js?
A question I've often had, how good at Math do I need to be to create 3 dimensional games? I get along with 2d games just fine. I understand everything I'm doing without problems after practise. However, jumping into 3d does seem a little scary and I'm worried my "bad at maths brain" will take it. I love creating games, I really don't want this to hold me back.

Is it possible to learn as I go along or do I need to have some natural math talent to be able to create 3d games? Also... if anyone can find a good place to start for a guy like me I'd really appreciate that too.

Thanks

# Answer
> Is it possible to learn as I go along or do I need to have some natural math talent to be able to create 3d games?

**Yes** it's possible, **no** you don't need any natural talent. Knowledge comes mostly from practice, in 3D just as in 2D.

> How good at Math do I need to be to create 3 dimensional games?

Just because you're adding a third dimension to your game doesn't mean you suddenly become inapt to develop it. There sure are concepts to grasp and things to know but nothing that should worry you. At first vectors, matrices and quaternions might scary you a bit, but once you've seen how they work in practice you'll soon understand they're not that complicated after all.

Game development math is easy compared to what true mathematicians manipulate. Pardon the lousy analogy, but you could figure mathematics as an engine: just because you're not an engineer or a mechanic doesn't mean *you can't drive a car*.

My advice is to do as you did with 2D games: grab a good Three.js tutorial, maybe grab a good book (e.g. Essential Mathematics for Games and Interactive Applications: A Programmer's Guide), and start working.
> 1 votes

---
Tags: 3d, javascript, three.js, mathematics
---


title: Differences between textures?

text:
# Question
Title: Differences between textures?
Me and a small team of people are creating a video game in UDK. As i have heard, the game engine can only go up to `8192x8192px` textures. In cry Engine 3, you can go up to about `16K px`. Is there a difference in the look of the two textures in the game? Does it depend on the monitor used? I am very new to this, and was just curious. Should i go to the cry Engine, or stick with UDK? Thanks.

# Answer
There is a some difference, you will need a very good artist to make it look better from the 8k/8k. It is better to use smaller textures merged using UV mapping.

If you are not a proffesional I'd stick with the smaller resolution. Epic games tries to create a product for the masses, and unless you know how to make a good lightmap it makes no sense to make shorten the game audience, not everyone bothers playing on ultra detail.

As for the use of such high resolution maps, yesterday I played the game Tomb Raider 2013. I used my development pc which has the GTX Titan installed and in one scene Lara Croft picked up a photo of her and it has looked real. Like a normal photo taken by a real life camera. And you don't need an ultra res. Photo to achieve that. You can merge more smaller photos using UV mapping.

Should I stick with Cry Engine or Unreal:

Stay with UDK, better doc's and it is more user friendly, with over more than a milion downloads you can get more help around the game dev.

If you are a team of gamers making games without good 3d modelling experience, it wont make a difference. Unreal4 engine has some features that the Cry Engine lacks. Furthermore, with Cry Engine without paying a large sum you will not have access to the engine source code, which is always easing the development.
> 1 votes

---
Tags: textures, udk, 3dsmax, cryengine
---


# Question
Title: Issues with touch buttons in XNA (Release state to be precise)
I am trying to make touch buttons in WP8 with all the states (Pressed, Released, Moved), but the `TouchLocationState.Released` is not working.

Here's my code:

Class variables:

```
bool touching = false;
int touchID;
Button tempButton;

```

*Button is a separate class with a method to switch states when touched.*

The Update method contains the following code:

```
TouchCollection touchCollection = TouchPanel.GetState();

if (!touching && touchCollection.Count > 0)
        {
            touching = true;

            foreach (TouchLocation location in touchCollection)
            {
                for (int i = 0; i < menuButtons.Count; i++)
                {
                    touchID = location.Id; // store the ID of current touch
                    Point touchLocation = new Point((int)location.Position.X, (int)location.Position.Y); // create a point
                    Button button = menuButtons[i];

                    if (GetMenuEntryHitBounds(button).Contains(touchLocation)) // a method which returns a rectangle.
                    {
                        button.SwitchState(true); // change the button state
                        tempButton = button; // store the pressed button for accessing later
                    }
                }
            }
        }
        else if (touchCollection.Count == 0) // clears the state of all buttons if no touch is detected
        {
            touching = false;

            for (int i = 0; i < menuButtons.Count; i++)
            {
                Button button = menuButtons[i];
                button.SwitchState(false);
            }
        }

```

*menuButtons is a list of buttons on the menu.*

A separate loop (within the Update method) after the touched variable is true

```
if (touching)
{
    TouchLocation location;
    TouchLocation prevLocation;

    if (touchCollection.FindById(touchID, out location))
    {
          if (location.TryGetPreviousLocation(out prevLocation))
          {
                Point point = new Point((int)location.Position.X, (int)location.Position.Y);

                if (prevLocation.State == TouchLocationState.Pressed && location.State == TouchLocationState.Released)
                {
                       if (GetMenuEntryHitBounds(tempButton).Contains(point))
                              // Execute the button action. I removed the excess
                }
           }
     }
}

```

The code for switching the button state is working fine but the code where I want to trigger the action is not.

`location.State == TouchLocationState.Released` mostly ends up being false. (Even after I release the touch, it has a value of `TouchLocationState.Moved`) And what is more irritating is that it sometimes works!

I am really confused and stuck for days now. Is this the right way? If yes then where am I going wrong? Or is there some other more effective way to do this?

*PS: I also posted this question on stack overflow then realized this question is more appropriate in gamedev. Sorry if it counts as being redundant.*

# Answer
I finally found the solution myself. It does not need the `released` state of the `TouchLocationState`

Posting it here. Hopefully it'll help others. Thanks if anyone was trying.

The class variables are renamed:

```
private Point _touchPoint;
private TouchLocation _touchLocation;
private int _touchID;
private Button _selectedButton;
private bool _touched;
private bool _launchEvent;

```

The update method now has the following code

```
        TouchCollection touchCollection = TouchPanel.GetState();

        if (!_touched && touchCollection.Count > 0)
        {
            _touched = false;
            _launchEvent = false;

            foreach (TouchLocation location in touchCollection)
            {
                for (int i = 0; i < menuButtons.Count; i++)
                {
                    Button button = menuButtons[i];
                    _touchID = location.Id;
                    _touchPoint = new Point((int)location.Position.X, (int)location.Position.Y);

                    if (GetButtonHitBounds(button).Contains(_touchPoint))
                    {
                        button.SwitchState(true);
                        _selectedButton = button;
                    }
                }
            }
        }
        else if (touchCollection.Count == 0)
        {
            _touched = false;

            for (int i = 0; i < menuButtons.Count; i++)
            {
                Button button = menuButtons[i];
                button.SwitchState(false);

                if (GetButtonHitBounds(button).Contains(_touchPoint) && _launchEvent)
                {
                    OnReleased(i, PlayerIndex.One);
                    _launchEvent = false;
                }
            }
        }

        ///
        // This if statement checks whether the touch is still inside the button area.
        // Then assigns a value of true to the _launchEvent variable.
        //
        // The 'try' block is used because if the first touch is not on button, then the
        // value of the _selectedButton is null and it will throw an exception.
        ///
        if (touchCollection.FindById(_touchID, out _touchLocation))
        {
            if (_touchLocation.State == TouchLocationState.Moved)
            {
                try
                {
                    if (GetButtonHitBounds(_selectedButton).Contains((int)_touchLocation.Position.X, (int)_touchLocation.Position.Y))
                        _launchEvent = true;
                    else
                        _launchEvent = false;
                }
                catch { }
            }
        }

```
> 0 votes

---
Tags: xna, xna-4.0, touch, windows-phone-8
---


title: OpenGL light not shining quad

text:
# Question
Title: OpenGL light not shining quad
I've constructed a scene using OpenGL/GLUT with a spot light but I'm getting troubles with light shining some of the walls

what is going on and how to solve?

# Answer
Without seeing any shader code and vertex setup, this is difficult to answer. But I suspect that you have winded the quads of the left wall clockwise instead of counterclockwise, or vise versa. Or you didn't specify the normals correctly.
> 4 votes

---
Tags: opengl, lighting
---


title: How to subdivide a quad?

text:
# Question
Title: How to subdivide a quad?
I'm working with OpenGL and I'm importing from a file coordinates for quads in the following format:

```
 0.0 1.0 0.0 //normal vector
 20.0 -5.0  20.0 10.0 10.0 //x y z u v
 20.0 -5.0 -20.0 10.0 0.0
-20.0 -5.0 -20.0 0.0 0.0
-20.0 -5.0  20.0 0.0 10.0

```

I want to tessellate the quad so I'm starting with this:

```
------------
|          |
|          |
|          |
------------

```

And I should get this:

```
-------------
|___|___|___|
|___|___|___|
|   |   |   |
-------------

```

Can you guys help me creating the subdivide function? I'm struggling with it...

# Answer
To subdivide your quad in `n*n` sub-quads, you create `n*n` sub-quads inside it. There are several ways of doing this, so there is not such thing as *the* subdivide function.

Things get messy if you want to handle the most general case, i.e. a quad that is not necessarily a perfect square. Your illustration does not really tell us what you want. There is a whole lot of different kinds of quads (and this is only for "proper" quads, lying on a plane).

So I'm giving you one solution for gentle quads that are not too weird (so, convex quads), but don't expect it to work in every case. You can create line segments that start and end at regular intervals on each of your original quad's edges, and use these as edges for your new quads. E.g. with `n=3`:

In pseudo-code:

```
function naiveSubdivide(quad, n)
    assert that n > 0
    for i from 0 to n-1
        // the P1-P2 line segment
        P1 = A + i * (D - A) / 3
        P2 = B + i * (C - B) / 3
        // its sibling to the "right", Q1-Q2
        Q1 = A + (i + 1) * (D - A) / 3
        Q2 = B + (i + 1) * (C - B) / 3
        // create n sub quads along the line segments
        for j from 0 to n-1
            A' = P1 + j * (P2 - P1) / 3
            B' = P1 + (j + 1) * (P2 - P1) / 3
            C' = Q1 + (j + 1) * (Q2 - Q1) / 3
            D' = Q1 + j * (Q2 - Q1) / 3
            create a new quad with vertices A', B', C' and D'
        end for
    end for
end function

```

For the general case, it's probably possible to write an entire book about it, but my guess is that working with triangles instead of quads would already be a good start.
> 5 votes

# Answer
Create 2 variables, hdivs and vdivs. In this example, hdivs=7, vdivs=5.

Now what you have to do is, compute all the points on the perimeter of quad ABCD. That means there are 20 points (including the corners) to be precomputed and stored.

You then need the 7 horizontal and 5 vertical lines (including the end lines). These are the lines along which the subdivided quads will be drawn. They are shown in red in the diagram above.

So then you just have to spin quads out of these 12 vectors. I will refer to the bottom line (AD) as the "1st horizontal line (1H)", and the left line (AB) as the "1st vertical line (1V)".

Your first quad will be made of (winding clockwise here):

* Left side: A *to* A+(1/6 1V)
* Top side: A+(1/6 1V) *to* A+(1/6 2V)+(1/4 2H)
* Right side: A+(1/6 2V)+(1/4 2H) *to* A+(1/4 1H)
* Bottom side: (A+1/4 1H) *to* A

Using arrays and a for loop will make this process very automatic.
> 4 votes

---
Tags: opengl, tessellation
---


# Question
Title: Shader program compiles fine on Ati, fails on other vendors
Got a real annoying problem here.

My shader program compiles fine on my Ati Radeon HD card, but on Nvidia and Intel it failes to compile.

Vertex shader:

```
#version 120
attribute vec3 in_position;
 attribute vec3 in_normal;
 attribute vec3 in_texcoord;

 uniform mat4 modelMatrix;
uniform mat4 viewMatrix;
uniform mat4 projMatrix;

varying vec2 texture_coordinate;
varying vec3 normal;

void main()
{
gl_Position = (projMatrix * viewMatrix * modelMatrix) * vec4(in_position, 1.0);
normal = in_normal;
texture_coordinate = in_texcoord.xy;
}

```

Fragment shader:

```
#version 120
varying vec2 texture_coordinate;
varying vec3 normal;

uniform sampler2D gColorMap;

 void main()
 {
   gl_FragData[0] = vec4(texture(gColorMap, texture_coordinate).xyz, 1.0f);
   gl_FragData[1] = vec4(normalize(normal), 1.0f);
}

```

Any ideas? I checked the shader for errors, but I can't find anything. Thanks.

# Answer
> 8 votes
The GLSL function `texture` and the output `gl_FragData` are only available in GLSL version 1.30 or better.

So, change line `#version 120` to `#version 130`

To find compile problems you should use glGetShaderInfoLog and glGetProgramInfoLog

---
Tags: opengl, shaders, glsl
---


# Question
Title: Are the Marek-knows tutorials any good or still relevant?
Anyone have any experience with this? This hasn't been refereed as mush as it 'looks/sound' like.

https://www.marekknows.com/

Among many other products, the site provides game engine development video, which is around *45hours long*. Starting from context creation, model loading, scene graph, animation. But it looks like a little old. Is it still useful?

# Answer
Depends on the section. I can tell you for certain that any tutorials on C++, basic game development maths, and very basic network programming won't be particularly dated if they were complete and correct when these were written. The fields just haven't changed much.

On the other hand, OpenGL has undergone a lot of changes recently. Personally speaking, I wouldn't pay for a series of tutorials that covered OpenGL \<2.0, since the fixed-function pipeline has been eliminated altogether in modern versions of both major graphics APIs. So in that sense, yes, any OpenGL tutorial written without extensive use of shaders is going to be extremely dated.
> 2 votes

# Answer
I have personally bought these tutorials, both the game engine tutorial and the alterative tutorial using the game engine to build a game (recently i have also got the networking tutorial as well)

In my personal opinion if you are wanting a set of tutorials to show you how to create a fantastically rendered terrain with prepass etc etc these tutorials are not for you.

However if you are looking for a solid introduction to game development with c++ look no further. The tutorials take you through the very basics of not only coding a game engine but understanding what you are doing and why you are doing it.

Yes they may be a bit out of date but then again everything is out of date the second its published.

I would certainly recommend then, i think the detail they go into is fantastic and definitely good value for money.
> 2 votes

# Answer
I have to say that it is worth the money. I bought it couple of years ago. Lost the disk and he still manages to answer all my questions straight away. He's a star and he knows his stuff.

I have learned plenty from his tutorials. Most of all his methods got me thinking outside the box in terms of how an engine should be programmed from the ground up.

I hope this helps

Chris
> 0 votes

---
Tags: video
---


title: Physx gravity not working as expected

text:
# Question
Title: Physx gravity not working as expected
We have been facing a strange issue with physx vehicles. The game behaves correctly in almost every situation: jumps, impacts, etc.

Gravity is applied correctly downward.

But when the vehicle is put upside down in a track, in a loop or twist, somehow it's stuck to the track as if SpiderCar was playing.

Find a video of it here. And an image below:

We are using `PxVehicleUpdate::updateDrive4W` as coming in the framework version 3.2.2 So the call is just

```
void VehicleManager::updateVehicle(const PxF32 timestep,
const PxVec3& gravity,PxVehicleDrivableSurfaceToTireFrictionPairs * mSurfaceTirePairs)
{
    PxVehicleUpdates(timestep,gravity,*mSurfaceTirePairs,mNumVehicles,mVehicles);
}

```

Gravity is a vector `(0.0,-9.8,0)` being Y the vertical coordinates. Inside it calls `updateDrive4W` for all the vehicles, which is about 400 lines

# Answer
The answer is quite easy: it's a bug, confirmed by physx team. https://devtalk.nvidia.com/default/topic/546019/vehicle-not-falling-from-track/
> 2 votes

---
Tags: physx, vehicle
---


# Question
Title: Is this a efficient implementation of a pool?
This is how I realized a pool, to prevent stutters during gameplay.

I load everything I will probably need during runtime upfront, and take each model I need from the pool during runtime. Now, my *pool* is just the left-hand side of the viewport and I know this is very dirty.

So what could I do, to have a more efficient pool?

I am asking since the game still tends to stutter once in a while when I grab some models off the pool to ingame-runtime (although it is already ingame)

# Answer
> 1 votes
Pooling is more often used to get around memory allocation issues. If you are making a bullet-hell game then creating and destroying all of those bullets is going to be a costly operation. It would be better to create a bullet pool, and when a bullet is destroyed it is just removed from the logic and draw loops, and returned to the pool. Once it is shot again it is re-initialized and added again to the logic and draw loops.

If you are trying to use this to precache objects, I would take a different approach. If you are drawing three balls there is no reason to load its texture and shape three times. If your object and renderer are separate (makes life way easier) then you can just have the renderer draw the same ball in three different locations. You can take this a step further with sprites. You can load a single sprite sheet for all of the animations of an object (or multiple objects) into a texture and just draw a section of the texture each time. Each object does not need its own texture.

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


title: How to balance hybrid classes?

text:
# Question
Title: How to balance hybrid classes?
In RPGs sometimes there will be hybrid-classed characters, ie, characters that can fill the roles of multiple characters. Sometimes they're really weak and useless because despite filling out many roles they're just not good enough to do it, and othertimes they're extremely overpowered because they can do the job of characters with a single dedicated role just as well, while still being able to do other jobs.

This often leads to either using those characters all the time, or avoiding using those characters because they're dead weight. Even just "fine tuning the numbers" doesn't seem to work because the weaker they get in regards to a dedicated role character the less useful they are overall, and then when buffing their numbers to make them more capable of holding their own makes a small reduction in power compared to a dedicated role character a minor tradeoff, because they're doing the roles of two characters in one spot.

Is there a way to actually make hybrid-role characters useful while still making players want to carry single-role characters too?

# Answer
I would try to look at hybrids from a different angle. You seem to trying to make a hybrid class fill two different roles. Instead try to make a class fill a single role with the tools of other classes.

Lets do an example with amonk. Monks are classic healer-fighters, or a priest-warrior hybrid. If you just give a warrior the ability to heal like a priest then you have an unstoppable killing machine. Well nerf the numbers too hard, and now you have a mediocre fighter who has heals that don't have enough impact to use. You have a class trying to do two jobs, and either being too good are not good enough. Its going to take a ton of iteration to find the right balance.

Instead of tweaking numbers we can tweak abilities and give the monk a purpose a couple of different ways.

1. Change range and AoE. Priests and warriors may have strong AoE abilities. Monks trade could trade the ability to hit multiple targets with the ability for strong single target spells. Also maybe limit monks to short range heals. In order to heal you have to be more like a front line medic.
2. Give advantage over base classes. Priests may be able cast strong heals and weak buffs, but monks could cast weak heals and strong buffs. Hybrid classes could excel where some roles that base classes are bad.
3. Mechanics that reward doing both. Maybe Priests use mana, but monks use spirit, and the only way to generate spirit is to attack something. That way they are limited on how much they can do a certain job.
4. Specialization. If you have talent trees you could choose to go more of a healer path or a warrior path.
> 11 votes

# Answer
Runescape has the system called the Combat triangle which works as the paper, scissor, rocks.

* Meele is strong attacking ranged armours
* Ranged defeats Mage's
* Magic defeats Meele

They have it easier, because they have a **no class** system. Which can be modified depending on what they wear, that way you are not bound to any stereotypes such as that the mage can not wear a heavy armor; a mage must look like Gandalf and due to his age he must tripp over his beard. In this type of world, players can be a hybrid of everything. That way armored mages could be effective fighters but their maneuverability could be weakened. They wouldn't be able to jump. fly, swim or do something that was possible in robes, such as creating a cyclone to life off the ground(came up with this now).

In Tibia, it has been a serious problem for Cipsoft to balance the classes. They had one class which has been a hybrid - the paladin

* Knights - Heavy armored had high defence must approach enemies in close combat has lot of HP, easy to play, has a non degradable weapon. Their magic level raises slowly .
* Paladins - (rangers) Hybrid of a mage and knight. They use bows and other ranged equipment to fight, they have only 30% less health than knights but they have 3x more mana than knights. Their distance fighting skill raises fast and their magic level raises a lot faster than the knights. Their defence goes slower than knights, just about 30% slower, while the mages have the defence level progression slower by around 95%.
* Druids - healers that were also earth/ice Mages. In combat they were mostly healers, and they also supplied special healing runes to all other. They are very expensive to play at a higher level and require a massive ammount of money to fight monsters(they need to drink mana potions that are used for casting spells).
* Mages - had most powerful spell, and were the only class that could create an item used by both Fire/Energy Mages. They also act in combat like the druids.

Cipsoft has changed some stuff in every update he delivered. When I was playing in 2008, they have downgraded the effect of healing runes that were player made, which wrecked the player based economy, the druid class has been useless, and the knight has been fairly weaker. The paladin, considered to be a balanced character, received a special weapon called the assassin star, which made the entire class 50% more deadly. In order to make up the failure, Cipsoft has weakened the weapon and made the entire class weakened. In the same time, the druids got a pump with a stronger spell. They have been keeping this up for the last few years. Leaving out the balanced classes out of the game system.

I would suggest giving every class a special ability, not an "iron fist" but a special skill, that is needed around the world, such as some kind of elemental magic, a druid in Tibia is effective against the fire creatures, where the Mage would do little harm. For roleplay make an ability, that the stronger Tank class will be good and the hybrid of both will have both of their weaknesses but this would also make them more flexible. So the tank healer will be able to sustain a very strong attack. I do not know your system so giving you my solutions to a situation I do not know.

You should look up the Path of Exile skill tree, which is the most complex level-up system in the gaming world.
> 3 votes

---
Tags: rpg, character, balance
---


title: Starting off C++ games development?

text:
# Question
Title: Starting off C++ games development?
I've just finished my 2nd year of college, and now that I have time on my hands I want to start working on a 3D game, though my stumbling point is trying to find the resources to learn C++ games development.

I'd like to code an engine from scratch, but since my lack of experience I'd guess I'm best to utilize libraries, but, I'm not certain of which ones to use.

Any advice would be appreciated for libraries to use, what books to read or any tutorials that you found useful when starting out.

Thank you!

# Answer
For C++ game dev, I learnt C++ on learncpp.com and cplusplus.com, and worked with SDL. This is a great platform-independent combination. Of course, use SDL with OpenGL for GPU graphics rendering.

SDL is like the glue code between C++, your computer and the GPU. So, you can write a lot by yourself. SDL comes with great libraries available on their website. For example: sound effects library, font library, etc...
> 1 votes

---
Tags: c++, 3d, graphics
---


# Question
Title: How do you make money from html5 games (i.e sponsorships)?
I make games with flash and I am interested in making games in html but I haven't seen any companies or websites which are willing to buy these games (i.e game sponsorships). I was hoping somebody could tell me about a company who would do this or why people don't buy html games?

# Answer
> 8 votes
As someone who is currently working on a commercial HTML5 game, I can give some possibly helpful insights.

First, HTML5 and gaming is brand new. HTML5 is really brand new, and WebGL and accelerated canvas are really really brand new. Mobile platforms for instance still lack WebGL entirely, and accelerated canvas is only available in very recent Firefox and Chrome/Webkit builds.

We're just now seeing the first conferences, books, and panels on HTML5 games. There's been the stuff at the most recent Google I/O and some panels at PAX 2011, and aside from that there's very little information.

One problem is that HTML5/JavaScript is still not quite ready for games. There's no way to lock/bind the mouse cursor, for instance, which makes a lot of games impossible to make (FPS style games) or just somewhat obnoxious to play (any fast-paced game, puzzle or otherwise, where a player is moving the cursor around a lot and has a good chance of accidentally going outside the browser content area and clicking). There's the WebGL support problem mentioned above. The HTML5 sound API is entirely unsuitable for games, although Chrome has an experimental new API that works better for games. Linear algebra libraries for JavaScript are largely slow (though they're getting better -- Chrome Canary has some amazing optimizations targeting libraries like Closure and glMatrix.js that make a huge difference) and the copy-by-reference nature of them makes it a pain to use (in a game, you often use vectors more than scalar numbers, so imagine a language where every single value/type was copy-by-reference and then you have an idea of what doing a game in JavaScript can be like).

Things will improve. There are some really big companies pushing to get the Web into a suitable state for games, which includes new specifications/APIs to correct deficiencies in the platform, browser performance and behavior improvements, and evangelization/education about the platform. Until then, though, most companies are playing it safe and staying away from the risky, new, and largely experimental gaming platform that is HTML5, which is why you won't see a lot of them willing to invest in it.

# Answer
> 2 votes
We had an interesting thread in our forum about this:

http://www.scirra.com/forum/how-do-you-make-money-with-html5\_topic46184.html?KW=make+money

The obvious ways to monetise HTML5 games are:

* Webstores (for example Chrome Webstore)
* Advertisments (traditional banner adverts for example)
* Inapp purchases (Chrome Webstore is enabling this)
* Wrap in an EXE and distribute on Steam
* Wrap with something like Phonegap and distribute as an App for Android/iPhone

Lots of ways!

# Answer
> 2 votes
# HTML5 Sponsorship/Publishing

This model is very much alive, especially for HTML5 games.

Check out marketJS, a platform to connect HTML5 game devs with publishers.

Disclosure: I work for the platform.

A good HTML5 game, when optimized for the mobile web can fetch about $500/license. Really good ones can fetch $1500+. Publishers are increasing adopting HTML5 games because they want to move away from the competitive app economy.

# Non-Sponsorship

I also wrote this blog post highlights some good ways to make a living for devs

# Answer
> 1 votes
Like Ben said, MarketJS is a great resource for finding sponsors. If you're familiar with the Flash Game market, it is more or less the equivalent of FGL.

Keeping with the Flash analogy, another model for making money from web games is through distributing to as many places as possible, and earning through ad revenue share. Mochi Media was and is the king of this for Flash.

For HTML5, there is Clay.io. Right now it's primarily mobile-web-friendly games that are picked up, so that should be a must-have when designing your HTML5 game.

*Full Disclosure: I work for Clay.io*

Other options that haven't found as much success yet are:

* Selling the games in the Chrome Web Store or similar marketplaces - however, I'm not sure this will ever work for web games. People just aren't in the mindset to buy games when it comes to games on the web.
* In-game purchases. You need a really sticky, addictive game for this to work. Zynga is a company that did, and still does this fantastically well, so if you have a chance, take a look into how they did it.

And of course, advertising is always a fairly easy option - it's just a matter of getting a high quantity of views to your game. In my experience, mobile web ads right now perform much better than traditional web in terms of CPM.

# Answer
> 0 votes
There's a few reasons that HTML5 games aren't making money via sponsorships in the same way that Flash games do.

1. HTML5/canvas/javascript is still fairly slow. For some games (puzzle, turn based strategy), this isn't a huge problem, but it's still a concern, and for a large amount of browser, the canvas tag still isn't hardware accelerated.
2. There's no reliable way to prevent theft of the code/game/etc, or ways to prevent cheating. This is a problem with Flash games, too, but it takes a bit more work to decompile Flash than Javascript (since Javascript has to be received as plain text for the browser to handle it)
3. Similar to the second point, there is no easy way to distribute an HTML5 game. With Flash, it's a single .swf file. With HTML5, there's an .html file, and at least one .js file, plus any assets used by the game. There's some potential solutions to this, but no one has come up with a method to handle this yet.

There's probably some other issues I haven't addressed, but those are the major ones that I see. Note that there are ways to make money from HTML5 games, but the route is different from a typical flash game. Chrome's app store is filled with HTML5 apps/games, many of which charge for extra levels or features. There's also hosting a game on your own server and having ads in the hopes of generating some income.

# Answer
> -1 votes
Many of the above mentioned obstacles for HTML5 game development are quickly being overcome by modern browsers. Already there is significant support for games in the major browsers. Check out my game I have been building using only HTML5 (http://asteroidsinc.com/) it plays similarly to a flash game but uses only HTML5. As for monetization it looks more time is needed. Currently there are not very many options for HTML5. I have placed some ads on my above mentioned game, however this has proven to not be profitable in the least. But I imagine with time just as with flash larger game portals will eventually emerge to take advantage of the new technology and monetization will become more straight forward.

# Answer
> -5 votes
Of course such sites won't buy HTML 5 games, they wouldn't work for a large part of their users. If you want at least a chance of convincing any of these sites to buy HTML games you better write IE6 compatible HTML 4.01.

But you'd still have a heck of a job talking them to sense, so bring a hit game if you are serious about breaking the wall, they are certainly not going to change their way of business for anything that is merely good.

---
Tags: flash, html5, monetization
---