title: undo touchdown in LibGDX with scene2D

text:
# Question
Title: undo touchdown in LibGDX with scene2D
i'm making a game in libgdx and i have a question.

I have a Button from scene2d. If there is a touchDown event on this button, i want the touchUp event only inside my button.

Now if i touchDown a button, then swipe outside my button, libgdx consider this like a touchUp.

I know that i can extend stage and work with it, the question is if there is a simple way to do this...

# Answer
the correct way to achieve this is very simple. touchDown() touchUp() and touchDragged() methods of Button class gives you button relative coordinates (0,0 is the origin of the button) so you can easly check it in touchUp() method:

method of Button class:

```
 public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
            if(x<0 || y<0 ||x>getWidth() || y>getHeight()){  // means outside the button
                System.out.println("click canceled");

            }else{
                System.out.println("clicked");

        }
    });

```
> 0 votes

# Answer
Implement one of these and override the methods you need to detect a move outside of your button. You can then disable the normal "touch up" functionality and re-enable it on the "touch up".

https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/scenes/scene2d/utils/DragListener.html
> 0 votes

# Answer
Attach clickListener to the button actor and Just use

```
Event.handled()

```

For example

```
TouchUp(Event event,.......) {

If(event.handled) //do something

Else //do something

```

You have to extend the clickListener class
> 0 votes

---
Tags: libgdx, multitouch, scene2d
---


# Question
Title: score displaying system without using bitmap
how to make a score displaying system without using bitmap in libgdx. I making a fluppy bird remake somone can explaim me in details?

# Answer
> 1 votes
One way is to use the Freetype Library -\> See here

First you have to include the library into your project as described in the article.

Then in your constructor you define the font object using your desired font.

```
FileHandle handle = Gdx.files.internal("YOUR_FONT.TTF");
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(handle);
FreeTypeFontParameter parameter = new FreeTypeFontParameter();
parameter.size = 50;
parameter.flip = true;
BitmapFont font = generator.generateFont(parameter);

```

And finally in your `render()`Method you draw the text.

```
font.draw(batch, "SCORE: " + score, x, y);

```

# Answer
> 0 votes
Assuming you do not want to use bitmap font because it doesn't center correctly on the screen, you can take a look at libgdx's scene 2d API's Label.

---
Tags: libgdx
---


# Question
Title: How to do pixel perfect movement with Unity3D?
How would you be able to make sprites move pixel by pixel in Unity3D? I've tried the following things.

* `int x = (int) transform.position.x;`
* `int x = Mathf.FloorToInt(transform.position.x);`
* `int x = Mathf.RoundToInt(transform.position.x);`

I don't know what else to try

Because I'm making an SNES looking game, and when things move, there is very bad pixel crawl in the sprites.

# Answer
> 2 votes
I've done several pixel perfect games in Unity (the latest one.

Your first thought is the one I use, I cast every position as an integer. Something like :

```
Vector2 pos = transform.position;
Vector2 clamped_position = new Vector2((int)pos.x,(int)pos.y);
transform.position = clamped_position;

```

However if you're interested in movement it's a little bit complex but not too hard. The trick here is to update a variable with movement value (in pixel per second). Once the variable describes a movement greater than one pixel, you know that you have to move your GameObject.

Here is what you can find in the LateUpdate method of my GameObject:

```
    private void LateUpdate()
    {
        // Clamp the current movement
        Vector2 clamped_movement = new Vector2((int)_movement.x, (int)_movement.y);
        // Check if a movement is needed (more than 1px move)
        if (clamped_movement.magnitude >= 1.0f)
        {
            // Update velocity, removing the actual movement
            _movement= _movement- clamped_movement;
            if (clamped_movement != Vector2.zero)
            {
                // Move to the new position
                transform.position = ClampVector(transform.position) + clamped_movement;
            }
        }
    }

```

And here is how I update the `_movement` variable when player wants to go left :

```
 public void GoLeft()
{
    // speed is defined in pixel per second.
    _movement.x -= speed * Time.deltaTime;
}

```

With that in mind you just have to take care of the orthographic size of your camera. Using this simple trick you can be sure that your main camera is correctly set up, and everything should work out.

I hope it helps.

---
Tags: unity, screen, pixel-art
---


# Question
Title: Unity Animated Player Character Rotation Glitch
I was wondering if anyone experienced this issue in Unity with Mecanim-animated characters ...

I have an animated player character with a third-person camera control (Game Camera from the asset store, even though I think it isn't really related) and if the character is standing at the default y-rotation angle I can orbit around her with the camera and she will always face the same direction, as it should be.

But if the character stands with an arbitrary other transform y-rotation (for example 90.0001 or 180, etc.) and I orbit around the character, the character's Y rotation is ever so often randomly changed.

I don't know what changes the Y rotation. Game Camera doesn't touch it as long as I don't move the character so I suppose it is related to Mecanim, even though i'm not sure about that either.

I was hoping somebody has more familiarity with this issue and know what causes this. This glitch is definitely a problem in gameplay.

# Answer
> 2 votes
Some values of Mechanim animations are absolute. Then you rotate or move your character, actual values changes, but animations still use old hard-coded values in wolrd-space coordinates. You should try to put your character into empty parent object. Animate character itself, but rotate and move the parent.

---
Tags: unity, camera, rotation, mecanim, bug
---


# Question
Title: Windows Phone 8.1 Monogame Content.Load<Effect> exception
need some help, just trying to load compiled .fx (.xnb) file by monogame (version 3.4.0.456) in Windows **Phone** 8.1 enviroment by this code

```
MainEffect = Game.Content.Load<Effect>("chessboard");

```

there is a some delay, about 3-4 seconds, and then i get

> SharpDX.SharpDXException "Additional information: HRESULT: \[0x80070057\], Module: \[General\], ApiCode: \[E\_INVALIDARG/Invalid Arguments\], Message: The parameter is incorrect."

Tried different files, but seems no matter how complex the are, behaviour is the same. Even this simple effect gives an error:

```
float4x4 World;

struct VertexShaderInput
{
    float4 Position : SV_POSITION0;
    float4 Color : COLOR0;
};

struct VertexShaderOutput
{
    float4 Position : SV_POSITION0;
    float4 Color : COLOR0;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;
    output.Position = mul(input.Position, World);
    output.Color = input.Color;
    return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    return input.Color;
}

technique Specular
{
    pass Pass1
    {
        VertexShader = compile  vs_4_0 VertexShaderFunction();
        PixelShader = compile ps_4_0 PixelShaderFunction();
    }
}

```

But for Windows 7/8/10 its works well. Any ideas ?

# Answer
Well changed versions of vs/ps to 4\_0\_level\_9\_3 and it worked :)

```
    VertexShader = compile vs_4_0_level_9_3 VertexShaderFunction();
    PixelShader = compile ps_4_0_level_9_3 PixelShaderFunction();

```
> 2 votes

---
Tags: xna, directx, monogame, effects
---


title: GLES multiple output buffers

text:
# Question
Title: GLES multiple output buffers
I'd like to write multiple values (not just the color and depth value) in one pass to avoid redundancy in vertex shader. Therefore, i attach multiple (let's say two) color buffers (e.g. textures) to a frame buffer object. As i read, GLES 3.0 supports GLSL 3.0 which supports layout( location = # ) qualifiers. However, the shaders do not compile with the error message "Typename expected, found 'layout'\n"

Simple fragment shader example:

```
uniform sampler2D uTexture;
varying vec3 vNormal;
layout( location = 0 ) out vec4 color;
layout( location = 1 ) out vec3 normal;
void main() {
    color = texture2D( uTexture, vTexture );
    normal = normalize( vNormal );
}

```

I would expect color going to GL\_COLOR\_ATTACHMENT0 and normal going to GL\_COLOR\_ATTACHMENT1. So, is there a way to avoid multiple passes in GLES 3.0?

# Answer
OK, the answer is easy: the line

```
#version 300 es

```

has to be put on top, otherwise it will be interpreted as GLES 2.0 code. Furthermore, `varying` is obsolete and has to be exchanged by `in` and `texture2D` is covered by `texture`.
> 0 votes

---
Tags: android, frame-buffer, opengl-es3
---


# Question
Title: How can I export a model from Unity to three.js?
I want to buy some assets from the Unity asset store and use them in my three.js project, but I am not sure what the best way to go about this is. Some cursory googling got me this, but Collada Exporter does not support the latest version of Unity afaik. I have also tried some other exporters such as this one, but the objects I get out of it are buggy (mirrored pieces not rendering etc.). Ideally my workflow would be Unity -\> Blender -\> three.js (as json). I know there is a three.js blender exporter, so I suppose the missing part is going from Unity to Blender. I would also like animations to be exported.

Does anyone have experience with a workflow successfully exporting assets from Unity to three.js?

# Answer
> 3 votes
I wrote an Unity3D to Three.js exporter that does exactly what you ask for.

---
Tags: unity, javascript, blender, three.js
---


# Question
Title: How does one test the effectiveness of a game engine?
A few friends and I are working on a home-brewed engine for a selection of games we wish to produce in the future. We're making it to satisfy a few key requirements that we haven't found were properly handled in professional game engines. But we were wondering, how can we test how effective our engine is at solving the problems we set out to solve?

For example, our games require a very specific internal OOP architecture, and the engine facilitates that, making it easy for us to do what we want. How are we supposed to make sure the engine *actually* helps us?

The reason I ask is because I've written unit tests before, but they've usually been to test whether or not something is *correct*. Does the engine properly determine collisions between convex polygons? Does the event propagator properly respond to user input? Is the implementation of Bresenham's line algorithm for rendering line primitives correct? Things like this.

When it comes to testing effectiveness of the application as a whole, however, there is no notion of *right* or *wrong*. It's fuzzy, it could be pretty effective, very effective, or not effective at all. Is the only solution just to make a game using the engine, and determine the engine's effectiveness from there? I want to say no, because the point of testing is to catch errors early on right, so if we make a game to test effectiveness, we have to build the entire engine beforehand.

How would tests like these even be included? If we integrated "test games" using the same program we use to integrate unit tests, they'd get run every time the engine builds. But we don't want our stupid test games to start running every time we build.

So is there another solution?

# Answer
> 3 votes
Engineering is all about having to prototype machines in order to see whether a concept works. There is some minimum amount of labour required to test any such theory in working form - usually quite a lot - and until that labour's been put in and the system is in working form, it is just a theory.

An engine is largely complex (especially in the temporal sense) and highly specific in its operation, and since it exists *to provide a runtime environment*, it also dictates all the rules of that environment. For this reason, there's no better way to test the engine than to see if it adequately supports the game specifications intended to run within its environment. The engine *is* the scaffold; the tests *are* the games or simulations that run therein. And more cases = better coverage.

In the very first place then, to know whether your engine meets your standards, you must know what those standards are. Until then, the question "is it good enough" cannot be answered definitively. Recall the idea of why we cannot use traditional testing to test gameplay - again, in the gameplay arena our logic is rather fuzzy so we do not have (thankfully) a pre-specified set of requirements that makes a game "enjoyable" vs. "not enjoyable". The less fuzzy, the more testable.

Re traditional testing, this tends to be used for well-encapsulated, low-level, easily judgeable features like, "did this texture load correctly" or "when rendering, does this font display at the specified height" as well as things like "can we maintain N frames per second over one hour". (Visual aspects, like font display, may require tests to do things like take screenshots of the framebuffer and take measurements from there, but that's a whole other can of worms.)

And you're right, the typical way to test runtime modules would be to have a separate script that runs these perhaps triggered only on certain types of builds or only when you explicitly execute it.

Also see these rather nice anecdotes from those who've implemented automated testing in games.

---
Tags: architecture, testing
---


# Question
Title: How do I create a rocket projectile that is "dropped", then accelerates toward the enemy?
I'm making an *Asteroids*-like game. I've successfully implemented linear bullets.

Now I want to add some rocket-styled bullets, with a certain flight path: The rockets should be "dropped" back first, then accelerate towards the enemy.

I'm having difficulty making this work when the shooter is rotated. To visualize what I mean:

Bullets have a `lifeTime` which increases every frame.

# Answer
> 4 votes
A simple way to achieve this effect would be to launch the missile with an initial velocity of (ship's backwards vector + ship's rightwards vector), then apply a constant acceleration of (ship's forward vector) each frame, until it reaches some maximum forward velocity.

Of course, that describes a "dumb" rocket that always follows that (rightward) trajectory. If you're looking for a "homing" rocket, you can achieve that by launching with only (ship's backward vector) as the initial velocity, and applying the acceleration in the direction of the target (instead of just forwards) every frame instead.

If the engine you're using doesn't give you your ship object's directional vectors for free (Unity's transform.forward is a godsend for this sort of task), then you'll have to calculate them yourself. Given the ship's rotation as a number of degrees from some starting angle, and the ship's forward and rightward vectors when at the starting angle, you can calculate the ship's forward and rightward vectors at the specified rotation like this:

```
rotated_vector_x = original_vector_x * cos(angle) - original_vector_y * sin(angle);
rotated_vector_y = original_vector_x * sin(angle) + original_vector_y * cos(angle);

```

For further reading, I highly recommend the Wolfire Games blog posts on "Linear algebra for game developers", which begin here. Part 3 contains a description of calculating and applying basis vectors, which is pretty much exactly the problem you're trying to solve here.

---
Tags: rotation, vector, projectile-physics
---


# Question
Title: Unity -- custom shader behaves differently on WebGL deployment (correct) and editor view (incorrect)
I started working on shaders and lighting on Unity3D 5.2.1f1. I set up a scene where the sun object rotates the directional light (the only light in the scene) based on its position to simulate a light object orbiting around the model object while rotating the directional light accordingly.

Here, I have implemented Phong reflection model by writing the custom shader below.

```
Shader ".Tutorial/Phong"
{
    Properties
    {
        _Diffuse("Diffuse Color", Color) = (1, 1, 1, 1)
        _Specular("Specular Color", Color) = (1,1,1,1)
        _Ka("Ambient Light", Vector) = (0.3, 0.3, 0.3)
        _Shininess("Shininess", Float) = 1000
    }

    SubShader
    {
        Pass
        {
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag

        struct appdata
        {
            float4 vertex : POSITION;
            float3 normal : NORMAL;
            float2 texcoord : TEXCOORD0;
        };

        struct v2f
        {
            float4 pos : SV_POSITION;
            float3 normal : NORMAL;
            float2 texcoord: TEXCOORD0;
        };

        fixed4 _Diffuse;
        fixed4 _Specular;
        float4 _LightColor0;
        float4 _Ka;
        float _Shininess;

        v2f vert(appdata IN)
        {
            v2f OUT;
            OUT.pos = mul(UNITY_MATRIX_MVP, IN.vertex);
            OUT.texcoord = IN.texcoord;
            OUT.normal = mul(float4(IN.normal, 0.0), _Object2World).xyz;
            return OUT;
        }

        fixed4 frag(v2f IN) : COLOR
        {
            float3 N = normalize(IN.normal);
            float3 L = normalize(_WorldSpaceLightPos0);
            float3 V = normalize(_WorldSpaceCameraPos - IN.pos.xyz);
            float3 R = 2 * max(0.0, dot(N, L)) * N - L;

            float4 Kd = _Diffuse * max(0.0, dot(N, L));
            float4 Ks = _Specular * pow( max(0.0, dot(R, V)) , _Shininess);

            float4 Illumination = Kd + Ks + _Ka;

            return _LightColor0*Illumination;
        }

        ENDCG
        }
    }
}

```

---

**Here's the issue:** This shader works correct on the WebGL deployment but looks like this in the editor scene and play views.

You can see the specular component is far off in the scene/play view in the Editor, but is right on the WebGL deployment.

If you want to give yourselves a try here are the links to

---

What causes this? How can I begin to debug such an issue? Anyone experienced this before?

# Answer
The problem is that `IN.pos` is not in world space. I think you need to do something like

```
struct v2f
{
    float4 pos : SV_POSITION;
    float3 normal : NORMAL;
    float2 texcoord: TEXCOORD0;
    float4 posWorldSpace : TEXCOORD1;
};

v2f vert(appdata IN)
{
    v2f OUT;
    OUT.pos = mul(UNITY_MATRIX_MVP, IN.vertex);
    OUT.posWorldSpace = mul(_Object2World, IN.vertex);
    OUT.texcoord = IN.texcoord;
    OUT.normal = mul(float4(IN.normal, 0.0), _Object2World).xyz;
    return OUT;
}

fixed4 frag(v2f IN) : COLOR
{
    float3 N = normalize(IN.normal);
    float3 L = normalize(_WorldSpaceLightPos0.xyz);
    float3 V = normalize(_WorldSpaceCameraPos.xyz-IN.posWorldSpace.xyz);
    float3 R = 2 * max(0.0, dot(N, L)) * N - L;
    float4 Kd = _Diffuse * max(0.0, dot(N, L));
    float4 Ks = _Specular * pow( max(0.0, dot(R, V)) , _Shininess);

    float4 Illumination = Kd + Ks + _Ka;

    return _LightColor0*Illumination;
}

```
> 1 votes

---
Tags: unity, shaders, lighting, webgl
---


# Question
Title: Rendering Tic Tac Toe Cross and Circle in libGDX
I am new in LibGDX. For learning purpose, I am creating TicTacToe and I spent two days to figure out what went wrong with rendering the cross and circle. Whenever I click on the cell, the cross and circle blinking at the same time. It is supposed to print alternately. What I did wrong in the code? Here is the code

```
package com.mytictactoe;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector3;

public class MyTicTacToe extends ApplicationAdapter {

    private static final int MAX_FINGERS = 2;

    SpriteBatch batch;
    Texture tile, circle, cross;
    Vector3 mouse;
    OrthographicCamera camera;

    enum Tile { EMPTY,  CROSS,  CIRCLE  }

    final int WIDTH = 480;
    final int HEIGHT = 600;

    int tileSize;
    int boardOffset;
    Tile[][] tiles;
    Tile currentPlayer = Tile.CROSS;

    @Override
    public void create() {
        tiles = new Tile[3][3];
        tileSize = WIDTH / tiles[0].length;
        boardOffset = (HEIGHT - tileSize * tiles.length) / 2;

        camera = new OrthographicCamera();
        camera.setToOrtho(false, WIDTH, HEIGHT);

        batch = new SpriteBatch();
        tile = new Texture("tile.png");
        circle = new Texture("circle.png");
        cross = new Texture("cross.png");
    }

    public void update(float dt) {

    }

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

        //processing user input
        for (int i = 0; i < MAX_FINGERS; i++) {
            if (Gdx.input.isTouched(i)) { //using polling
                mouse = new Vector3();

                mouse.x = Gdx.input.getX(i);
                mouse.y = Gdx.input.getY(i);

                camera.unproject(mouse);

                if (mouse.y > boardOffset
                        && mouse.y < boardOffset + tileSize * tiles.length) {
                    int row = (int)((mouse.y - boardOffset) / tileSize);
                    int col = (int)(mouse.x / tileSize);

                    tiles[row][col] = currentPlayer;
                    currentPlayer = (currentPlayer == Tile.CROSS)
                            ? Tile.CIRCLE : Tile.CROSS;
                }
            }
        }

        batch.begin();
        for (int row = 0; row < tiles.length; row++) {
            for (int col = 0; col < tiles[0].length; col++) {
                if (tiles[row][col] == Tile.CIRCLE) {
                    batch.draw(circle,col * tileSize,
                               row * tileSize + boardOffset,
                               tileSize,    tileSize);
                    System.out.println("Circle is printed");
                } else if (tiles[row][col] == Tile.CROSS) {
                    batch.draw(cross,col * tileSize,
                               row * tileSize + boardOffset,
                               tileSize,tileSize);
                    System.out.println("Cross is printed");
                } else {
                    batch.draw(tile, col * tileSize,
                               row * tileSize + boardOffset,
                               tileSize, tileSize);
                    System.out.println("Tile is printed");
                }
            }
        }
        System.out.println("Outside the FOR LOOP");

        batch.end();
    }

    @Override
    public void dispose() {
        batch.dispose();
        tile.dispose();
        cross.dispose();
        circle.dispose();
    }
}

```

# Answer
`camera.setToOrtho(false, WIDTH, HEIGHT);` is redundant, change this:

```
camera = new OrthographicCamera();
camera.setToOrtho(false, WIDTH, HEIGHT);

```

for this:

```
camera = new OrthographicCamera(WIDTH, HEIGHT);

```

Also, add `batch.setProjectionMatrix(camera.combined)` before `batch.begin();`
> 0 votes

# Answer
I believe your problem is this `for`:

```
for (int i = 0; i < MAX_FINGERS; i++) {
   ...
}

```

I'm not too sure why do you have this `MAX_FINGERS` variable, but since its value is `2`, you are changing twice the `currentPlayer` variable every loop inside this part.

A solution could be:

```
// for (int i = 0; i < MAX_FINGERS; i++) { <-- remove for
if (Gdx.input.justTouched()) {           //  <-- remove index & use justTouched()
    mouse = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
    camera.unproject(mouse);

    if (mouse.y > boardOffset
            && mouse.y < boardOffset + tileSize * tiles.length) {
        int row = (int)((mouse.y - boardOffset) / tileSize);
        int col = (int)(mouse.x / tileSize);

        tiles[row][col] = currentPlayer;
        currentPlayer = (currentPlayer == Tile.CROSS) ? Tile.CIRCLE : Tile.CROSS;
    }
}

```

And you could reduce your draw section to:

```
for (int row = 0; row < tiles.length; row++) {
    for (int col = 0; col < tiles[0].length; col++) {
        Tile t = tiles[row, col];
        Texture tex = t == Tile.EMPTY ? tile : t == Tile.CROSS ? cross : circle;

        batch.draw(tex, col * tileSize, row * tileSize + boardOffset, tileSize, tileSize);
    }
}

```

**EDIT**

Change `isTouched()` for `justTouched()`
> 0 votes

# Answer
I allready answered this question on javagaming, as you asked it there to. You querry the touched tile once per render loop. But a touch most times takes longer then a render loop.
So as soon as you touch a Tile, it starts switching between circle and cross every render loop and when you release it stops switching. If it is Circle or Cross is pretty random as it switches 30 times/second (on 30FPS).
The solution would be to set the Tile only, if it is empty.
This would also make it impossible for the opponent to overwrite your move.
> 0 votes

# Answer
I managed to solve the clicking problem after googling here and there.

What I did was, I extended InputAdapter class for my Input Listener class

Here is the sample codes

```
package com.mytictactoe;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector3;

public class MyTicTacToe extends ApplicationAdapter{

   SpriteBatch batch;
   Vector3 mouse;
   OrthographicCamera camera;

   final int WIDTH = 480;
   final int HEIGHT= 600;

   int tileSize;
   int boardOffset;
   int boardHeight;
   Tile[][] tiles;

   boolean turn = true;

   @Override
   public void create () {
       tiles = new Tile[3][3];
       tileSize = WIDTH/tiles[0].length;
       boardOffset =  (HEIGHT-tileSize*tiles.length)/2;
       camera = new OrthographicCamera();
       camera.setToOrtho(false, WIDTH, HEIGHT);
       batch = new SpriteBatch();

       for(int row=0;row<tiles.length;row++){
           for(int col=0;col<tiles[0].length;col++){
            tiles[row][col] = new Tile(col*tileSize+tileSize/2,
             row*tileSize+boardOffset+tileSize/2,
             tileSize,
             tileSize);
       }
    }
    Gdx.input.setInputProcessor(new MyInputListener(this));
}

public void update(float dt){

}

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

    batch.begin();

    for(int row = 0; row < tiles.length; row++) {
        for(int col = 0; col < tiles[0].length; col++) {
            tiles[row][col].render(batch);
        }
    }
    batch.end();
}

   @Override
   public void dispose() {
       batch.dispose();
   }
}

```

Tile Class

```
package com.mytictactoe;
import java.util.HashMap;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Rectangle;

public class Tile {

    static final int EMPTY      =-1;
    static final int CIRCLE     = 0;
    static final int CROSS      = 1;

    int player = EMPTY;

    float x;
    float y;
    float width;
    float height;

    TextureRegion tile;
    TextureRegion circle;
    TextureRegion cross;

    HashMap<String, TextureAtlas> atlases;
    Rectangle rectangle = new Rectangle();

    public Tile(float x, float y, float width, float height){
       this.x=x;
       this.y=y;
       this.width=width-4;//4 is tile spacing
       this.height=height-4;

       atlases= new HashMap<String, TextureAtlas>();
       loadAtlas("pack.pack", "pack");
       tile = getAtlas("pack").findRegion("tile");
       circle = getAtlas("pack").findRegion("circle");
       cross = getAtlas("pack").findRegion("cross");
   }

   public void loadAtlas(String path, String key){
       atlases.put(key, new TextureAtlas(Gdx.files.internal(path)));
   }

   public TextureAtlas getAtlas(String key){
       return atlases.get(key);
   }

   public void render(SpriteBatch batch){

       batch.draw(tile,x-width/2,y-height/2, width, height);
       if(player==CIRCLE){
           batch.draw(circle,x-width/2,y-height/2, width, height);
       }else if(player==CROSS){
           batch.draw(cross,x-width/2,y-height/2, width, height);
       }

   }

   public boolean touched(float x, float y){
       rectangle.set(this.x-width/2, this.y-height/2,width,height);
       return rectangle.contains(x, y);

   }
}

```

Input Listener class

```
package com.mytictactoe;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.math.Vector3;

public class MyInputListener extends InputAdapter{
   MyTicTacToe myTicTacToe;
   Vector3 coordinate = new Vector3();

   public MyInputListener(MyTicTacToe myTicTacToe){
       this.myTicTacToe=myTicTacToe;
   }

   @Override
   public boolean touchDown(int screenX, int screenY, int pointer, int button){
       coordinate.set(screenX, screenY, 0);
       myTicTacToe.camera.unproject(coordinate);

       for(int row=0;row<myTicTacToe.tiles.length;row++){
           for(int col=0;col<myTicTacToe.tiles[0].length;col++){
               Tile tile = myTicTacToe.tiles[row][col];

               if(tile.touched(coordinate.x, coordinate.y)){
                   tile.player = myTicTacToe.turn?Tile.CIRCLE:Tile.CROSS;
                   myTicTacToe.turn = !myTicTacToe.turn;
               }
           }
       }
       return super.touchDown(screenX, screenY, pointer, button);
   }
}

```

hopes help for someone out there :)
> 0 votes

---
Tags: libgdx
---


title: Cocos2d v3.4 Templates

text:
# Question
Title: Cocos2d v3.4 Templates
How to create cocos2d v3.4 without using Cocos2D-SpriteBuilder?

I installed Cocos2D-SpriteBuilder as they recommended in cocos2d blog:

http://cocos2d.spritebuilder.com/get-started

But I need to create cocos2d v3.4 project from Xcode without creating it first in Cocos2D-SpriteBuilder.

Any help?

# Answer
Regarding the info found here, currently there is no official way to achieve this but they are working on it. Meanwhile you can download the "standalone template" found in the same link.
> 2 votes

# Answer
As I recall, as from Cocos2Dv3 you can only create cocos2d projects via SpriteBuilder. If you insist to work without SB, What I'd recommend is to create a new SpriteBuilder project and delete all the SB files from there. Another option would be to copy all the source files from the sb project to the new Xcode project.

Hope it helped.
> 1 votes

# Answer
Oh yeah!

Finally solved!

Get it if someone need: cocos2d v3.4.9 template
> -3 votes

---
Tags: cocos2d-iphone, cocos2d
---


# Question
Title: Where/how should A Star tie breaking occur?
I've recently written a path finding script that utilizes a basic implementation of the A Star algorithm. It works fine but is not very fast. This is due, at least in part, to the fact that it isn't optimized at all. Through a bit of searching through this site and others I've realized that at least one thing I need is a tie breaking procedure that updates the heuristic values of nodes in the open list. Currently, whenever the pathfinder function is initiated. The pattern the finder takes pretty much expands outward in all directions from the point of origin until the target node is found. I've seen several videos that show A Star almost immediately traveling towards the target node thus eliminating many checks and ultimately speeding up the process. I believe this is due to a tie breaking procedure.

My question is... At what point in the process should I be applying the tie breaking procedure and is there a better modifier to add to the heuristic aside from the below code?:

```
Node.heuristic += (Mathf.Abs((Node.x * endNodeVector.z) - (endNodeVector.x * Node.z)) * 0.001F);

```

This seems to be the most common that I have found. However, for some reason, this doesn't seem to effect the algorithm at all. It still searches in all directions from the origin position. What am I missing to make my A Star favor open list nodes that are closer to the target?

# Answer
The tie-breaker is the heuristic.

The next node to process is the one with the lowest `f = g+h` where `g` is the known cost from start to the node and `h` is the estimated cost from the node to the destination.

To guarantee you get the shortest path this `h` must underestimate the remaining cost. A common one is the path as the crow flies.
> 1 votes

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


# Question
Title: How can I quickly check if my sprite tiles well?
I am trying to create tilemap sprites that tile nicely, but checking how well they tile is really cumbersome.

Ideally, I'd like to have an image editor that shows a layout like this, so I could see if it tiles well without a manual check:

```
     [img]
[img][img][img]
     [img]

```

What programs can do this, or how can I otherwise make this easier?

# Answer
> 67 votes
Here's a quick hack that works with any image editor.

If your tile image is called `tile.png`, create an `index.html` like this:

```
<body style="background:url(tile.png) repeat 0 0"></body>

```

<sup>(Thanks @Deryllium for the simpler alternative!)</sup>

Open that in a web browser.

Whenever you need to check how well the image tiles, save it, and refresh the web browser.

GIMP's *export* shortcut is `Ctrl``e` and Chromium's *refresh* shortcut is `Ctrl``r`. The `e` and `r` are adjacent on a QWERTY, so this is pretty fast to do.

# Answer
> 18 votes
Using photoshop or GIMP, you can use the offset command. If you are working for say a 100x100px image, you can offset it 50px in each direction, and the seam where the image tiles together will be displayed in the middle of the image.

This page has screenshots demonstrating how this works: http://blogs.adobe.com/jkost/2015/01/how-to-create-a-seamless-pattern-tile-in-photoshop.html

# Answer
> 17 votes
Krita has a feature that allows you to edit tiling textures and see the changes update live. By pressing the W key, it enables wrap around mode, which makes this possible. A youtube video of this feature in action is available here. (feature is enabled at 0:12)

# Answer
> 6 votes
Make your tile a tiled wallpaper on you desktop. Super easy and no coding or extraneous software.

# Answer
> 5 votes
If you want to test multiple images, it may help to have an mini webapp based on Anko's answer. This will let you drag images onto the page to let you test them in quick succession:

```
window.addEventListener('load', function() {
  document.body.addEventListener('dragover', function(event) {
    // Accept the drag
    event.preventDefault();
  });

  document.body.addEventListener('drop', function(event) {
    // Prevent page redirect
    event.stopPropagation();
    event.preventDefault();

    var reader = new FileReader();

    reader.onload = function(e) {
      // Set background image
      document.body.style.background = 'url(' + e.target.result + ') repeat 0 0';
      document.body.textContent = ''; // Remove instructions
    };

    // Begin reading file
    reader.readAsDataURL(event.dataTransfer.files[0]);
  });
});
```

```
html, body {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

html {
  border: 2px dashed black;
}

body {
  padding: 10px;
}
```

```
<p>Drag an image here</p>
```

# Answer
> 0 votes
In GIMP: Filters -\> Map -\> Tile. If you change the unit to "%" and then enter 300% x 300% for the dimensions, you'll get a 3x3 tiling of your image, which lets you see all four edges easily. After doing it once you can use Ctrl-F (repeat last filter) to re-do the tiling after making modifications, as long as you don't use any other filters of course.

---
Tags: sprites, tilemap, tools, workflow
---


# Question
Title: Calculate angles between two other angles
I am trying to implement a FOV for my light casting algorithm. In the diagram below each white line represents a ray cast from a `std::vector<float>` of normalized radians. How can I only include angles which lie between the two green lines? (The FOV min and max).

# Answer
I found this which works pretty well.

```
bool angleBetween(float _angle, float _min, float _max)
{
    float angle = std::fmod(360 + (rad2deg(_angle)), 360);
    float min = std::fmod(3600000 + rad2deg(_min), 360);
    float max = std::fmod(3600000 + rad2deg(_max), 360);

    if(min < max)
        return (min <= angle && angle <= max);

    return (min <= angle || angle <= max);
}

```
> 1 votes

---
Tags: c++, mathematics, lighting
---


title: 2D Collision Box Clipping

text:
# Question
Title: 2D Collision Box Clipping
There is this strange issue with the collision in a game I am making. When the player is slightly lower than a block it is colliding with from the side, the player ends up clipping to the top of the block rather than sliding along the side of it down. Do you have an idea how to fix it?

If that description didn't help you at all you can reproduce it here (goes to the website with the game on it). (Use WASD/Space/Arrow Keys to move) To reproduce, stand on the single block and hold the right move button. You will fall off the edge, hit the side of the block, and get clipped to the top of it. You are meant to fall onto the block below instead. (The words and colors are debug info)

The code below is what handles the collision detection. If you need the rest of the code, you can view the source of the page linked above.

```
this.doCollision = function() {
var tx = Math.floor(this.x),
    ty = Math.floor(this.y),
    nx = this.x % 1,
    ny = this.y % 1,
    cell = this.cell = levelStorage.currentLevel.getTileAtPosition(tx, ty),
    cellRight = this.cellRight = levelStorage.currentLevel.getTileAtPosition(tx + 1, ty),
    cellDown = this.cellDown = levelStorage.currentLevel.getTileAtPosition(tx, ty + 1),
    cellDiag = this.cellDiag = levelStorage.currentLevel.getTileAtPosition(tx + 1, ty + 1);

if(this.vy > 0) { // Ground collision
// The !cell checks return if the cell exists or not (null)
  if((cellDown && !cell) || (!cellRight && cellDiag && nx)) {
    this.y = ty;
    this.vy = 0;
    this.falling = false;
    this.jumping = false;
    ny = 0
  }
}else
if(this.vy < 0) { // Ceiling collision
  if((!cellDown && cell) || (cellRight && !cellDiag && nx)) {
    this.y = ty + 1;
    this.vy = 0;
    cell = this.cell = cellDown;
    cellRight = this.cellRight = cellDiag;
    ny = 0;
  }
}
if(this.vx > 0) { // Right collision
  if((cellRight && !cell) || (!cellDown && cellDiag && ny)) {
    this.x = tx;
    this.vx = 0;
    nx = 0;
  }
}else
if(this.vx < 0) { // Left collision
  if((!cellRight && cell) || (cellDown && !cellDiag && ny)) {
    this.x = tx + 1;
    this.vx = 0;
    cell = this.cell = cellRight;
    cellDown = this.cellDown = cellDiag;
    nx = 0;
  }
}
this.falling = !(cellDown || (nx && cellDiag)); // If player isn't on ground
}
}

```

Thanks for the help!

EDIT: I should note this also happens with the bottom of blocks as well. The same principles apply as clipping to the top, except you clip to the bottom instead.

# Answer
I'm guessing that vx and vy are velocities...

Since you check for vy floor and ceiling first, then any down-and-right collision gets corrected vertically first, then horizontally, so you end up running rooftop-to-rooftop.

In this particular case, maybe checking for vx left and right first might just fix it. Or handle it as an else clause, since once you correct horizontally (hitting the wall) it shouldn't continue to also handle it vertically.

Other strategies that apply for this kind of collision checking include:

* Look at x- and y-penetration, and fix the smaller of the two
* Never "correct" a motion more than you've moved in that tick
* Handle x- and y-penetrations sequentially

None of these is always the right thing to do, each has their place depending what kind of a world you're trying to simulate or present.

P.S. Having the demo live was very useful to understand what you were describing. ++.
> 1 votes

---
Tags: 2d, collision-detection
---


# Question
Title: Calculate visible points in grid in 2D game
I have a game grid and I need to figure out which game grid points are not behind occupied grid point from players view. The **visible points**. I'd like to define a visible point first, because it can mean many things and I had to figure it out:

* I call a point **visible point** if lines from **refference point**'s centre to two closest point's corners do not intersect with any occupied point. On image bellow, illustration shows **invisible in orange**, **visible in green**.

By this definition, we can make a map like this:

### Legend:

* \- visible pixel
* \- partially visible pixel
* \- occupied pixel
* \- player

I'm not interested in partially visible pixels, but I need to find out which pixels are visible. I don't know where to start. My only idea was to loop angles, but that doesn't work on larger map, where one iteration skips many actual pixels.

How do I check the visible pixels, or ideally, only the furthest visible pixels, as on this map:

And looping through all pixels must be probably avoided, that would eat up too much performance.

# Answer
The trick is to cast rays from the source point to the edges of occupied squares.

Then sort the rays by their angle. You then 'sweep' those angles and cull the pixels that are behind the intersection points. There are ways to optimize the algorithm by removing rays that have multiple intersections, as these rays will always be between rays that have only one intersection point.

See also my answer on a similar question: 2D - Smooth lighting with shadows for a tile-based game

And an example of the algorithm in a polygon environment: http://ncase.me/sight-and-light/ The theory is also easily applied to a grid, since that could be represented by bunch of square polygons.
> 2 votes

---
Tags: mathematics, algorithm, line-of-sight
---


title: 3ds max render to texture in PNG

text:
# Question
Title: 3ds max render to texture in PNG
Using 3ds Max 2012, I've been able to use the "render to texture" function to successfully bake my lighting. The only problem is that these image files are always output to TGA files. I need PNG files. If I select all of my objects I want to bake, the option button with \[...\] that opens up the "file name and type" selection menu is GREYED OUT.

If I select ONE object and try to export only that one object then the "file name and type" menu becomes clickable and I can select my file type. But when I click "render" I get an error message "The following nodes output to invalid directories and will not be rendered" with my one object listed below and it's output directory which is "sceneassets\images"

What am I doing wrong here?

Thank you.

# Answer
I know this is a couple years late but maybe someone searching for a solution will come across this.

So in order to change the "Default" file type assigned to new Output Elements created in Render to Texture, you can do the following.

1 MaxScript \> Open Script

2 Navigate to the MacroScripts folder in you installation directory

3 Open "Macro\_BakeTextures.mcr"

4 Change the filetype in the following line to the filetype you want. (line 87 for max 2014)

```
local   defaultFileType = ".tga" -- default bitmap file extension

```

5 Save the macroscript and restart 3D Studio Max.

Note that this does not change exisiting Output Elements.
> 2 votes

---
Tags: textures, rendering, 3dsmax
---


title: Texture not working on object

text:
# Question
Title: Texture not working on object
I have a project that I'm having a bit of trouble with. Let me try and explain. In short, I'm trying to apply a texture to an object, but instead it is a solid color.

I built a building in "Autodesk 123d design", and exported it as stl. Then I used an online converter to convert it to obj, then added that to the unity scene. I created a material with a texture and tried to apply it to the object, but it was a solid color.

I think the UVs on the object might be messed up. I tried some things in blender, but had no luck. Any ideas on how I can fix this?

**Edit:**

Here is the 3D model I'm working with: http://www.123dapp.com/123D\_Design/Conisbrough-Castle-Keep/4578568

# Answer
The STL file is a poor format for exporting 3D art, it only support 3D geometry. from wikipedia

> STL files describe only the surface geometry of a three-dimensional object without any representation of color, texture or other common CAD model attributes. The STL format specifies both ASCII and binary representations. Binary files are more common, since they are more compact.\[6\]

Try other richer formats such as `Fbx` or at least `Obj` when exporting from your 3D modelling program. I assume STL is only support for legacy reasons.
> 1 votes

---
Tags: unity, 3d, textures, uv-mapping
---


# Question
Title: In My Direct2D Gui System, Is It Safe To Use A Bitmap Render Target Per Gui Element?
I am trying to implement a relatively simple GUI system for use in a few simple games.

In this system, all Gui elements extend BaseControl. BaseControl has an update and draw method, as well as various parameters applicable to all controls (clipping, transforms, etc).

Let's say I have a Panel element, which contains other elements. The panel element will pass all its children a render target when it wants them to draw themselves.

There is a button that exists partially outside the bounds of the panel. If clipping is enabled in the panel, that button should show up clipped at the panel boundary. The button doesn't know it is out of bounds of its parent, nor should the button have to check if it needs to be clipped, or if clipping is enabled, or if a specific transform should be applied to it, etc.

Here's how I was going to go about handling clipping and other effects that should be controlled by the BaseControl class and not derived controls. Each control has an ID2D1BitmapRenderTarget, and they draw what they want onto it. When the BaseControl's internal Draw method gets what the derived control drew to it, it can modify it, get a Bitmap from its render target, and draw the bitmap to the parent's target.

So for example, if the parent is that panel with clipping enabled, it can perform any clipping on its internal Bitmap (which its children have drawn onto) before drawing that onto the window render target. Button draws to its own render target. Get bitmap from button's render target that is drawn to the Panel. The panel gets the bitmap from its render target, and clips the bitmap before drawing the contents to the window render target.

Right now, everything is drawing to a single render target (the window's render target). The problem is, once something is drawn to it, that drawing can't be editted. So if the internal draw method of a BaseControl, for example, had properties set to clip whatever the derived code drew, it would have no way to clip the now already drawn image without affecting other GUI controls or content drawn by other parts of the game.

Is it safe to have potentially a lot of ID2D1BitmapRenderTarget instances like this (there would be 1 for every control)? Is it as safe to make a lot of ID2D1BitmapRenderTargets as it is to make an ID2D1SolidColorBrush per control? Or is there a much better, more common sense way to accomplish what I'm trying to do that would only use one render target?

# Answer
Okay, I think I've figured out how to properly do what I'm trying to do. I need to use the Direct2D ID2D1RenderTarget's layering and clipping abilities.

1. Clipping can be done using `PushAxisAlignedClip` and `PopAxisAlignedClip`functions of the Render Target. Pass in the rectangle you want that represents the area that should be preserved to the Push function. Perform Draw calls. When the Pop function is called, only the region specified by the rectangle passed to the Push function will be drawn.
2. Layering can be done using the `PushLayer` and `PopLayer` functions of the Render Target. All calls after the Push will be placed in a separate layer, and these will be finalized and "flattened" on the call to PopLayer. Microsoft recommends using layers sparingly on Windows 7 and back. Windows 8 and forward apparently have major enhancements done in the layering code, and it is recommended to use them.

If you didn't notice, the Push and Pop functions imply clipping and layering can be stacked on top of each other.

Using these two methods, I can now use a single render target that all controls can draw directly to, where Pushing and Popping clips and layers allow controls their own "sections" of the render target before finalizing draws. I believe this is the proper way to accomplish what I need to do.
> 0 votes

---
Tags: c++, directx, gui, multiple-render-targets, direct2d
---


# Question
Title: How to set rotations to 0,0,0 in 3ds max for exporting in unity?
I'm a modeler in 3ds max and the unity programmer ask me that the object must have:

* pivot with Y up
* rotations at 0,0,0

but every object that I export in fbx he says don't have rotations at 0,0,0. I tryed different solutions as:
\- reset xform
\- freeze rotation
\- rotation to zero
\- $.rotation = eulerangles 0 0 0

but in unity he have values like this \[4.577637e-05, -1.525879e-05, 0\] or \[-90, 1.525879e-05, 0\] and so on

It's a problem that can I fix in max or the programmer has to fix it in unity?

Thanks

# Answer
There is a script for max called *XNA Utilities MAXScript for 3DS Max* which solves your problem. 3DS Max operates with two pivot points, which causes this value when importing to other 3D packages.

Althogh it was made for XNA development it works for Unity aswell. Just run this script before exporting the FBX file and you should get an imported mesh rotated to \[0,0,0\].

All credit to Dr. Charles B. Owen

I also point my Y axis on the model up, and export with the Y-up setting on the FBX export.
> 1 votes

---
Tags: unity, 3dsmax
---


# Question
Title: Steering behaviours: collision avoidance with rectangles
I'm trying to implement collision avoidance steering behaviour using rectangles. Most of the tutorials I've found are with circles, and there's a substantial difference. For example, I've been reading this:http://gamedevelopment.tutsplus.com/tutorials/understanding-steering-behaviors-collision-avoidance--gamedev-7777

My current approach: first, detect the nearest rectangle as done in the article. I create a point called *ahead* in front of my entity and then check if that point is inside the rectangle. After calculating the nearest object, I decompose my rectangle in a set of points, equally spaced in the rectangle walls. My entity will *flee* those points.

EDIT: I've also proven to convert my rectangle in an electromagnetic repulsive rectangle with 4 bars of homogeneus charged. It didn't worked. I also tried the "containment" section described in Craig Reynolds' website and it also didn't worked properly.

That works reasonably well: my entities try to avoid the rectangle. However, they sometimes get a bit into it, and when they're near the rectangle they start flipping to left and right quickly. That is not a very natural behaviour, so I think I want to prove another thing.

I've read this in gamedev SO: Wall avoidance steering I think that this could be what I need, approximately. However, I need some guidance on this.

* First, the answer speakes about a dot product of the wall-boid vectors (let's call them WBi). Which is the another vector I have to multiply with? In the code sample is noted as `partsList` but I don't know what it is. **So, first question: what is this second vector?**
* In my opinion, this algorithm as a very important flow. If the force is exerted in the direction of normal of the wall, and by chance my entity goes with velocity normal to the wall, it will stop. This, I think, could be a rare event because more steering forces are involved... **Second question: there is a way to avoid this? Is this effect important enough to take care of it even if I have more forces?**
* In fact, **I need an algorithm capable of detecting and avoding rectangles with steering behaviors** -or, at less, a way to move my entities in a space with obstacles using something compatible with steering behaviors, because I use them for coordinate movement.

Take in account that some combinations of rectangles could create convex shapes.

**EDITS:**

* The rectangles aren't rotated.

# Answer
While a bit different to your example above, I have implemented a spring algorithm into my game that has worked for me. The idea is that if the object comes close at a certain determined buffer distance to another object, a magic invisible spring appears and corrects the path of the object(s). Here is a video recording of my game engine demonstration illustrating what I mean. The yellow vectors visualize the spring between the two objects that appears when the objects come close together. The longish brick object uses a sliding spring, the short brick object uses a fixed spring at the object's center.

To calculate a repulsive spring action, use the physics to determine the acceleration conditional on the distances between the objects and some chosen parameters like spring\_stiffness and mass, e.g.

```
float spring_stiffness = 3.0;
float mass = 0.5;
float dist = CalculateDistanceObjectToObject(*ObjectA, *ObjectB);
float stretch = dist-buffer_distance;
float angle = GetAngleofVector(ObjectB.Position - ObjectA.Position);
float acceleration =  (spring_stiffness/mass)*stretch;
float acceleration_x = sin(angle*TOARC)*acceleration;
float acceleration_y = cos(angle*TOARC)*acceleration;

```

Where stretch is 0 for the spring at rest. Trigger acceleration when distance is under a certain pre-determined value.

Use as buffer as the circle spanning around plus some preferable extension. If you like your objects to avoid each other at closer distance, keep the extension small (e.g. 20%).

This works fine fir circular objects. If you have very longish objects like walls, you need to adapt the code to have a "sliding" spring. For my demonstration above, I used a SAT (Separate Axis Theorem Approach). Note how the yellow line shifts with the flightpath. For this you need to look up tutorial on how to calculate the closest collision point between two boundaries and attach a "sliding spring between the objects.

Another useful extension is to determine mass that decreases when the distance is getting smaller between the objects, to avoid, by all means, a collision, as the spring force consequently increases. I use an algorithm that increases mass to infinity if the distance between the objects is approaching zero. `float mass=0.5f/((2.5f-radius)/(dist-radius));` where radius is the both objects inner circle. (Note: You may also want to modify this to be smoother, e.g. sinus function etc.).

A finer point is to use this for AI control. Use the determined acceleration vector as the 'set\_acceleration' and link it with your game control, e.g. turn into the direction, switch on thrusters and accelerate until set\_acceleration == actual\_acceleration. This would give an impression like the object is on collision course and does a last minute correction, fires its thrusters to escape.

Edit: The game logic could therefore look something like:

1. Determine a circle with radius from the object's center to its farthest corner. Do this for all objects during initialization stage of the game (call this minimum\_circle).
2. Create a second buffer\_circle by a chosen realistic expansion of the minimum circle (e.g. 20 % larger than minimum\_circle)
3. Check distances between all objects circle\_buffers (if necessary make use of calculation saving algorithms, e.g. check distances within a certain sector etc.)
4. Flag a collision approach between object A and object B.
5. If two buffer\_circles intersect (=distance(A.pos,B.pos)-A.buffer\_circle.size-B.buffer\_circle.size\<=0), apply spring algorithm to create a repelling force with spring\_size=A.buffer\_circle.size+B.buffer\_circle\_size
6. Determine either object A or B to be the eluding one, e.g. wall vs player/AI. Consequently decrease mass of object A relative to object B, so the spring force increases to infinite if distance between the minimum circles approaches zero.
7. Unflag collision approach and release spring algorithm when object A and B buffer\_circle's are not intersecting anymore.

Optionally you may at point 5 give one of your object a random initial push (up/down or normal of net\_speed\_vector, to give it a bit more realism if two objects are on direct head-on approach with each other. Also, if rectangles are subject to change, change the circle size (buffer and minimum) accordingly with it, so that the spring algorithm gets instantly updated.
> 3 votes

---
Tags: libgdx, ai, steering-behaviors
---


# Question
Title: What are the common methods for achieving dynamic asset destruction?
I am trying to determine the most appropriate destruction solution for an online desktop game. There are two main factors here that I am considering; 1) the performance of the approach taken and how much resources it requires, 2) the turn around time for making an asset "destructible".

There are three main destruction approaches which I am aware of:

1) Creating a destruction animation for each asset, which plays based on specific conditions

2) Create a second version of each asset consisting of rigidbodies. Under specific conditions, replace the static asset with the rigidibodies and gravity/ other physics forces will cause it to collapse

3) Use a mesh splitting system to dynamically split static assets into rigidbodies at runtime

Option 1 appears to have the best performance, however it also requires the most preparation time to do realistically. Option 3 on the other hand requires no preparation time for assets, however it is the heaviest on performance since it is completely physics based.

My question than is, which of the above approaches is most common in the industry today? Or if there is another better approach which I have missed, what is it. Ideally I would like to go with option 3, but I fear that the performance hit would be too severe.

# Answer
> 1 votes
I think there are too many factors to consider to make a cut and dry decision. That is why all styles are still in use today. Some projects use more then one in concert - animate the core elements and use physics to drive some additional dynamic objects or particles. The latest GTA worked that way in many places - some dynamics but a lot of canned animation since gameplay elements were important and objects and characters needed to end up in the right place for progression. Games like Star Wars: The Force Unleashed uses both predefined shatter points and dynamic mesh splitting because it is core to the power and structure of the player, and everything needed to be slicable by a sabre. Voxels are popular now for all over 'everything is destructible' but there are trade offs there, as well.

# Answer
> 1 votes
These days, for games? You're likely to find that cubic voxels or other uniform-subdivision approaches (voxels, hexels(?)) are the most common... it's a bit of a fad. You might call this the "atomic" approach since destructibles are made up of *atoms* as in the original sense of that word, i.e. "indivisible element". Building a thing as inherently fragmented makes it far easier to actually break it up - both logically and visually - when the time comes, and is the reason why (again, these days and specifically for games) it's far less common to go for dynamically-fragmented geometry... one of the problems with this latter approach is that it can be harder to control the process of fragmentation in a way that doesn't potentially impact heavily on performance, for example, when shattering a wall, just how many vertices are needed? How many are too many for the hardware? Using atoms, these questions are immediately answerable because the lattice in which they exist immediately answers such questions - e.g. within 5 meters, we have 5 voxel boundaries.

Another approach that is related is something more like octrees or KD-trees, where we may still have these atoms but they are wrapped / grouped in large elements to avoid having to deal with many finer elements except where absolutely necessary. For example, if we cast a ray through a space, if a container element contains no atoms, we can walk through it in a single step, but if contains one or more, we'll need to be iterate through it on an atom-by-atom path in order to ensure we don't hit any obstacles on the way through.

Games built using the atomic approach e.g. cubic voxels make this easier because we can say definitively that within some distance, area or volume, we have P(x Q(x R)) individual elements we will have to deal with as a result of some or another destructive action.

---
Tags: performance, 3d-meshes, rigidbody, rigid-body-dynamics, procedural-destruction
---


# Question
Title: Collision Response in Entity Components Systems
This question seems to be a duplicate of mine, but I don't think it is.

I'm trying to build a game using an ECS, but I want this ECS to be as simple as possible, therefore I am eschewing messages.

My question is where should the the behaviours go for collision responses. Not physical responses, but logical response (e.g. bullet hurts player, player picks up health, explosion destroys enemies).

Is there a big HandleCollisionsSystem, or does each type of collision have it's own system or should the logic be in one or both of the colliding entity's components (but a component is just data, right?)

I'm sure there are several approaches, but for the moment I would like to err on the side of simplicity.

# Answer
> 1 votes
You can call certain collision events like Unity does, allowing components to exist independently but still work together. For my physics engine, I have all collision processing centralized so detecting when a collision just started or ended, or if there is collision at all is just a matter of a boolean check and calling off the corresponding events. I.e.:

```
CollisionPair[,] CollisionPairs;
void ProcessCollision (Body b1, Body b2)
{
    CollisionPair colPair = CollisionPairs[b1.ID, b2.ID];
    if (/*CollisionDetected*/)
    {
        if (!colPair.IsColliding)
        {
            b1.OnCollisionEnter (b2);
            b2.OnCollisionEnter (b1);
        }
        colPair.IsColliding = true;
    }
    else {
        if (colPair.IsColliding)
        {
            b1.OnCollisionExit (b2);
            b2.OnCollisionExit (b1);
        }
        colPair.IsColliding = false;
    }
}

```

Then to listen to these events:

```
void Start ()
{
    GetComponent<Body>().OnCollisionEnter += HandleOnCollisionEnter;
}

void HandleOnCollisionEnter (Body body)
{
    if (body.Tag == "Bullet")
    {
        Health -= 20;
    }
}

```

# Answer
> 1 votes
In my articles I wrote about a possible solution to your problem. In my vision of ECS, I group the systems according their context and level of abstraction. When I talk about context, I mean the scope of the systems. For example, are the systems handling enemies? Are the systems handling weapons? Are the systems handling the player? Once I give a context to the systems, I group them under the same namespace, like *PlayerSystems*, *EnemySystems* and so on.

Level of abstraction is instead about how abstracted a system is, for example: is it the system that manages the general physic collision? Or is it the system that manages the collision between enemies and enemy targets? The latter is less abstracted than the first one.

In this scenario, what I would do is to let the general system, that manages collisions, communicate with the less abstracted systems.

The communication could happen through an observer, defined in the same namespace of the abstracted system and used by injection by the other systems.

Alternatively (and that's what I actually do), I let the systems communicate through the components. The *EnemyTargetColliderSystem* knows exactly the same component used by the *PhysicCollisionSystem* therefore knows when an enemy collides with something. At that point it must check if *something* is a valid target.

This is just one way to solve the problem, it really depends if you want to take advantage of the computation already performed by the PhysicCollisionSystem. If not, you can simply perform a collision check between all the enemies and possible enemy targets inside the EnemyCollisionSystem.

Be careful that I call it enemy target and not player. It would be wrong to let an EnemyEngine know about a component relative to the PlayerEngine.

if you want to know more about my point of view on ECS, you can read my articles starting from this one: http://www.sebaslab.com/the-truth-behind-inversion-of-control-part-i-dependency-injection/

# Answer
> 0 votes
I would Have a Handler, "Handle" those depending on the type of entity. Unfortunately, in my Non-ECS engine, I have collision code for every type of collision between different types.

Works like a charm tho :)

---
Tags: entity-system, collision-resolution, entity-component
---


# Question
Title: How do I keep 1v1 player positions consistent over UDP on Kryonet?
I have a server which is simple:

When two connections comes in, it opens a game room, pass their connections to it and runs a thread with a gameloop. (Everything is running on Kryonet)

So... I made the movement, it works on TCP and UDP, but it has to be done via UDP, cause it will be a real-time game, there is no place for a lag. After switching updating positions to UDP, as we all know, some of the packets are lost. Sometimes the server is loosing some packets and it doesn't send them to the second client - that's why the opponent seems to move by 2x, not by x (it happens only sometimes).

My question is: How this kind of things should be implemented? How everything should be handled, I mean - sending states (walking, running), positions etc that there is no visible lagg? Should I send the packets more often? I heard once, that the server should also save player's positions and send it back to him and his opponent (to avoid cheating and laggs). I know how to implement these things, but I don't know how should it look like in a real-time fighting game.

If there is any experienced programmer, that could give me an advice, I would be grateful.

# Answer
You will always run the risk of losing packets and having latency - you need to hide this from the player while trying to give reliable gameplay. If the data being sent is small you can simply send the current frame and the last 32 frames of data in a single packet. Mark each frame with a sequence number before you send it. On the receiving end the peer only consumes those pieces of data it has not yet seen. In this way you get some data redundancy. On the receiving end, you will also want a buffer to delay processing this data to help smooth out the 'jitter' of the latency. Latency is never constant, and you don't want to be processing the data exactly as it arrives or you might have block waiting for the next piece. Instead you want to artificially delay the data once received to give your peer more time to receive late packets.

There are a lot of other options here - you could use a snapshot system with delta compression (Gaffer covers a lot of this here and it is an excellent read: http://gafferongames.com/networked-physics/introduction-to-networked-physics/) and extrapolation to help *guess* where people are going to be. There are a lot of details to explore.
> 0 votes

---
Tags: multiplayer, synchronization, udp
---


# Question
Title: How can I minimise memory thrashing when doing vector math in C# or C++?
I'm doing a lot of 3D math in my game engine loop using typical classes like Vector3D, Matrix4x4, Plane3D, etc. Currently every operation causes a new object to be created for the result value. The number of new objects created causes a stutter whenever the GC kicks in.

In this simple vector operation, 2 new Vector3D objects are created, one at the divide and one at the multiply operator.

```
// C#
result = (v / len1) * len2; // where len* is a `double`

```

I happen to know some C++, so an optimized version would create a disposable object on the stack and pass that to the individual ops, thereby automatically disposing off the temporary objects at the end of the function (also avoiding the GC altogether), something like this:

```
// C++
Vector3D result;
v.divideBy(len1, &result);
result.multiplyBy(len2, &result);

```

But as you can see its cumbersome and unreadable. So what are commonly used memory optimization strategies used by pro C++ gamedevs to optimize vector math? I'm looking for general platform agnostic solutions that can be implemented in C# and other high-level languages, although C++ memory tricks are also appreciated.

# Answer
Are you sure that the matrix operations are causing the slowdown? In C# most Vector libraries implement their types as structures, which are not generally allocated using the garbage collector, but are instead created on the stack. The temporaries in your example don't cause allocations that need to be collected.
> 4 votes

# Answer
> Currently every operation causes a new object to be created for the result value. The number of new objects created causes a stutter whenever the GC kicks in.

Make sure your math types are value types (`struct`s); value types don't create garbage (unless boxed inside a reference type).

If your math types are already value types, use a profiler, because the GC hitches you're seeing aren't directly caused by what you appear to be assuming they are.

> I happen to know some C++, so an optimized version would create a disposable object on the stack and pass that to the individual ops, thereby automatically disposing off the temporary objects at the end of the function (also avoiding the GC altogether), something like this:

C# doesn't have RAII, and the `IDisposable` pattern is for disposing *unmanaged* resources (or managed resources that are themselves `IDisposable` because they contain unmanaged resources). Using it for math types will not optimize anything.
> 3 votes

---
Tags: c#, c++, performance, optimization, memory-efficiency
---


# Question
Title: How do I create a draggable object which snaps to obstacles in the way?
I bring yet-another-drag-with-mouse question (I am using Unity with C#), but with a less common particular detail: the existence of obstacles in the middle of the way trough which dragging occurs (3D space, not 2D).

Let me explain. Suppose I have a plane over which I want to drag a cube called "obj" .That's easy. Here is my simple implementation for that:

```
void Update () {
  Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  RaycastHit hit;
  if(Physics.Raycast(ray, out hit, 1000000))
  obj.transform.position = new Vector3(hit.point.x,0.25F,hit.point.z);
}

```

It works. However, suppose that I also have a few other cubes over the plane, which are the obstacles. Obviously, when the player moves "obj" over the plane, such movement should be blocked by the obstacles. And then, while colliding with the obstacles, "obj" should move only snipped to the sides of that obstacle. If mouse is moved and "obj" stops colliding with obstacles, free dragging-style movement resumes again.

To make the challenge harder, I am trying hard to achieve that without the use of RigidBody components at the obstacles (the dragged object can have it). Any ideas on what is the most efficient way of achieving that? Many thanks!

EDIT: Commentators have brought to my attention that I should mention that objects are allowed to rotate when snapping.

EDIT 2: Considering the difficulty of the original formulation, I changed the question allowing the use of Rigidbody components at the dragged objects. The solution just can not use Rigidbody components at the obstacles.

# Answer
> 2 votes
It's difficult to detect collision without any rigidbodies involved, but since you're using cubes you may be able to use Bounds.Intersects. Each update, check if the dragged object's bounds intersect with any obstacles' bounds. If it does, then you could try this:

1. Disable the Mesh Renderer for the dragged object to make it invisible (but continue to drag it).
2. Drop a visible, placeholder object identical to the dragged one at the last position before bounds intersection (now it looks like the object stopped, but really you are still dragging the original).
3. Each update, check to see if the bounds of the object you're still dragging intersect with an obstacle's bounds.
4. When the dragged object's bounds no longer intersect with an obstacle's, delete/deactivate the placeholder object and re-enable the Mesh Renderer for the dragged object to make it visible again.

You never stop dragging the block; it simply appears to the user that the block has stopped dragging while it would intersect with an obstacle.

# Answer
> 1 votes
Without having done it myself, here's what I'd try:

1. Decide how high some obstacle on the plane has to be in order to block your dragged object (where "high" means removed along whichever axis is appropriate—I'd assume the one that points toward the camera).
2. Each update, save the position of your raycast hit.
3. Each update, before saving the position of the current raycast hit, check the position of the current raycast hit against the position of the previous raycast hit.
4. If the difference \>= blocking height, stop your moving object at the previous raycast hit position.

It seems to me that if you'd like your object to drag along a slanted plane of an obstacle, you should simply have its transform continue to follow the position of the latest raycast hit.

---
Tags: unity, c#, collision-detection, transformation, mouse
---


# Question
Title: How can I develop my Android game for different phone resolutions?
For instance, the Motorola Droid is as wide as the G1, but has more height.

Should I try to spread the UI out across the extra height found on the Motorola Droid? How do others handle this problem?

I'm not using OpenGL, but a SurfaceView for a 2D game.

# Answer
Be aware of density independence (basically resolution) as described here: http://developer.android.com/guide/practices/screens\_support.html

And as related to aspect ratio, pick your minimal target aspect ratio and design within it as sort of a safe frame. When confrontend with wider aspect ratio, show more of the game which is not critical to gameplay. I have posted a similar question here and described what I'd do: How do you approach resolution independence in raster based graphics content?
> 7 votes

# Answer
You can do the dynamic resolution which I show here on the iphone:

http://www.blog.namar0x0309.com/2011/10/adaptive-resolution/

* Make sure you place everything with ratios. For example a health bar would be placed at 80% of the screen width with 10% of the screen width for its horizontal scale (refer to CSS styling dimensions). It's a little weird in the beginning but you won't have to deal with all the different resolutions in the long run as your widgets/images will move dynamically with different screens.
* If your game uses picking translate that too with ratios (you need an original set dimension which you can use as reference to build ratios with the device dimensions.
> 3 votes

# Answer
If you are using eclipse, you can have several different sized images put into the drawable-ldpi, drawable-mdpi, and drawable-hdpi and the android engine will automatically choose which image will be appropriate for the screen resolution.
> 1 votes

# Answer
Keyframe mentions a good approach, but I'll offer two more:

1) Design your game for multiple resolutions/aspect ratios. The idea is to take advantage of every bit of the screen real estate, but "design out" any advantages that one aspect ratio might have over another. Depending a lot on the game, different aspect ratios may still have an advantage over others, so you'll want to keep that in mind for things like multiplayer matchmaking, leaderboards, achievements, etc. if any of these are relevant.

2) Use the extra space for more HUD / chroming. Pretty much what Keyframe said as far as having a baseline or minimum resolution supported, but instead use the extra space for something other than the game action.

The big disadvantage with the second approach is that if you take something very square-ish as your "safe zone," you leave a lot of unused / unintentionally used pixels in a widescreen setup.
> 1 votes

# Answer
Chosing the optimal resolution for a game from the start of development can reduce headaches with porting later on.

The "best" resolution depends on a lot of factors:

-The platform the game is supposed to be released on first

-Other possible platforms you plan to port to later

-Graphical fidelity (An 8-bit or pixel art game doesn't need to be hi-res.)

-Genre (A puzzle-game can probably get away with a lower resolution, but a high-speed competitive FPS might not.)
> -2 votes

---
Tags: android, resolution
---


title: Is FreeGLUT still a good choice?

text:
# Question
Title: Is FreeGLUT still a good choice?
I recently decided to utilize the C++ library called FreeGLUT to have a window be managed from my program, where I can draw things via OpenGL. But at the same time I saw some people telling that it is an old library, not that much reliable and so on... Should I keep using that or move to another one?

# Answer
I would only recommend using FreeGLUT if you are just learning OpenGL and don't want to worry yourself with things like window and context creation.

FreeGLUT is also use full when you would want to create a quick graphics demo, something that purely shows off some graphics related concept.

Its otherwise a bad choice for games as you don't have control over the game loop and raw input collection, which are quite important for high performance games.
> 2 votes

# Answer
GLFW is a good alternative. It is still actively maintained, and easily allows creating an OpenGL context and window, supports multiple windows, and supports controller input.

http://www.glfw.org/

There are tutorials on their website for using it, but if you are already used to FreeGLUT, this tutorial here may be of use, as this tutorial series primarily used freeglut but transitions over at this point in the series.
> 1 votes

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


# Question
Title: Need some general direction for turn-based planning AI
I'm planning to make a turn-based fleet battle game. While I *think* I can figure out most of the things I need, I have no idea about the AI handling this sort of game. I need some general direction about how should I deal with it.

None of the things I described below is currently done - except maybe unit movement stuffs.

The combat resembles Frozen Synapse or Steambirds, in which you and your opponent plan their unit's actions and then execute it to see how it resolves. Since the units are naval warships, their movement is restricted by current direction and speed, etc etc. They attack when you order them to do so(not automatic).

I *think* I can give scores to each move(like Chess AI), depending on its location, direction, possible movement area, known enemy positions and things like that. Then I can use Minimax algorithm to let the AI select the best move.

Now, I'm asking because I can't figure out

1. which situation should the score be based on. Should the AI make a plan assuming the enemies are all moving straight, predict the best enemy plan based on it, and then write the actual plan based on the prediction? Is it going to demand a lot of processing power? Or is there simpler way using Minimax?
2. Unlike grid-based tactical games, the area which a unit can move is a (semi-)continual area. If I try to give score to all possible positions, that might take too much processing power. Is there a way to handle this issue neatly?
3. There might be more efficient/effective alternatives to the Minimax on this particular game which I do not know.

So... i'm asking for general direction about how should I handle the AI. Details will be in when I actually make it.

# Answer
> 3 votes
When the game is parallel turn-based, you can calculate your moves while the player is making theirs. This gives your AI quite a lot of time. So performance is not that much of a concern as it would be in a real-time game.

In many games it is not actually necessary to plan ahead more than one round. It is often possible to write a passable AI which doesn't. It will certainly be weaker than any moderately experienced player, but you can compensate for that by giving the AI a material advantage in form of more and stronger units. Yes, this is a lazy solution, but it is the solution used by the majority of titles on the market, among them many bestsellers. The expectations of the players are quite low in this regard.

When you decide that you do want to calculate more than one move ahead, the number of calculations increases exponentially. In an average turn-based strategy game, there is a very large number of possible moves each unit can perform per round. So even when your AI has up to a minute per move, this might become too much to handle. You can not assume that the player will set idle, so you have to also calculate the possible moves the player could perform and evaluate them like you evaluate those of the AI. This creates a really, really broad game-tree, which means some alpha-beta pruning will be necessary.

You can easily do that by reducing the moves you evaluate down to those which fulfill some tactical objective. First, check which tactical objectives are available for each unit. Which objectives are worth considering depends on your game mechanics, but it could be things like "rush enemy unit A", "snipe enemy unit A", "secure objective A" or "protect self". Take the one most obvious move to fulfill each objective, and use these moves as possible candidates by calculating the strategic value of each.

A completely different approach is to not focus on creating a strategically smart AI, but rather one which has units act impulsive like you would expect people to act in a real-time environment. Have units only react on what they can see and make them do decisions depending on a state machine governed by emotions like "anger" or "fear", not on what would be the decision with the strategically best outcome. The result will be an AI which will definitely be far too weak to stand any chance against a player when put on equal terms, but one which will be quite enjoyable to play against when a small number of player units is put against an overwhelming enemy force.

---
Tags: ai, turn-based, turn-based-strategy
---


title: Vector3.MoveTowards on y axis only

text:
# Question
Title: Vector3.MoveTowards on y axis only
I am making a final boss fight area and it has multiple platforms that go higher and higher up, I need the boss to follow the player up and down. I have a script that has the boss the follow the player but I need to restrict it to the y axis only

Here is the script I have:

```
 public class FollowPlayerY : MonoBehaviour {

     public Vector3 playerPos;
     public float followSpeed;
     public Transform player;

     void Update () {
         playerPos = player.transform.position;
         float step = followSpeed * Time.deltaTime;

         transform.position = Vector3.MoveTowards (transform.position, playerPos, step);
     }
 }

```

# Answer
You effectively answered your question: you want to move the boss towards the player Y, leaving X and Z unchanged. To do that, create new vector and give it X and Z from current position and Y from player position:

```
...
Vector3 actualTarget = new Vector3(transform.position.x, playerPos.y, transform.position.z);

transform.position = Vector3.MoveTowards (transform.position, actualTarget , step);

```
> 2 votes

---
Tags: c#, movement
---


# Question
Title: Storing visibility graph for path-finding: do redundant and non-visible pairs of points have to be saved?
Using C# in Unity, I have recently implemented an algorithm that determines during run-time the visibility graph of a given scene in my game project (visibility between corners of obstacles). Now I am in doubt about the best way to save the result.

So, considering that I want the visibility graph for path-finding, I would like to know the following:

1) Suppose that points A and B are visible to each other. Then, AB and BA both detect the same visibility line. It happens to all mutually visible pairs in my case. So, in order to perform an A\* algorithm do I really need all these redundant pairs or can I get rid of the redundant ones, leaving only AB or only BA?

2) Now suppose that points A and C are NOT visible to each other. Do I have to save AC and/or CA? It is, to apply an A\* algorithm do I have to save pairs of points that are not visible?

I ask that because if the answer to both questions is "yes", then the final array storing the graph becomes NxN, where N is the number of points (corners of obstacles) in the scene, with each cell holding the value 0 for non-visible pairs or a value equal to the distance between each visible pairs. I think technically it is called an Adjacency Matrix.

However, if the answer to any or to both of these questions is "no", then I would be able to save a lot of memory because the final results would require a much smaller array. The reason is that I would then not save redundancy and also most points are not visible to each other (it's technically a non-dense graph), so they would not be included.

But I am not sure I can go that route for path-finding. So, in case the answer to any of the 2 questions above is "no", what is the logical format I should use for saving the results, in order to perform an A\* algorithm in the visibility points?

Many thanks for your time.

# Answer
To answer your main questions:

1. Does your A\* implementation expect undirected graph? Do you have one-way mirrors?
2. no, unless you require logic for finding not-visible-paths

And about saving memory, it all depends - how spare the adjacency matrix would be? *(profile!)*
If most nodes see almost all nodes (a forest for example), you would lose a lot memory by not going matrix - while saving one edge in matrix would take 1 bit, saving and `Edge` object would take at least 3 pointers (assuming 1. was no), that is at least 96 (192 for 64-bit) times more.
Additionally, you can optimize the matrix memory as well: using the knowledge that it is triangular matrix you already cut the memory requirements in half. Moreover, there are techniques to compress spare matrices to take even less space.
On the other hand, storing edges has it upsides, for very sparse matrices(interiors, dungeons) it would probably take less space and offer superior comfort.
> 1 votes

---
Tags: c#, path-finding, storage, graph, visibility-determination
---


# Question
Title: Does each game asset always require a prefix such as 'spr' or 'obj' in their name?
Having started only recently with using GameMaker for game development (*keep in mind that this is the first time in a long while that I'm doing something like this, so I'm technically at beginner level*), I've lately been thinking about something that seems to be common place throughout creating a game with the software.

Through all the tutorials I've been through so far in GameMaker:Studio, I've noticed that the tutorials seem to want the names of game assets to always have a prefix in their names depending on what the game asset is, usually something like *spr\_* for sprites or *obj\_* for objects.

I've never exactly liked this sort of naming method, but I don't know whether or not to keep doing this or to just avoid using the prefix entirely. Does the engine require these prefixes for a game to compile or something?

**Are these prefixes necessary?**

# Answer
> 3 votes
No, this is just a coding convention on the part of the people who wrote the code. You can name your objects however you want (within reason... I'm sure `$@#$` would not be a legal name).

The idea behind this convention is that you know what type an object is just by looking at its name, which is supposed to aid understanding while reading code. I don't really like it, either. :)

---
Tags: game-maker
---


# Question
Title: How do I optimize 2D visibility cone calculations?
I'm creating a simple 2D game and got a little bit stuck with a visibility cone algorithm, influenced by walls and other obstacles on the map.

The only issue I'm currently having, is that it's **very slow**.

On a map with ~100 square obstacles, an `UpdateVision` call takes up to 60ms without compiler optimizations (up to 15ms with, so still very long), though depending on how many obstacles are in the cone. According to the profiler, most of the time is spent in `find_intersection`.

I know one of the main causes: the algorithm actually checks all the obstacles in the 120 degree cone, ignoring how far away they are. The small cone is actually a masked version of this:

So ignoring far points early should help a lot. Except I can't simply ignore them, because then stuff like this happens:

How can I improve on this?

---

Here is the commented relevant part of my code:

```
struct IntersectionData {
    float T1, T2;
};

/*
* For two lines, (p11, p12) and (p21, p22)
* Finds their intersection point.
* The point coordinate ca be calculated with: p11 + T1 * (p12 - p11) OR p21 + T2 * (p22 - p21)
*
* Formula from: http://ncase.me/sight-and-light/
*/
IntersectionData find_intersection(const sf::Vector2f &p11, const sf::Vector2f &p12, const sf::Vector2f &p21, const sf::Vector2f &p22)
{
    float r_px = p11.x, r_py = p11.y;
    float r_dx = p12.x-p11.x, r_dy = p12.y-p11.y;

    float s_px = p21.x, s_py = p21.y;
    float s_dx = p22.x-p21.x, s_dy = p22.y-p21.y;

    float T1, T2;

    T2 = (r_dx*(s_py-r_py) + r_dy*(r_px-s_px))/(s_dx*r_dy - s_dy*r_dx);

    if (r_dx != 0)
        T1 = (s_px+s_dx*T2-r_px)/r_dx;
    else
        T1 = (s_py+s_dy*T2-r_py)/r_dy;

    return IntersectionData{T1, T2};
}

/*
* Finds the closest intersection of a ray with origin (x, y) and angle a
* With a wall
* A wall contains a vector of points, making a convex shape.
*/
sf::Vector2f Enemy::CastRay(float a, const std::vector<std::shared_ptr<Wall>> &walls) {
    float best_T1 = 1000000;
    const float cos_a = cosf(a), sin_a = sinf(a);
    for(const auto &wall : walls){
        for(size_t i = 0; i < wall->points.size(); ++i){
            const auto &p1 = wall->points[i];
            const auto &p2 = wall->points[(i+1)%4];
            const auto intersection = find_intersection({x, y}, {x+cos_a, y+sin_a}, p1, p2);
            const float &T1 = intersection.T1, &T2 = intersection.T2;

            if ((T1 > 0) && (T2 > 0) && (T2 < 1))
                if(T1 < best_T1)
                    best_T1 = T1;
        }
    }
    return {x + best_T1 * cos_a, y + best_T1 * sin_a};
}

/*
* Algorithm from: http://ncase.me/sight-and-light/
*/
void Enemy::UpdateVision(const std::vector<std::shared_ptr<Wall>> &walls)
{
    // first, let's get all the vertices of all the walls

    std::vector<sf::Vector2f> points;
    for(const auto &wall : walls)
        for(const auto &p : wall->points)
            points.push_back(p);

    std::vector<sf::Vector2f> visPoints;

    for(const auto& point : points) {
        float angle = atan2(point.y-y, point.x-x);
        float normalized = NormalizeAngle(angle);

        // if the point is outside of the cone of vision, ignore it

        if(normalized > visibilityAngle || normalized < -visibilityAngle)
            continue;

        // analyze two slightly off angles, to see both a wall the point belongs to and possibly a wall just behind it

        float a1 = angle + 0.0001, a2 = angle - 0.0001;

        auto p1 = CastRay(a1, walls);
        auto p2 = CastRay(a2, walls);

        visPoints.push_back(p1);
        visPoints.push_back(p2);
    }

    // also add two rays just on the edges of cone of vision

    visPoints.push_back(CastRay(direction - visibilityAngle, walls));
    visPoints.push_back(CastRay(direction + visibilityAngle, walls));

    // sort the points based on their angle, so they can be correctly drawn with OpenGL TriangleFan mode

    std::sort(visPoints.begin(), visPoints.end(),
        [&](const sf::Vector2f &p1, const sf::Vector2f &p2) {
            return NormalizeAngle(atan2(p2.y-y, p2.x-x)) < NormalizeAngle(atan2(p1.y-y, p1.x-x));
        });

    float mid = texture.getSize().x / 2;

    // vision is a vector of sf::Vertex and is used for actual rendering
    // the third argument is the UV coordinate on the texture

    vision.clear();
    vision.push_back(sf::Vertex({x, y}, sf::Color::Green, {mid, mid}));

    for(auto &p : visPoints)
        vision.push_back(sf::Vertex(p, sf::Color::Green, {p.x - x + mid, p.y - y + mid}));
}

```

# Answer
> 4 votes
I have a couple of suggestions

## Avoid Allocations and Copies

A lot of your code has unnecessary allocations and copies. Instead of filling a vector with `push_back`, try pre-allocating the vector and setting the data there. You have a fixed maximum number of intersection points, so pre-allocate a vector of that size.

## Do a Simple Broadphase

Before you do anything at all, find out which shapes could possibly intersect the camera. You already do this here:

```
    if(normalized > visibilityAngle || normalized < -visibilityAngle)
        continue;

```

Avoid doing it again here:

```
for(const auto &wall : walls){
    for(size_t i = 0; i < wall->points.size(); ++i){

```

Instead, you should only check the walls which potentially intersect the camera when raycasting.

### Example: Try Frustum Culling + Quad Tree

Convert your algorithm so that it uses a frustum rather than a cone with a radius. Then, do the following:

* Create a quadtree. All of the points in all of the rectangles should get added to this tree.
* Intersect the quadtree with the bounding box of the camera frustum. This gives you a list of potentially intersecting rectangles.
* Continue as normal, using only these intersecting rectangles.

You can then make your frustum longer or shorter to keep from having to check so many rectangles.

### Example 2: Try Bresenham's Algorithm

You can make a loose, coarse grid over your whole scene. When a shape intersects a grid cell, add it to a list associated with that cell. Then, when you cast a ray, use Bresenham's Algorithm to search for the cells that the ray could intersect. Only check the shapes contained in these cells, rather than *all* of the shapes. If your grid is coarse enough, Bresenham's algorithm will run extremely quickly.

# Answer
> 2 votes
Whenever possible, use *vectors, not angles*. Arithmetic operations are more efficient than trigonometric ones, and vectors enable spatial indexing.

## 1. Use vector cross products for cone intersection (not angles)

Your current method wastes cycles on the costly `atan`, `sin` and `cos` functions *for every point **upfront***, even points that get discarded.

Instead, consider this:

The sign of the cross product of 2 vectors determines which *side* (left or right) of the second the first is on. Example implementation on StackOverflow here. With this, you can filter points by whether they are both—

* to the *right* of the vision *left* border (in red), and
* to the *left* of the vision's *right* border (in green):

All points that satisfy the conditions (i.e. fall within the red-green section on the right) are within the vision cone.

This requires only arithmetic operations in the inner loop.

## 2. Precompute a spatial index

This is an illustration of @mklingen's observation that you can optimise spatial queries easily, by precomputing a spatial index and using it for broad-phase pruning.

For example, if you precompute a quadtree containing all of your environment's corner points, you can do an initial *(log n)* quadtree walk to prune points down to the vision region's AABB:

For a large or detailed map, this gives a huge performance boost.

---
Tags: c++, 2d, optimization, shadows, visibility-determination
---