# Question
Title: Are there many games involving the manipulation of water?
I'm in the very, very early brainstorming stages of a game which centers around the manipulation of water and the terrain around it. (i.e., changing the water's state between solid, liquid, gas; building up or tearing down hills to control its flow; and so forth.) I'm not yet sure if it should be a puzzle game, a platformer, or what.

Usually, when brainstorming a game, I try to find games with similar mechanics to see what is done well, poorly, etc. But this time, I'm having trouble thinking of any games that use the flow of water as a primary mechanic. (Pipe Dream is about all that comes to mind.)

So, I'm asking around... does anyone know of any games where controlling water is a major aspect? Is there much reference material (of any kind) on the subject of water as a gameplay mechanic? Or any ideas where to look?

Thanks

# Answer
> 12 votes
Dwarf Fortress comes to mind. Water can be pressurized and (re-)routed through a mountain as it's constantly influenced by gravity.

The game isn't *about* water (it's essentially a city-building game), but the water mechanics really add to the depth of the gameplay. There's a good article on Gamasutra on how they did the water. I'll try to find it.

**Edit**: found it. Here's some representative images..

# Answer
> 11 votes
## Wetrix

Wetrix was a cross between Tetris, and water manipulation. The idea was to create lakes by raising terrain to capture water. It was pretty fun for the N64 and PC

> In the classic mode, you start out with a flat piece of land; the ultimate goal being to gain as many points as possible, managing a landscape of lakes and ponds. This is accomplished by maneuvering different types of random pieces that fall onto the playing area, one at a time (much like the puzzle game Tetris). These pieces each have differing effects upon the arena, but the standard pieces are uppers, which increase the land level by one tier, and fall in different shapes. These can be used to sculpt walls and dams, and the perimeters of lakes. Shortly into the game, water bubble pieces will begin to fall, which burst upon impact with the land, and flow realistically like a fluid across the landscape. The main method of gathering points is by using the fireball piece to evaporate lakes, the amount of points depending upon the volume of water. On the right side of the screen is a water gauge, which fills up as water falls off the edge of the landscape, or down holes created by bombs. The player loses the game when the gauge fills up to the top. The only way to reduce the level of the water gauge is by evaporating water with fireballs, again the amount it is reduced by depends on the amount of water evaporated.

*Images by ign.com*

# Answer
> 5 votes
Hydrophobia is a game that is centered around the physics of water. So I guess this game is what you're looking for.

# Answer
> 5 votes
Some games that come to mind:

There's also a game I seem to remember but wasn't able to find where you are adjusting the terrain of a flat world in preparation for rain to fall, with the goal of trapping the water.

EDIT: David Young put it in his answer. Wetrix is what I was thinking of.

Minecraft has water physics in a similar way that Dwarf Fortress does.

# Answer
> 4 votes
From Dust comes to mind, though not much information has been released. Similarly, Minecraft has a lot of complexity in its water system (see also: the invention of the waterladder).

# Answer
> 4 votes
It's not quite water, maybe better.

There is a flash game called "Creeper World" that has fantastic fluid dynamics.

It's more of a "Goo" than water, so it tends to spread out more slowly, but the dynamics are spot-on.

# Answer
> 4 votes
Super Mario Sunshine!

:P

# Answer
> 3 votes
I wonder how's nobody did mention the "Where's My Water?".

# Answer
> 2 votes
There was a great game for the Acorn Archimedes called Cataclysm - Video here \- which featured water leaking through a space ship. You had to capture enough water to avoid disaster...

# Answer
> 2 votes
Phun (2D physics sandbox game) allows you to play with water.

# Answer
> 2 votes
One game that doesn't seem to be mentioned yet: Pixeljunk Shooter

While its still 'only' 2D, the water physics are done pretty good and it's definitely a big part of the gameplay.

I guess the hardest part in using water/fluid as a major game mechanic is getting the simulation stable (just like every other physics based game, but with water it's a little harder). You really want to get the same results every time you re-run the simulation under the same conditions.

If you want to go 3D with this you might want to read the GPU Gems article about fluids.

# Answer
> 1 votes
Charles Bloom built a little game around fluids in the very first Indie Game Jam: http://www.indiegamejam.com/igj0/games.html#flow The goal was to manipulate the terrain to guide the fluid molecules to a goal area.

# Answer
> 1 votes
There's a puzzle game called Enigmo that uses water drops that you may want to check out. Basically you have to get water (or lava) from the source to the destination container using various contraptions to bounce, accelerate and slide the drops.

# Answer
> 1 votes
I heard a lot of traps and other mecanics in MineCraft does profit from water physics.

# Answer
> 1 votes
Fluidity/Hydroventure is a platform game for the Wii (and later - the 3DS) co-developed by Nintendo. You control a small body of water and move around by rotating the stage via the controller, to collect more water and manipulate the environment.

# Answer
> 0 votes
BioShock had several levels with pretty fancy water effects. Don't know how much that actually affected the gameplay, though.

# Answer
> 0 votes
Flood on the amgia had a water filling effect.

http://www.youtube.com/watch?v=8EbGjm\_x808

and

worse things happen at sea (don't be put by the graphics, this game was awesome fun!)

# Answer
> 0 votes
Sprinkle seems to be all about fluid/water dynamics.

# Answer
> 0 votes
There's a small open-source game called Sand Traps. It's about sand, not water, but the mechanics are rather similar. The game is for Wii homebrew, but maybe you can still learn something.

Here's the WiiBrew page (liks to source):
http://wiibrew.org/wiki/Sand\_Traps

And here's a gameplay video where you can see the code in action:
http://www.youtube.com/watch?v=RkqxoJV1tGM

# Answer
> 0 votes
Klooni Games Bloody Zombies, 'the goriest game ever made in the glorious 128 x 96 resolution!'

It tries to simulate dynamic flowing liquid. Which sometimes work quite well producing splashing waves. Other times the liquid behaves like a pile of sand.

---
Tags: game-design, game-mechanics
---


title: Drag an object in unity3d

text:
# Question
Title: Drag an object in unity3d
I want to drag an object to a perticular place.In case I release that dragged object before I reach that particular area ,the object should come to its initial place where i start to drag. How it possible? Is there any specific motion for this?

```
void OnMouseDown()
{

    drag = true;
    //Debug.Log("haii ");
}
  void OnMouseDrag()
{
    if(drag)
    {
        var pos =Input.mousePosition;
        pos.x =Mathf.Clamp(pos.x,0,Screen.width);
        pos.y =Mathf.Clamp(pos.y,0,Screen.height);
        if(zdist>0)
        {
     zdist=Vector3.Distance(Camera.main.transform.position,transform.position);
            pos.z=zdist;
            pos = Camera.main.ScreenToWorldPoint(pos);
            transform.position =pos;

        }
    }
}

```

# Answer
You can do this using plain mouseup/down tests and raycasting, and the same pattern applies to many other situations, like marquee selection.

```
// Call this inside an Update method.
void HandleDragging()
{
    const int mouseButton = 0; // button values are 0=left,1=right,2=middle
    if(_isDragging) // Leading underscore denotes private member variables
    {
        if(Input.GetMouseButton(mouseButton))
            UpdateDrag(); // Move your object according to Input.mousePosition
        if(Input.GetMouseButtonUp(mouseButton))
        {
            _isDragging = false;
            EndDrag(); // Set the object's position to its final destination
        }
    }
    else if (Input.GetMouseButtonDown(mouseButton))
    {
        // The bottom-left of the screen or window is at x:0, y:0
        var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        // This requires a Collider component on the draggable objects
        if (Physics.Raycast(ray, out hit))
        {
            // Here you can filter down the kind of objects/components
            //     I've used gameObject, but transform is what you'll
            //     modify to move the object around.
            var dragObject = hit.transform.gameObject;
            _isDragging = true;
            // Here you can capture the object being dragged,
            //     or create a phantom representing the destination
            //     until the drag is completed or cancelled.
            BeginDrag(dragObject);
        }
    }
}

```
> 2 votes

# Answer
When you start drag (OnMouseDown), save object position in some variable. Then OnMouseUp you can test that object is in position you needed else restore object position by saved variable.

UPD:

```
// Define some target to place object in. It can be any Collider
public Collider target;
// Variable for saving initial object position
private Vector3 initialPosition;

void OnMouseDown()
{
    drag = true;
    // saving initial object position
    initialPosition = transform.position;
    //Debug.Log("haii ");
}

void OnMouseDrag()
{
    if(drag)
    {
        DragMe();
    }
}

void OnMouseUp()
{
    // UPD2: missed some test if object are actually dragging now
    if(drag) {
        // Testing object and target collision
       if(TestObjectInPlace(target, transform))
        {
            // Place object in target position if they are colliding
            transform.position = position;
            // or you can call DragMe() to put object under mouse cursor
            // DragMe();
        } else {
            // Restore initial object position if object is not collide with target
            transform.position = initialPosition;
        }
        drag = false;
    }
}

void DragMe()
{
    var pos =Input.mousePosition;
    pos.x =Mathf.Clamp(pos.x,0,Screen.width);
    pos.y =Mathf.Clamp(pos.y,0,Screen.height);
    if(zdist>0)
    {
        zdist=Vector3.Distance(Camera.main.transform.position,transform.position);
        pos.z=zdist;
        pos = Camera.main.ScreenToWorldPoint(pos);
        transform.position =pos;
    }
}

bool TestObjectInPlace(Collider target, Transform obj)
{
    // I test some distance between object and target for demo
    // (I use distance less than 1 unit, but you can use any parameter of Collider
    // to test collision of target and object and if they are colliding return true
    // or false if not)
    return Vector3.Distance(target.transform.position, obj.position) < 1;
}

```
> 1 votes

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


title: AndEngine- OnAreaTouched

text:
# Question
Title: AndEngine- OnAreaTouched
In my AndEngine-based game there are a few sprites on the scene. One sprite acts as a surface and the rest of them are placed on top of this surface. I want to take unique actions whenever any of the these sprites is touched (the surface as well as the sprites on top of it). When I attach use registerTouchListerner for the surface sprite the Touch Listener does not work for any other sprite on top of it. Touching the sprites on top triggers the event, but it thinks that the surface sprite has been touched.

When I remove the touch listener from the surface it can successfully responds to touch event for the rest of the sprites on top.

So, does the AndEngine allow to attach OnAreaTouch listener to sprites on the top layer when the bottom layer sprite has already been attached to a touch listener?

(OnSceneTouched event cannot be used, as the 'surface' sprite only occupies bottom half of the screen and not the complete scene background)

# Answer
> 1 votes
To quote @Haider on his solution in comments:

> I got the solution. If you attach the surface sprite to the listener BEFORE attaching listener to the top sprites it doesn't work. I changed the code to attach listener to the top sprites FIRST and later to the surface sprite, things started to work fine.

So this sounds like a order of execution issue. If you're having a similar issue try organising your event listeners in an a different order.

A huge tip for anyone starting with events, especially those related to drawing, get a piece or paper and write out the layers of your scene from the furthest background right up to your foreground effects sprites and put them in order. This should be the order that you draw them in and the opposite order for how you interact with them (mouse click, touch screen etc.)

Good luck!

---
Tags: andengine, input
---


title: Ranking - which position to show?

text:
# Question
Title: Ranking - which position to show?
My company is making Android apps, mostly little games... Most of them have a view with the users profile and a view with a ranking list.

In the users profile you can see what rank the user is and of course you can see it in the ranking list. The ranking list shows ranks 1 - 100 and if the user is rank 35476 we are showing ranks 35466 to 35486 too, so whatever your rank, you are always in the ranking list.

Now my boss wants me to scroll the ranking list to the users position and I don't understand why you'd want this. You can see the rank in the profile and in my mind, when I go to the ranking list, I want to see the top guys and see how much points or whatever they have and I am not interested in seeing rank 35475 or 35477...this just doesn't make sense to me.

Is there some consensus on where to scroll the ranking list?

# Answer
Actually there are consequences to players whether you use one system or the other.

I quote

> However, it can be very de-motivational for those at the bottom or even not on the leaderboard at all.\[...\] try to solve this issue by showing a users position relative to others of a similar rank.\[...\] you are less aware of how far down the list you are!

The rationale is that absolute leaderboards can be demotivational to many players, seeing how impossible is for them to reach the top. On the other hand, if you show only the players right above/below them, they can get encouraged to overcome "that guy just right over me".

There are also several possible mixed solutions, beyond the basic just show both. One that I like particularly is using a relative leaderboard for the general player list, and an absolute leaderboard for your friend list. That way, you don't know your general position in all the game players, but you know that you are 5th in your friend list. This isn't as aggravating as your friend list usually is not that big, you can have a shot at the top position and it encourages competition between friends.
> 2 votes

---
Tags: ranking
---


# Question
Title: JBox2D Polygon Collisions Acting Strange
I have been playing around with JBox2D and Slick2D and made a little demo with a ground object, a box object, and two different polygons. The problem I am facing is that the collision-detection for the polygons seems to be off (see picture below), but the box's collision works fine.

My Code:

Main Class

```
package main;

import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.World;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;

import shapes.Box;
import shapes.Polygon;

public class State1 extends BasicGameState{
World world;
int velocityIterations;
int positionIterations;
float pixelsPerMeter;
int state;

Box ground;
Box box1;

Polygon poly1;
Polygon poly2;

Renderer renderer;

public State1(int state)
{
    this.state = state;
}

@Override
public void init(GameContainer gc, StateBasedGame game) throws SlickException
{
    velocityIterations = 10;
    positionIterations = 10;
    pixelsPerMeter = 1f;

    world = new World(new Vec2(0.f, -9.8f));

    renderer = new Renderer(gc, gc.getGraphics(), pixelsPerMeter, world);

    box1 = new Box(-100f, 200f, 40, 50, BodyType.DYNAMIC, world);
    ground = new Box(-14, -275, 50, 900, BodyType.STATIC, world);

    poly1 = new Polygon(50f, 10f, new Vec2[] {
            new Vec2(-6f, -14f),
            new Vec2(0f, -20f),
            new Vec2(6f, -14f),
            new Vec2(10f, 10f),
            new Vec2(-10f, 10f)
        }, BodyType.DYNAMIC, world);
    poly2 = new Polygon(0f, 10f, new Vec2[] {
            new Vec2(10f, 0f),
            new Vec2(20f, 0f),
            new Vec2(30f, 10f),
            new Vec2(30f, 20f),
            new Vec2(20f, 30f),
            new Vec2(10f, 30f),
            new Vec2(0f, 20f),
            new Vec2(0f, 10f)
        }, BodyType.DYNAMIC, world);
}

@Override
public void update(GameContainer gc, StateBasedGame game, int delta) throws SlickException
{
    world.step((float)delta / 180f, velocityIterations, positionIterations);
}

@Override
public void render(GameContainer gc, StateBasedGame game, Graphics g) throws SlickException
{
    renderer.render();
}

@Override
public int getID() {
    return this.state;
}

}

```

Polygon Class

```
package shapes;
import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.FixtureDef;
import org.jbox2d.dynamics.World;
import org.newdawn.slick.Color;

public class Polygon {
public float x, y;
public Color color;
public BodyType bodyType;
org.newdawn.slick.geom.Polygon poly;
BodyDef def;
PolygonShape ps;
FixtureDef fd;
Body body;
World world;
Vec2[] verts;

public Polygon(float x, float y, Vec2[] verts, BodyType bodyType, World world)
{
    this.verts = verts;
    this.x = x;
    this.y = y;
    this.bodyType = bodyType;
    this.world = world;
    init();
}

public void init()
{
    def = new BodyDef();
    def.type = bodyType;
    def.position.set(x, y);

    ps = new PolygonShape();
    ps.set(verts, verts.length);

    fd = new FixtureDef();
    fd.shape = ps;
    fd.density = 2.0f;
    fd.friction = 0.7f;
    fd.restitution = 0.5f;

    body = world.createBody(def);
    body.createFixture(fd);
}
}

```

Rendering Class

```
package main;

import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.collision.shapes.ShapeType;
import org.jbox2d.common.MathUtils;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.Fixture;
import org.jbox2d.dynamics.World;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.geom.Polygon;
import org.newdawn.slick.geom.Transform;

public class Renderer {

World world;
float pixelsPerMeter;
GameContainer gc;
Graphics g;

public Renderer(GameContainer gc, Graphics g, float ppm, World world)
{
    this.world = world;
    this.pixelsPerMeter = ppm;
    this.g = g;
    this.gc = gc;
}

public void render()
{
    Body current = world.getBodyList();
    Vec2 center = current.getLocalCenter();
    while(current != null)
    {
        Vec2 pos = current.getPosition();
        g.pushTransform();
        g.translate(pos.x * pixelsPerMeter + (0.5f * gc.getWidth()),
                   -pos.y * pixelsPerMeter + (0.5f * gc.getHeight()));
        Fixture f = current.getFixtureList();
        while(f != null)
        {
            ShapeType type = f.getType();
            g.setColor(getColor(current));
            switch(type)
            {
                case POLYGON:
                {
                    PolygonShape shape = (PolygonShape)f.getShape();
                    Vec2[] verts = shape.getVertices();
                    int count = shape.getVertexCount();
                    Polygon p = new Polygon();
                    for(int i = 0; i < count; i++)
                    {
                        p.addPoint(verts[i].x, verts[i].y);
                    }
                    p.setCenterX(center.x);
                    p.setCenterY(center.y);
                    p = (Polygon)p.transform(Transform.createRotateTransform(current.getAngle() + MathUtils.PI, center.x, center.y));
                    p = (Polygon)p.transform(Transform.createScaleTransform(pixelsPerMeter, pixelsPerMeter));
                    g.draw(p);
                    break;
                }
                case CIRCLE:
                {
                    f.getShape();
                }
                default:
            }

            f = f.getNext();
        }
        g.popTransform();
        current = current.getNext();
    }
}

public Color getColor(Body b)
{
    Color c = new Color(1f, 1f, 1f);
    switch(b.m_type)
    {
    case DYNAMIC:
        if(b.isActive())
        {
            c = new Color(255, 123, 0);
        }
        else
        {
            c = new Color(99, 99, 99);
        }
        break;
    case KINEMATIC:
        break;
    case STATIC:
        c = new Color(111, 111, 111);
        break;
    default:
        break;

    }
    return c;
}
}

```

Any help with fixing the collisions would be greatly appreciated, and if you need any other code snippets I would be happy to provide them.

# Answer
As per Andy's comment:

> Nevermind, I fixed it. I just had to take out the
>
> `p.setCenterX(center.x);p.setCenterY(center.y);`
>
> out of the render function.
> 1 votes

---
Tags: java, collision-detection, box2d, jbox2d
---


title: change texture at runtime

text:
# Question
Title: change texture at runtime
How can I change the texture at runtime. I have done changing the label(text) at runtime. The following code is used

```
using UnityEngine;
using System.Collections;

public class switchtime : MonoBehaviour {

    // Use this for initialization
    private bool showLabel = false;
    private bool showLabe2 = false;
    private bool showLabe3 = false;
    private bool showLabe4 = false;

    public void Start() {
        Invoke("ToggleLabel", 1);
        Invoke("ToggleLabel2", 3);
        Invoke("ToggleLabel3",6 );
        Invoke("ToggleLabel4", 9);
    }

    public void ToggleLabel() {
        showLabel = !showLabel;

    }
    public void ToggleLabel2() {

        showLabe2 = !showLabe2;
    }
    public void ToggleLabel3() {

        showLabe3 = !showLabe3;
    }
    public void ToggleLabel4() {

        showLabe4 = !showLabe4;
    }

    public void OnGUI() {
        if (showLabel) {
            GUI.Label(new Rect(300, 200, 100, 20), "Copying window file..");

        }
        if (showLabe2) {

            GUI.Label(new Rect(40, 40, 100, 20), "Epanding windows file..");
        }
        if (showLabe3) {

            GUI.Label(new Rect(80, 80, 100, 20), "Installing Feature..");
        }
        if (showLabe4) {

            GUI.Label(new Rect(100, 100, 100, 20), "Installing Updates");
        }
    }
}

```

Now I need to change the GUITexture at runtime. How can do this? Can anybody help me in coding?

Here is some changes I made. I worked on changing the gameObject when mouse is placed on it. This is the code I applied and its working for me

```
using UnityEngine;
using System.Collections;

public class change : MonoBehaviour {

    // Use this for initialization
    public GameObject newSprite;

    private Vector3 currentSpritePosition;
    void update()
    {
    }

    void Start()
    {
        newSprite.renderer.enabled = false;
        currentSpritePosition = transform.position;

        //then make it invisible
        renderer.enabled = false;

        //give the new sprite the position of the latter
        newSprite.transform.position = currentSpritePosition;

        //then make it visible
        newSprite.renderer.enabled = true;
    }

    void OnMouseExit(){
        //just the reverse process
        renderer.enabled = true;
        newSprite.renderer.enabled = false;
    }
}

```

Now the problem is that, in same code I need to set a time so that the text get loaded without the mouse click. I mean a particular time to load each text one after the another.

Here is my screen shot

Here I have placed the image one below the another,when the mouse is hovered on it it will change the text from bold to normal text.Changes process stated in (image 2,3).That code I posted is working for me.

# Answer
> 1 votes
You can load resources from a folder called "Resources" using this:

```
Texture texture = Resources.Load(textureName);
guiTexture.texture = texture;

```

Nice and simple. If you want to find a particular texture using a named reference you can use:

```
Texture texture = Resources.Load(textureName);
GameObject.Find("NameRef").guiTexture.texture = texture;

```

You can even shorthand it to:

```
GameObject.Find("NameRef").guiTexture.texture
    = Resources.Load(textureName, typeof(Texture));

```

EDIT:

You can also apply this to an attached texture:

```
using UnityEngine;
using System.Collections;

public class switchtime : MonoBehaviour {

    public GUITexture myGuiTexture;

    public void OnGUI()
    {
        // Blah blah do other stuff

        ApplyMyTexture();
    }

    public void ApplyMyTexture()
    {
        myGuiTexture.texture
            = Resources.Load(textureName, typeof(Texture));
    }
}

```

You can change the function names to suit your usage.

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


# Question
Title: Palette reduction to pre-defined palette
I'm writing a bunch of GLSL effects for fun, but I can't wrap my head around this. Basically, I want to reduce a texture's palette into a pre-defined set of colors. For example, a post-processing shader would take the FBO result texture and a 1D / 2D texture that would contain the reduced palette (say, 64 colors), and the output would then be sampled based on these.

Something like this in its core:

```
sampler2D source;
sampler2D palette;

vec4 source = texture2D(...); // Source texture to sample
vec4 palette = texture2D(...); // Palette

vec3 result = /* color from the source converted to the closest value available in palette */;

```

Any ideas how to do this? And to be more precise, I don't mean palette swapping - the source texture is full-colored result, and this shader would ultimately be a post-processing shader, reducing the amount of colors to the ones that are predefined in the palette texture.

# Answer
> 6 votes
Another way to do this is to make a texture that maps each RGB to a colour on the palette, an image like this (from the NES colours):

Then in a post processing shader you can the RGB colour from your regular image in a way like this:

```
uniform sampler2d paletteMapping;

vec3 mapColor( vec3 realColor ) {
    vec3 mappedColors = floor( realColor * 16 );
    int mappedI = mappedColors.r + mappedColors.g * 16 + mappedColors.b * 16 * 16;

    return texture2D( paletteMapping, floor( vec2( mappedI / 64, mod( mappedI, 64 ) ) );
}

```

I've not tested the shader as I'm at work, but this should work on a texture that has interpolation disabled (i.e. it uses nearest neighbour sampling).

The map image I created with a little tool I wrote, from the NES palette image on wikipedia

# Answer
> 0 votes
This problem is called Color quantization. Basically for each pixel you want to find a closest color present in the palette. This can be done by partitioning the 3D color space into regions each of which containing exactly one palette color. The partitioning can be performed using e.g. Voronoi diagram, octree or any other spatial partitioning data structure. Then, for each pixel, a point location problem has to be solved, i.e. the region containing the pixel color has to be found. In case of octrees this can be done efficiently in a straightforward way. The unique palette color in the region will replace the original pixel color.

Because this process is computationally intensive, you should perform as many steps offline in a preprocessing step (e.g. in your asset pipeline) as possible.

Performing the entire quantization step on your textures offline is the easiest way. ImageMagick can perform this via the `-remap` option. ImageMagick can also perform dithering automatically, which improves the visual quality of quantized images.

If you want to apply a palette to your rendered scene while using your original textures, but the palette is fixed, the color space partitioning can still be done offline. E.g. you can build an octree using the palette colors, transfer the tree to the GPU, and use it in the shader to perform the quantization. ImageMagick uses this approach (on the CPU), the algorithm is described in the source code.

If you want to be able to switch between palettes, the partitioning has to be done on-the-fly, but reasonably on the CPU.

---
Tags: opengl, shaders, color, palette
---


# Question
Title: Transform coordinates in vertex shader or in geometry shader?
Currently I have a vertex shader which just passes the coordinates to the geometry shader and a geometry shader which does some sort of tessellation. Now I also want to transform my model with a 4x4 matrix before applying the tessellation.

I could apply the transformation either at the end of my vertex shader or in the beginning of my geometry shader.

Does that make any difference? Is there a recommended practice?

# Answer
> 2 votes
"Do as little work in the GS as is reasonable. The GS happens after the post-T&L cache, and you want to get as much out of that as possible. So do as much of your real transformation work as is reasonable in the vertex shader." (Source)

In addition vertex shaders are always run on all vertices and if no vertex modification or transformation is required, a pass-through vertex shader must be created and set to the pipeline. So why not use it as well? Vertex shader is meant for performing per-vertex operations such as transformations, skinning, morphing, and per-vertex lighting.

# Answer
> 1 votes
As per common practices, transformations from local object space to homogeneous clip space occur in the **vertex shader** while things which include manipulating the geometry data of an object as a whole happen in the **geometry shader** (like tesselation and particle effects).

The vertex shader can handle only one vertex at a time. Thus it makes sense to do transformations in this shader, as transformation is a *per vertex* operation. The geometry shader on the other hand can "see" more of the vertices of the mesh bieng rendered, so things which use this fact are done in the geometry shader.

---
Tags: hlsl
---


# Question
Title: Is it possible to create 3d games with good performance in java?
Recently i use Javafx 8 for creating small 2D games , but i think it can't manage memory and other things very well .I see Jmonkey jmonkeyengine as a game engine for Java and i see some videos of their project in YouTube. Now i want to know it is possible to create a good game with good performance and graphic with Jmonkey or other game engines writtent in java? Is it possible to deal with GPU buffers in Java?

# Answer
> 1 votes
Java is a bit slower then c++ however this effect is less then people tend to think. There are several points on which it matters:

1 Calls towards openGL will have to take another extra step this means that if you make many calls towards openGL you pay a small penalty (not that large but it's there).

2 You don't control the garbage collector that means that you will sometimes seem to miss one frame, this isn't that bad but can screw up your game in a multiplayer environment especially when using a lock-step approach for resolving concurancy issues (for example in a rts).

3 You cannot do a clear memory and then rewrhite step approach for example in c++ you might decide to first clear the old map then write a new one in the same memory, if you are using almost all memory this will cause problems, note that you can almost always navitage around this by instead of "destroy and recreate" you can often just rewrite the object instead.

4 Often c++ programers are better used towards performance based programming, well focus on performance and this won't be a problem.

If you want to know about fps take a look at for example minecraft and you will see you can get some reasonble performance in java (note minecraft could be optimised a lot more).

# Answer
> 1 votes
Let me get this straight: render performance is in (almost) no way related to the programming language, but to the **graphics API used** (Ex: OpenGL, DirectX, software, etc.) The programming language used is only an interface to these APIs and will not affect graphics performance.

What the language will have an impact on is the arithmetics. If you want to do a lot of calculation, then you will need to chose a fast language like C or C++. If you only need to do graphics, then any language will do (hell, even Brainfuck for what I care.)

---
Tags: java, performance
---


title: Fullscreen FPS slowdown in Linux

text:
# Question
Title: Fullscreen FPS slowdown in Linux
I've got a homemade game engine that supports both Windows and Linux using Win32 and Xlib, respectively. By default, the engine will create the window and then switch it into fullscreen mode. When running in Linux, the main game loop updates with a very low framerate (2-7 FPS) that slowly keeps ticking downwards. If I alt-tab out and then alt-tab back in, the game will shoot up to and stay at a consistent 60 FPS.

Since my time since last tick (dt) keeps increasing during this time, my thought is it has something to do with the game not being properly registered as "fullscreen" when it's initially opened, leading the CPU scheduler to not give it full priority. That being said, that's entirely speculation. Does anyone have any idea what the cause of this could be? I can provide code samples if requested.

System info:
Linux Mint 17 Cinnamon 64-bit
Intel Core i7 @ 3.40GHz x 4
8GB DDR3 RAM
Nvidia GeForce GTX 680 with proprietary driver

**Edit**
My update loop is as follows:

```
while (gameIsRunning) {
    auto currentTime = std::chrono::steady_clock::now();
    auto dt = std::chrono::duration<float>{currentTime - lastFrame};
    if (dt >= engine->getFrameInterval()) { // getFrameInterval returns (1 / the target framerate) in seconds; in this case, 1/60s
        if (dt >= engine->getFrameInterval() * 2) {
            lastFrame = currentTime;
        } else {
            lastFrame += std::chrono::duration_cast<decltype(currentTime - lastFrame)>(engine->getFrameInterval());
        }

        // input, update, draw...
    }
}

```

After fooling around with it a bit, this creates a situation where the framerate will jump back up to 60FPS, tick down until it hits about 30FPS, and then jump back up to near 60FPS before ticking down again.

# Answer
"that slowly keeps ticking downwards" - this is your bottleneck. When doing a game engine with a standard update and render loop, you have to be careful that the update does not take too much performance, or else you will enter in a bottleneck. From what I can understand, your update loop looks a bit like this one:

```
dt += (timeNow - timeThen) * FPS / 1000; // In miliseconds
while (dt >= 1) {
    // Update stuff
    dt -= 1;
}

```

If you are doing something like this and dt starts getting out of hand (that is, higher than 10), you want to have some sort of mechanism to stop that. The simplest one is to change the line

```
dt -= 1;

```

by

```
dt = 0;

```

This will fix all problems but will be less accurate (though the accuracy loss is not significant). Another option is to add this after this line:

```
dt -= 1;
if (dt > 4) {
    dt = 0
}

```

This will add a check whether or not the loop is going out of control and will bottleneck the entire engine.
> 1 votes

---
Tags: frame-rate, linux, c++
---


title: Regeneration using Time.deltaTime

text:
# Question
Title: Regeneration using Time.deltaTime
I'm trying to regenerate stamina at a rate of 1 per second using Time.deltaTime, however this doesn't do anything (My 'current stamina' doesn't change at all). I've done some looking around and I have tried Time.fixedDeltaTime. Also tried Time.time, but that just regenerated all my stamina in under a second.

Here is my code:

```
var max_stamina : int = 100;
var cur_stamina : int;
var staminaRegenRate : int = 1;

function Update(){
    //regen
    if(cur_stamina < max_stamina){
        cur_stamina += staminaRegenRate * Time.deltaTime;
        Debug.Log("Second has passed");
    }
}

```

What am I doing wrong?

# Answer
> 4 votes
I guess since you are declaring the variables as integer, when you do `cur_stamina += staminaRegenRate * Time.deltaTime;` it is rounded to the nearest integer, effectively not changing its value.

Declare them as floats or doubles (and be more careful with data types!).

---
Tags: javascript
---


# Question
Title: If I convert my LibGDX game to an exe, is it legal?
I have a LibGDX jar file, and I want to have it as an EXE. Would that be legal? (Using launch4j)

Also, how do I obfuscate a LibGDX game?

# Answer
Sure, why wouldn't it? As stated on BadLogicGaming's Official Website:

> The license basically states you can do with the source whatever you want, copy it, modify it, include it in open and closed source projects without getting infected by the license itself.

You can do whatever you want with what you made. Just make sure you comply to these 3 lines **if you ever modify the source code if LibGDX**:

> * include the license file in your project
> * retain all copyright notices of my (modified) source files
> * if you chose to contribute your contribution will the Apache 2.0 licensed to

Source: http://www.badlogicgames.com/wordpress/?p=777

As of your second question, here is a site that lists Java obfuscators:

http://java-source.net/open-source/obfuscators

ProGuard seems like the best choice.

Source: https://stackoverflow.com/questions/2537568/best-java-obfuscator
> 2 votes

---
Tags: java, libgdx
---


title: Character bounces/stutters down hills

text:
# Question
Title: Character bounces/stutters down hills
I'm using Unity3D (not 4) and I'm experiencing a bit of a problem with character movement. I'm using a capsule as a First Person player with a camera attached to it. In this capsule is the stock ThirdPersonController script (with the animation parts removed). I know it's not conventional, but it's not the problem in this case.

The problem is when my character goes down hills, running or walking, it bounces down. It's as if it's going horizontally, then realising it's not grounded and then falling. It works fine going uphill but the downhill is driving me crazy.

One solution that may be possible is raycasting, I know what it is but I have no clue on how to use it.

# Answer
So I figured it out by myself (gee thanks a lot, downvoter) I looked inside my ThirdPersonController script and took a look around once more. I found this:

```
function ApplyGravity ()
{
    if (isControllable) // don't move player at all if not controllable.
    {
        // Apply gravity
        var jumpButton = Input.GetButton("Jump");

        // When we reach the apex of the jump we send out a message
        if (jumping && !jumpingReachedApex && verticalSpeed <= 0.0)
        {
            jumpingReachedApex = true;
            SendMessage("DidJumpReachApex", SendMessageOptions.DontRequireReceiver);
        }

        if (IsGrounded ())
            verticalSpeed = 0.0;
        else
            verticalSpeed -= gravity * Time.deltaTime;
    }
}

```

The key bit is `verticalSpeed = 0.0;`. In context, that meant "If player is touching the ground, set it's vertical velocity to 0.

What I did to solve my stuttering problem was change that value to `-10.0`. Now I have a character that smoothly traverses hills!
> 0 votes

# Answer
I would suggest **not** setting your vertical speed to -10 as this is essentially doubling the effect of gravity which can have some serious adverse effects later on.

I would replace the collider with a spherical based one on your character:

This should help smooth out collisions and contact with the ground as opposed to a square based collider which will have the sharp edge to "bounce down" hills.

*Image courtesy of iPhone & Mac Development Blog*
> 0 votes

---
Tags: unity, physics, javascript
---


# Question
Title: How can I create a game in RMVX without battle scenes?
I want to create a story-like game which depends on situations based on your decisions. I don't want to have "battle scenes" in my game; can I disregard the EXP/HP stuffs to create my own game?

# Answer
> -2 votes
Yes you can, although you will need ruby scripting to achieve that kind of modification.
Probably the are some community resources you could use to achieve it. Check here.
Also in the same forum I found this.

# Answer
> 0 votes
Yes, you can. I have made a few games like this; you may even be surprised to learn that RPG Maker can be used to make non-RPG games; see this blog post on the RPG Maker blog.

Games people have made include:

* Horror
* Adventure
* Interactive fiction
* Shooters

It's really up to you whether you use (or don't use) aspects of the game.

Also, due to the (insane) level of customization, you can also get away with things like disabling/removing menu items (if they're not used for your game).

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


# Question
Title: How can I determine whether a unit is in range or not?
I'm programming a small game that's going to be somewhat like a tower defence. I was playing around with how I determin whether a unit is in range or not.

```
public void Update(GameTime theGameTime)
    {
        Timer -= theGameTime.ElapsedGameTime.TotalSeconds;

        if (Timer < 0)
        {
            bool CreateNew = true;
            foreach (Unit theUnit in Lists.ennemyUnits)
            {
                if (Math.Pow(Math.Sqrt(Vector2.Distance(Location, theUnit.Location)),2) < 999);
                {
                    foreach (Arrow theArrow in Quiver)
                    {
                        if(theArrow.visible == false)
                        {
                            CreateNew = false;

                            theArrow.shootProjectile(Location, theUnit.Location);

                            Timer = 3;
                            break;
                        }

                    }

                    if (CreateNew == true)
                    {
                        Arrow theArrow = new Arrow();
                        Quiver.Add(theArrow);

                        Timer = 3;

                        theArrow.shootProjectile(Location, theUnit.Location);
                    }
                }
            }
        }

```

I'm running into a problem with this, when the location of my archer in Y is higher or the X is lower the archer doesn't shoot the enemy unit. I do not understand why?

# Answer
> 0 votes
You can use only the distance, without use the sqrt and the Pow because the distance is usually calculate with this formula:

```
float dist(vector3d v1, v2)
{
    v.x = v1.x - v2.x;
    v.y = v1.y - v2.y;
    v.z = v1.z - v2.z;
    return sqrt(v.x*v.x + v.y*v.y + v.z*v.z);
}

```

as you can see here.

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


# Question
Title: Binary Serialization of C# for GameObject in Unity?
I'm trying to serialize a **GameObject** (with children and textures) using the binary serialization for C#.

It works with many data types but not with **GameObject**. In the docs it says should be serializable (http://docs.unity3d.com/ScriptReference/SerializeField.html):

> Serializable types are: \- All classes inheriting from UnityEngine.Object, for example GameObject ....

I've read suggestions of using the asset of UnitySerialization, but that is overkill for me, I just need to store a **GameObject** on my scene (that will be generated by many users) and load them all in another scene.

This is the code (I'm following this tutorial: http://www.youtube.com/watch?v=J6FfcJpbPXE&feature=player\_embedded)

```
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public class GameControl : MonoBehaviour {

    public static GameControl control;

    public GameObject drawing;
    public string drawName;

    void Awake () {
        if (control == null)
        {
            DontDestroyOnLoad(gameObject);
            control = this;
        }
        else if (control != this)
        {
            Destroy(gameObject);
        }
    }

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }

    public void Save ()
    {
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create(Application.persistentDataPath + "/drawing.drawli");

        UserDraw data = new UserDraw();
        data.drawing = drawing;

        bf.Serialize(file, data);
        file.Close();
    }

    public void Load()
    {
        if (File.Exists(Application.persistentDataPath + "/drawing.draw"))
        {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath + "/drawing.draw", FileMode.Open);
            UserDraw data = (UserDraw)bf.Deserialize(file);
            file.Close();

            drawing = data.drawing;
        }
    }

}

[System.Serializable]
class UserDraw
{
    public GameObject drawing;
}

```

Check the Save/Load functions. I'm just trying to store the "drawing" (GamObject), save it and load it. That's all! Is very simple. With other data types it works. But not with **GameObject**.

This is the (execution) error:

*SerializationException: Type UnityEngine.GameObject is not marked as Serializable.*

# Answer
> 3 votes
> SerializationException: Type UnityEngine.GameObject is not marked as Serializable.

That means `UnityEngine.GameObject` is not marked with the `Serializable` attribute, which is a requirement (just because Unity says a type is serializable doesn't mean it's serializable with *all* serialization engines; in this case, it probably means that the type is serializable with Unity's engine, not the one that is part of the .NET BCL).

You can either use Unity's serialization mechanism, or you can try your hand at implementing an `ISerializableSurrogate` object for the Unity game object (this is likely to be tricky, and more effort than just using Unity's serialization).

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


title: AI, Pathfinding - Searching Behavior

text:
# Question
Title: AI, Pathfinding - Searching Behavior
I'm developing a top-down 2D game mostly based off a tilemap/grid. The player will be able to build structures on this grid while other objects like vehicles will move around freely. I've been working on the AI for awhile and have struggled with coming up with a searching method.

The basic behavior I'm looking for is that of a dog barking at someone inside a house. When the person inside runs to the left out of view, the dog will run left and could very well run around the whole house trying to reach/see the person.

Standard pathfinding algorithms look for shortest paths or near shortest paths. But the behavior I'm looking for is more dynamic and isn't about finding a path as much as searching for a way in.

The example I'm working with currently, as seen below, depicts a zombie that has sight of a player inside a building through a window. The player then moves to the right out of view. The desired effect would be that the zombie runs to the right and all the way around the building until finding the player again or giving up. Note that I don't want the zombie to go left and in through the door (which would be the shortest path) to reach the player.

I've fiddled with ideas about using steering behavior, weighted tiles based on distance, wall-following, etc. and nothing has really made sense yet. I'm looking for any thoughts on ways to go about this kind of behavior driven searching.

# Answer
> 8 votes
**Complete vs. incomplete information**

What you are looking to do is path finding without complete information. The conceptually sound way to do this would require you to keep track of all of your non-playing character's information state (i.e., the parts of the map they already have discovered).

**Local information**

A more workable solution in your case might be to have complete information path finding (as you do now) for human-like enemies, and use local information (a type of incomplete information) to perform path finding for creatures of lower intelligence.

You could do this, for example, by only considering obstacles within 5 tiles of the creature and assuming all other tiles are passable. Your example above would like this to the path finding algorithm:

Because every NPC has to re-path anyway when it finds it is executing an invalid path this should result in the behavior you are looking for. So when the zombie realizes at the top right corner there's a wall in its path you'll feed this new bit of local information to the algorithm:

**Oscillation**

Looking at that last picture I realize this might lead to oscillatory behaviour, as re-pathing in general may do. This can be resolved by keeping track of where the NPC has been and assign those tiles a higher weight when re-pathing.

Specifically for the solution suggested in this answer, you could also:

* have the creature keep track of one or more earlier path finding iterations' information states, or
* allow it local information around the path it has recently walked instead of only its current location.

---
Tags: ai, path-finding, tilemap, grid
---


title: Blood particles system,join particles

text:
# Question
Title: Blood particles system,join particles
Does anyone know how the particles behave in the following picture?

Let me explain,before the particles join they seem to be just simple textures of blood drops with a **black border** around them ,when they start to overlap the border disappears giving the illusion that its all one single blood drop.Is this some kind of shader?

# Answer
> 3 votes
This effect can be achieved by drawing the blood in two layers. The bottom layer is the black border and the top layer is the red blood. Note that actual "layers" are not required, as long as the drops can draw in two phases, all black, followed by all red.

Each droplet draws its shape as a black sprite. Then after all black shapes are drawn, they each draw a red shape *which is smaller around the edges by 1-2 pixels*. If the shapes are circles, then this means scaling by 1-2 pixels in width and height. For non-circular shapes, you can just have two sprites, one smaller than the other. This can be achieved via the "Inset" command in GIMP or Photoshop.

This achieves the desired effect because every part of the black shape is covered up by the red shapes, except around the edges where the red shapes aren't quite big enough. In interior regions where there are many blood particles, the black is hidden entirely.

No shaders are necessary, although they would be if you want it to be lit properly as if the blood was 3 dimensional.

# Answer
> 1 votes
If you look closer - it is not border of(each) blood drops - it is a border of all blood-red area. And I think the border was added actually after rendering blood to look cartoonish. This could be post processing effect just as well as shader. It should not be difficult to implement edge-detection algorithm (plus you know the color you are looking for).

---
Tags: textures, shaders, particles
---


title: Listen for asset modification in editor

text:
# Question
Title: Listen for asset modification in editor
I would like to listen for an event that some asset (prefab, precisely) has been modified. To my surprise, there's no such event in `AssetModificationProcessor`.

Is there any way to do this in Unity?

# Answer
> 1 votes
You can make use of the AssetPostProcessor to post-process your assets in Unity Editor.

Here is an extract of the code I used in a project before.

```
using UnityEditor;
using UnityEngine;
using System.Collections;

public class MyPostProcessor : AssetPostprocessor {
    public delegate void PostProcessAsset();
    public static event PostProcessAsset PostProcessAssetHandler;

    public static void OnPostprocessAllAssets(
        string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) {
        if (PostProcessAssetHandler != null) {
            PostProcessAssetHandler();
        }
    }
}

```

Register any functions you want to execute to the event `PostProcessAsset`.

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


title: Ethical F2P monetisation methods

text:
# Question
Title: Ethical F2P monetisation methods
I am just starting out in indie game development and one thing that seems clear to me is that in the mobile space at least, unless you are already a famous developer, have a well known brand/franchise or are just plain lucky, then you need to price your game at zero to stand any chance of being installed on devices. So to make money you must use Free to play (F2P) monetisation methods. In my own experience with myself and my kids plus reading around on the Web a lot of these methods are not appreciated by the players...

My questions is: Which F2P methods do players find ethical and acceptable?

I am looking for specific game mechanics and an answer which references or is based on data/research (if there is any) and not personal opinions or anecdotal references to successful, money making F2P games like Candy Crush Saga or Clash of Clans etc.

# Answer
As in many of these things, there is very little formal research as far as I know, most of them comes from the Gamification community. On this course lecture 7.1, they discuss monetization in games. Here is an screenshot with relevant information, in case you don't want to check the video.

So there are some guidelines but they are mainly "opinion-based", and the only thing you can trust about them is that some people has used them and proved their validity before.

Some key points would be:

* **Everything that can be purchased can also be obtained for free** in the game (paying is just a shortcut).
    + Exception to this rule are aesthetic items. These are items which provide no functionality but just make the player "look pretty". Since they provide no advantage whatsoever, it doesn't create any imbalance or unfairness in the game.
* **The best items available in game, are not obtained by money**. This prevents paying customers from automatically becoming the best players (they need to AT LEAST invest some effort).
* **First make a good game AND THEN add in-game purchases**. If you design your game around purchases, chances are it will become a pay-to-win unplayable mess.

Now, with my personal-anecdotal evidence. I have played many such games, and many of them fail in one or more of these points. The consequences are the following:

* When there are items that can only be bought, you are automatically creating a differentiation between free and paying customers. Most likely this will mean an **unfair advantage to paying customers**, and therefore will drive free customers away. The good point is that people willing to pay will be more loyal, as they will keep paying to keep the advantage, but you will lose a large player base of possible customers.
* When the best items can be purchased, you are **killing endgame**. If I can just pay my way to the top, chances are I will become bored of the game very fast. Combine this with the previous point and you have a combo of death where you are losing both free and paying customers.
* When games are designed bottom up to provide in-app purchased, the result usually is an insultingly unplayable mess. The game is practically to force players to spend money just to turn an awful game in a mediocre game. Such practices include **disproportional difficulty curve, gameplay limitations, penalties to non-paying customers or endless grinding**. The result usually is that free customers are driven away before they have a chance to consider paying. Usually paying customers do not start buying right away, first they get hooked to the game. If you don't give them even a chance, probably they won't.

So some in-game purchases practices which seem acceptable in my opinion are the following.

* **Premium currency**. Players can buy this currency to buy items in game. However make sure that any item that can be purchased this way, can also be purchased with regular currency.
* **Grinding shortcut**. Lets say you have a tech tree that you unlock as you complete missions. Customers could just pay to unlock it right away and save hours of grinding. However make sure that the time saved is balanced and fair for free players. If I need hundreds upon hundreds of hours to achieve something that cost a few bucks, I will feel that you are practically forcing me to pay.
* **Limitation extender**. This one I hate personally, but people seem to love it. The point is to limit the actions a player can do in a certain amount of time (for instance, each day), usually implemented with "action points". Then, players can buy extra action points for a fee, and then progress further than free customers. However, mind to put also a hard cap on how much a paying customer can advance using this system in order to avoid unfair advantage.
* Generally speaking, **reward paying customer instead of penalizing free customers**. An example of the later is implementing a death penalty where you lose some exp each time you die, and then ad a paying item that removes this penalty. That way feels that you are bashing me for not paying. Instead, add items that provide exp boosts. That way, I will feel that you are rewarding me for paying.

This is everything I can think of from the top of my head. I hope it is useful.
> 4 votes

# Answer
As a simple user, I quit any single game that pops up big screens begging for money (at the end of level, where the offers is actually bigger then my score). And every multiplayer game that offers boosts as unfair advantage.
A bit of explanation: the game made some advance since F2P became popular. As the players did - most are allergic to the early kind of F2P (farmville, RoM, and the most infamous mobile Dungeon Keeper).
As somebody interested in these questions, I found most satisfying answer: "it depends". It depends on platform, country, age etc.. **To sell well you must know your target audience.** And there is no general answer beyond that.
Also there is another question: do I need money more or good reputation? It might be worth to release a game that doesnt make nearly any money just to build a trademark (...and cash it later ofcourse). But that mostly depends on your current situation.
> 0 votes

# Answer
As a mobile gamer, I can say (personally) that some in-game adds don't bother me at all. For example: the game Jupiter Jump by Noodlecake Studios only shows ads after the first attempt (full screen) as well as at the main menu along the top. I think this is well-executed, as it doesn't overload the player after every attempt. Vector, by Nikku, is a little encumbering. After every attempt (roughly every minute) a full-screen ad is displayed. This not only annoys the player, but abruptly interrupts the flow and plot of the game.

Placing your ads away from the main focus of the screen creates far less stress for the user, and carefully managing the frequency at which you display ads can also keep your players engaged and entertained while unknowingly supporting the developer.

One thing to avoid at all costs is "pay $2 to get 50 coins!" If the user downloaded the game for free, odds are that he or she will steer clear of paying for anything, unless they become obsessed with the game (Candy Crush Saga). Also avoid using "sign up for Dish to receive 1000 XP" sort of deals. It's completely irrelevant to the user, and encouraging the user to sling his or her credit card information at one random company or another is borderline immoral.
> -3 votes

---
Tags: game-design, monetization, free-to-play
---


# Question
Title: what is the simplest way to get player selection system like checkers in unity 3d c#
like lets say the board is a top down grid like if your were in front of an actual checkers board i want to figure out how i would be able to select/deselect a piece then select/deselect a space on the board so that the players piece will move to said place and if another piece is occupying that place already then the said player cant move there

also im new to c# and progrming in general...i have been only doing it for about five months and have been looking at tutorials and all that ... but if some one could paste an example code if possible something simple so that i can dissect it, learn from it, and change it as I see fit.

and if you can explain how the code works that would be really appreciated.

things i need: some kind of grid/checker board code player selection/deselection

i would prefer it in c# and the code applicable strictly to unity3ds mono develop although I intend to learn visual studio in the future at the moment i just want something for unity.

lastly please assume that i may be stupid when explaining/writing your example code/ or answer.

# Answer
To begin with, in order to access and update your board with ease, you can make use of the `Dictionary<Key, Value>` class together with the `Vector2` structure defined by Unity.

```
Dictionary<Vector2, Tile> tiles = new Dictionary<Vector2, Tile>();

```

`Tile` is a class defined by you. It should contain information such as its coordinates on the board, and whether it is occupied by any entity etc. You can define a simple `Tile` class as follows.

```
using UnityEngine;
using System.Collections;

public class Tile : MonoBehaviour {
    public Vector2 coordinates;
    public ChessPiece chessPiece;

    // add other fields as you want to
}

```

Now, let's wrap things up by a `Board` class.

```
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Board : MonoBehaviour {
    public Dictionary<Vector2, Tile> tiles = new Dictionary<Vector2, Tile>();

    // add other functions later
}

```

Of course, you need chess pieces to play with.

```
using UnityEngine;
using System.Collections;

[RequireComponent(typeof(BoxCollider))]
public class ChessPiece : MonoBehaviour {
    // add other functions later
}

```

The management of the board should be centralized with the presence of a "Manager". This "Manager" is in charge of handling the transition of states of the board. Again, this "Manager" should be implemented by yourself.

```
using UnityEngine;
using System.Collections;

public class BoardManager : MonoBehaviour {
    public Board board;

    void Awake() {
        GameObject boardObject = new GameObject("board");
        boardObject.transform.parent = transform;
        board = boardObject.AddComponent<Board>();
    }

    // add other functions later
}

```

Colliders are often used by different physics-related functionalities. For instance, in a game of chess, each chess piece should have a collider attached to it. The collider, in this case, is mainly used for receiving user input, such as tapping and dragging. There are many excellent plugins available in the Unity Asset Store for handling different kinds of user input/gestures. By using these plugins, you are being freed from handling those tedious input-related logic. For example, there is certain plugin which allows to write functions like this.

```
// a function for handling 'tapping' on a chess piece
void OnTap(Gesture gesture) {
    if (gesture.pickObject == gameObject) {
        // process 'tapping' on this chess piece...
    }
}

```

Of course, the code snippet above covers only the basic usage of these plugins. You should refer to the official manuals provided by the authors of those plugins for more detailed explanations.

---

To summarize, you should at least have the following stuff prepared:

* **Manager**, responsible for managing the board
* **Dictionary**, storing the layout of the board
* **Chess Piece**, represents each individual chess piece on the board
* **Tile**, represents each individual tile on the board

---

**UPDATE**

Here is a screenshot which shows a hierarchy of `GameObject` in a simple chess game.

Of course, you don't need to follow it strictly. The structure can be very flexible. It is really important to experiment with different structures, so as to find a way to handle gaming logic which you feel comfortable while giving good performance.
> 3 votes

---
Tags: unity, grid
---


# Question
Title: Simple square hit the wall and turn around without stopping
I am coding and making my very first plat former game in Unity 4.5 2D.

Basically I want my character to ping pong between two walls.

I have set up a GroundCheck and CeilingCheck. I was thinking to add a WallCheck on the left and right of the character to detect the walls, but I will have platforms in the air, and if the character doesn't make the jump and hits the platform on the side I don't want it to turn around, but simply slide off and continue in it's current direction until it hits the wall again.

Coding in C# 1. Get the character ping pong from wall to wall 2. Know the difference between hitting the wall and hitting the side of a platform.

# Answer
> -1 votes
Define an interface `IWall`.

```
using UnityEngine;
using System.Collections;

public interface IWall {
    void OnCollisionEnter(Collision collision);
}

```

It is nice to separate the **vertical** and **horizontal** walls in to two classes as their logic for handling collisions is different.

**VerticalWall**

```
using UnityEngine;
using System.Collections;

[RequireComponent(typeof(BoxCollider))]
public class VerticalWall : MonoBehaviour, IWall {
    public void OnCollisionEnter(Collision collision) {
        if (collision.rigidbody) {
            // You can add forces to the collided object, change its velocity etc.
            Vector3 v = collision.rigidbody.velocity;
            v.x *= -1;
            collision.rigidbody.velocity = v;
        }
    }
}

```

**HorizontalWall**

```
using UnityEngine;
using System.Collections;

[RequireComponent(typeof(BoxCollider))]
public class HorizontalWall : MonoBehaviour, IWall {
    public void OnCollisionEnter(Collision collision) {
        if (collision.rigidbody) {
            // You can add forces to the collided object, change its velocity etc.
            Vector3 v = collision.rigidbody.velocity;
            v.y *= -1;
            collision.rigidbody.velocity = v;
        }
    }
}

```

Remember to attach a `Rigidbody` component to your character `GameObject`.

---

If you want to have your character to slide down along the vertical wall, you can set its velocity as `v.x = 0` rather than `v.x *= -1`.

# Answer
> 2 votes
If your platforms are isolated use Tags.

Each object and prefab in the Unity game world can be interacted with differently depending on the tag they have.

For a wall of any kind simply tag it as "Wall" and code it with this is mind when making collision detection on your main character.

For a platform, guess what, tag it as "Platform". You can then implement a different collision behaviour for each object type using OnCollisionEnter:

```
public class ExampleClass : MonoBehaviour {
    void OnCollisionEnter(Collision collision) {
        foreach (ContactPoint contact in collision.contacts) {
            switch(contact.tag){
                case "Wall":
                    CollideWithWall(contact);
                break;

                case "Platform":
                    ClimbUpPlatform(contact);
                break;

                // Some fun examples of how to expand:
                case "BouncyFloor":
                break;

                case "QuickSand":
                break;
             }
        }
    }
}

```

From there - create your methods: `CollideWithWall` and `ClimbUpPlatform` to handle what affects your character.

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


title: Automatic Left/Right movement

text:
# Question
Title: Automatic Left/Right movement
First 2d game in Unity. Started Character controller in C#.

Tried to get the character to move constantly right then once it hits the wall move left without needing any input from the player. Looked at a couple infinite runner character controller examples, but they seem to trick the character into thinking the player is holding down the right button in order to make the character run right infinitely "character.Move( 1, false , jump );".

Question: How to make the character start moving right automatically?

# Answer
Flip a switch depending on the walls' collision face:

```
bool runForwards = true;

public void WallCollsionHandler(Collider collider){
    if(collider.tag == "Left Facing Wall")
    {
        runForwards = false;

        // Or
        // JumpBackwards()
    }
    else if(collider.tag == "Right Facing Wall")
    {
        runForwards = true;

        // Or
        // JumpForwards()
    }
}

```

This will stop you getting stuck in a wall as well as switch your direction depending on the wall face you contacted. What you'll need to do is put 2 collision triggers on a wall to differentiate the direction you jump or run.

To make your character constantly move you can apply a constant velocity or position update on each Update, the below is very crude but will get you started:

```
float movementSpeed = 5f;

void Update(){
    oPos = transform.position;
    transform.position = new Vector3(oPos.x + movementSpeed, oPos.y, oPos.z)
}

```

Altogether:

```
public class RunningCharacter : MonoBehaviour {

    float movementSpeed = 5f;

    bool runForwards = true;

    void Update(){
        UpdatePosition();
    }

    void UpdatePosition(){

        Vector3 oPos = transform.position;
        float calculatedPosition;

        if(runForwards){
            calculatedPosition = oPos.x + movementSpeed;
        } else {
            calculatedPosition = oPos.x - movementSpeed;
        }

        transform.position = new Vector3(oPos.x + movementSpeed, oPos.y, oPos.z)
    }

    void OnCollsionEnter(Collider collider){
        WallCollisionHandler(collider);
    }

    void WallCollsionHandler(Collider collider){
        if(collider.tag == "Left Facing Wall")
        {
            runForwards = false;

            // Or
            // JumpBackwards()
        }
        else if(collider.tag == "Right Facing Wall")
        {
            runForwards = true;

            // Or
            // JumpForwards()
        }
    }
}

```
> 4 votes

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


# Question
Title: Adding touch/click event to a bitmap in android
In my android game, there is a `surfaceview` which has 36 `bitmap`s drawn on it. I want to change the `bitmap`s when they are touched. Is there a way implement `touch` or `click` event to the `bitmap`s ?

Adding `touch` event to `surfaceview` and then to calculate the `bitmap` touched will be very tedious since there are 36 `bitmap`s.

# Answer
If i correctly understood you, then I believe, you can add a click listener to a bitmap just like to a jpg image or other format.

In my example the image\_star is a png file.

```
ImageView img = (ImageView) findViewById(R.id.imageView1);

img.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            //some code
        }
    });

```

The xml :

```
    <ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/imageButton1"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="62dp"
    android:src="@drawable/image_star"
    />

```

The result of this would be lower. The picture with a star in the middle is a clickable image, the `ImageView img` from my code. The upper button is an ImageButton.

Also there is a way to make it clickable only through the xml code, but im not sure how that is done, because i dont like that way.
> 1 votes

# Answer
a `Bitmap` itself cannot be clickable on Android. You have to draw each `Bitmap` to an `ImageView` or an `ImageButton`, and listen to that view's touch events.
> 0 votes

---
Tags: android, input, events, touch
---


# Question
Title: D3D11 shader signature validation with SV semantics
I'm trying to figure out what the rules are for linking the outputs of one shader stage to the inputs of the next. Since D3D11 does not have any error checking for linkage between shader stages, I have written some code to check them by comparing the `D3D11_SIGNATURE_PARAMETER_DESC` struct from each input and matching it to an output of the previous stage. The code for checking the signatures is here.

This mostly works, except when there are certain special inputs to a stage that don't get passed from the previous stage. One example is the `SV_IsFrontFace` input to the pixel shader. Another example is the `SV_PrimitiveID` input to any stage *after* the vertex shader.

I've been googling and reading msdn.microsoft.com and so far it's totally unclear to me exactly how these special SV semantics work. In particular:

**Q1**. Does the ordering of them matter? Or must they occur *AFTER* all inputs that are passed in from the previous stage?

**Q2**. Some of these "special" SV values can be identified by looking at the `SystemValueType` field of the `D3D11_SIGNATURE_PARAMETER_DESC`. For example `SV_IsFrontFace` can be identified by checking if the `SystemValueType` field is `D3D_NAME_IS_FRONT_FACE`. However, what about `SV_GSInstanceID`? There doesn't seem to be a corresponding value in the `D3D_NAME` enumeration for that. http://msdn.microsoft.com/en-us/library/windows/desktop/ff728724(v=vs.85).aspx

**Q3**. Is there a link where the rules for shader input parameter linkage is explained clearly? Or better yet, code for validating shader signatures?

# Answer
So the short answer is to turn on the debug layer. Thanks to @Nathan Reed for pointing that out.

I tested it out and verified that it does indeed detect when shader signatures are incompatible. I also verified that new `SV` inputs to a shader stage must come last in the list of inputs.
> 1 votes

---
Tags: shaders, hlsl, directx11
---


# Question
Title: Java Buffers and OpenGL ES 2.0 (Android)
I've been trying to come up with a good solution for preloading textures asynchronously, but in Android with OpenGL ES you cannot create a texture out of context.

Would the proper solution be to load up a ByteBuffer with data from my png image, then when I'm back on the render thread call glTexImage2D? What I don't understand is whether or not OpenGL will actually copy the buffer into it's own location, or directly access mine. The latter approach would be ideal.

Could anyone give me clarification?

# Answer
> Would the proper solution be to load up a ByteBuffer with data from my png image, then when I'm back on the render thread call glTexImage2D? What I don't understand is whether or not OpenGL will actually copy the buffer into it's own location, or directly access mine. The latter approach would be ideal.

This is basically what you want to do. Load the texture *data* from a worker thread, and once the load is complete construct the OpenGL texture resource (from that data) on the main/render thread.

Once you call `glTexImage2D`, you don't need to keep your copy of the texture data in-memory any longer (you can delete it) unless you need it for some other purpose. OpenGL will copy the data it needs elsewhere.
> 1 votes

---
Tags: android, textures, opengl-es2
---


title: Is OpenGl still supported in C?

text:
# Question
Title: Is OpenGl still supported in C?
I'm reading the OpenGl superbible 3th edition (well I plan to) and it's all in C. Since this book was written in 2004 and all the other later versions are written in C++, i was wondering whether or not OpenGl is still supported in C, and whether the relevant downloads required will still be available. I want to do it this way, because I'm more comfortable with C, and I'm still learning C++.

# Answer
OpenGL is natively written in C. For C++ you usually use wrappers. So yeah, don't worry, it'll work just fine in C as always :)

I would suggest to read a more modern book though, a lot has changed with OpenGL 3+.
> 2 votes

# Answer
You can use OpenGL natively in either C or C++, the API has always been implemented in C.

You can also use OpenGL calls in C++ exactly the same way you would in C.
> 0 votes

# Answer
Yes.

The standard OpenGL headers are all written for C, although the book is written in C++ so that they can use their supplied classes. Most windowing frameworks, including SDL and GLFW, as well as GLEW for loading extensions, are also written in C. Even SFML has a set of C bindings.
> 0 votes

---
Tags: opengl
---


# Question
Title: "Pixel-perfect" camera positioning in 2d game
I am writing a 2d game using *LibGDX*. The view to the game world is top-down. The game shows a grid of lines, which looks nice when the camera is at its initial position (0,0).

The problem is now that when I move (shift) the camera left/right/up/down this grid sometimes becomes a bit blurry, so the lines do not look perfectly sharp any more.

I assume this is because in these cases the grid lines are not exactly on screen pixels, but somewhere in between. Is this correct?

In any case: Are there any "best practices" how to address this problem (not necessarily *LibGDX*-specific)?

# Answer
> 6 votes
> I assume this is because in these cases the grid lines are not exactly on screen pixels, but somewhere in between. Is this correct?

Yes, this is correct. The camera in LibGDX is based on a vector, which is made out of floats. When your camera is in between pixels (like at (1.2f, 63.5f)), then you will start to see that blur you mention because the rendering engine will try to draw in between pixels and approximate the colors.

The simplest way to deal with that is to the position of the camera as an integer.

```
camera.x = (int) camera.x;
camera.y = (int) camera.y;

```

The best way to do this would be directly when you position your camera. If you move your camera with a player, for example, then the code would look like this:

```
camera.x = (int) (player.x + xOffset);
camera.y = (int) (player.y + yOffset);

```

---
Tags: libgdx, camera
---


# Question
Title: Giving one controler button two functions
I'm currently working on a game that allows the player to do some different actions.

1. Dodge (X button)
2. Attack (A button)
3. Use Item (Y Button)
4. Block (BButton)

***I would like to be able to use the "Y" button to both use items and pick items up.*** This dual functionality would be determined by how long the player held the button and if the player was standing next to an item. I'm sure there have been studies on this and how long the player expects for a delay to use the second functionality but I'm worried that I have become biased in my testing and I can't find anything online.

My question is: **Is there some sort of standard for this type of a time delay for the button? If so where can I learn more about it?**

# Answer
HCI researcher here. I am not aware of any "standard" values that work for all scenarios. If you search on scholar.google.com for "user reaction time" or "target selection time" you should be able to find more. Although these works might investigate different setups than yours. For example target selection with multitouch input or eye-trackers (the "dwell time" is a known interaction technique in gaze-based systems).

However, this is the typical thing that you could investigate in a small qualitative user study. Try different conditions (ie 100ms, 200ms, 500ms, 1000ms) in alternating order and have users rate which condition they liked the most on a scale of 1 to 5 or 1 to 7. Users should repeat each condition a number of times, say 5.

You might not be able to publish these results :D but if you can spot a trend, then you'll have your answer. If finding at least 10 users is something that is feasible for you.
> 0 votes

---
Tags: control, timing
---


title: c++ OpenGL framerate question

text:
# Question
Title: c++ OpenGL framerate question
I am writing a simple 3D pacman using c++ and OpenGL. I'm new in OpenGL development, I wanted to make a small project before learning next concepts.

For now I can't have more than 55fps when rendering every objects.

These are my objects is the game :

After commenting my code to see which objects was causing problems, I know that the grid ( that is oly a plane, so 6 vertices ) and the walls ( 17k vertices, 1 draw call ) are causing the problems. ( By commenting all other elements, like foods, player and ghosts I only win 5 fps )

Which leads me to this question : What really matters with frame rate? The number of draw calls? The number or indices it has to render? the number of pixel that will be visible in the screen? Everything?

It seems that vertices outside the screen are ignored, but if that's true, how can I improve my fps count?

Or maybe I am just worrying for nothing and that's a normal thing with the first projects and should just continue?

Thanks for the help.

# Answer
> 2 votes
It might sound dumb, but make sure V-Sync is not enabled. And yes, reduce the draw calls to gain fps. If you have multipled shaders and textures, make sure you don't make unnecessary switches between them, like first draw all objects which use texture0 and not one object with texture0, then another one with texture1 and then back to texture0 etc. really try order these things. Also use VBOs, don't use glBegin and that deprecated stuff. For shaders you should also use uniform buffers instead of just uniforms.

# Answer
> 1 votes
Are you dynamically creating the buffer for the draw call each frame? If the walls never (or rarely) change then a vbo will be a good optimization.

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


title: AI Pathfinding Algorithms

text:
# Question
Title: AI Pathfinding Algorithms
I am looking to create a special kind of pathfinding system. At this point, the geometry is still flexible, but this pathfinding is integral to the project.

The goals I have are this:

1. I will have a number of entities seeking paths.
2. Each entity will have a memory of certain paths.
3. The memory will be based on landmarks. Landmarks will be objects or entities on the map that can be or have been seen by the entity.
4. When an entity generates a path, it's only doing it based on what it can see, and what it has memory of. Anything else has to be guessed, it can't use unknown information.
5. The system has to be able to handle a updating paths for a lot of entities at once, but it never has to find the best path, especially not on the first try.
6. It doesn't need to find a path to it's destination in a single frame, just be able to make progress, and reach the target eventually if possible.
7. Entities might be able to share partial or full path information.

I'm thinking this is best served by some modified D\* algorithm, but I was wondering if anyone had any other suggestions for something to do this, or challenges that I'd expect to face.

One thing I'm cognizant of for instance is that if I'm using landmarks to confirm the path, that I'll be able to quickly look up nearby landmarks. If I have thousands of landmarks in a list and need to iterate through them and calculate distance to the player this is going to cause trouble. If I'm going to define regions, like a convex hull, I might be able to share that calculation across entities when they need it since I might be able to say anyone inside this poly should be able to see everything within this poly.

# Answer
At first blush, I'd try to use Hierarchical Pathfinding for what you describe. The main reason why is that it seems that you're talking about Landmarks as the main element that represents the map at a high-level, and that should map well to a hierarchy of two levels.

So you'd have two maps. For the high-level map, each node is a Landmark, and you have a web of connections representing Landmarks contiguous to other Landmarks. This should address your concern with iterating through a list of Landmarks, although you'll probably still require some kind of spatial structure to find the Landmark closest to your start point and your destination. A simple, coarse, grid might work well, or you could build a tree structure, like a KD-Tree, or a Quadtree.

The low-level map would contain the actual geometry and navigation information. It would be grouped by Landmark. The way to divide the geometry will depend on what you end up using. If you use navigation meshes, you could literally cut out areas around a Landmark and have the polygons follow the borders. If you use a grid, then you could have a mask for what squares are linked to each Landmark.

As the characters learn about new Landmarks, you'd allow them to use those Landmarks in the high-level pathfinding (they'd become "unblocked"). The low-level pathfinding only needs to be done as a character prepares to enter the area around a new Landmark, and we only need to calculate how to get to the next area, which should be fast.

If you want to share paths, you could cache paths per Landmark, to go from one of the neighboring Landmarks to another.

The main sticking point with Hierarchical Pathfinding (especially compared to a general algorithm like D\*) is that because you're not doing a global search, it's possible that the path might look a bit unnatural. Think of a path using navigation meshes without the optimization step. You can solve that by carefully designing the areas that will be attached to Landmarks, and using tricks like looking ahead one Landmark (which is pretty effective).
> 1 votes

---
Tags: path-finding
---


# Question
Title: How should I set up 2D animations for weapons in Unity?
I have a character composed of several sprites (legs, torso, head, arms). The character has the ability to pick up weapons, which are of varied types.

Each type of weapon has its own animation (sprite sheet). Ideally I want the weapons not only to animate themselves, but also affect how the player is animated (e.g. lean back when swinging sword).

Here's how I'm thinking of setting it up right now:

Player has an animator controller with states for Walking, Attacking, Idle, Flinching and this controls all the body parts.

Main questions: \- How can I incorporate jumping in this? \- How can the weapon animations have control over the rest of the body?

For having different weapons I am thinking of adding different states per weapon type, but I don't think that's a great way, especially when I start adding combos.

# Answer
Your approach is inverse of what I would do. Weapons don't control the character, it's the other way around. So I suggest setup animations on character to jump normally as it has a weapon in hand. If you have several weapon types (light, heavy, custom...) you can setup animation for each one of them, it would probably just affect how hands are holding the weapon and maybe core body posture. In character then, when you jump, you start proper animation for type of weapon you are holding.

In general, I think this is a good approach but if every weapon requires custom animation for the character (hard to imagine) you might be better of with reversing the responsibility and linking animation to weapon instead of character. I wouldn't worry about combos, make your animations simple and combos would be just 2 or more animations blending into one at runtime.
> 1 votes

---
Tags: 2d, unity, animation, mecanim
---


# Question
Title: Creating a seamlessly looping 2D multiplayer level?
A discussion came up recently about how to create a 2D side-scrolling multiplayer game that can have an looping level design (Think of Starbound and how their worlds are looping).

I thought the simplest way would be to have a rectangular map with trigger zones which could teleport players from one side to another. However the obvious issue with this approach is the case of having multiple players at edge of the map at once. You don't want to just teleport players in front of each other and you would need a way to transport players without having other players disappear.

To append this idea and fix the issue I came up with the following: have a trigger zone (red square in image) where players will be able to see a "clone zone" (green square). In this green square, objects from the opposite side of the trigger zone would be copied into its corresponding clone zone (can be seen with A & B shapes). When a player gets to the starting edge of the "clone zone" they are teleported to the other side of the map.

In this example Player 2 would think they are seeing Player 1, however they would actually be seeing his clone and vice versa.

This seemed a bit extreme and complex for the problem at hand. My question now is to know if this solution is a good approach to tackling the issue, or is there a simpler way to solve this problem?

# Answer
> 16 votes
This system with all these triggers sounds a bit too complicated and error prone.

You could wrap the position of the player using modulo with something like `playerPositionX = playerPositionX % mapWidth`

This way when your player reaches `playerPosition == mapWidth` the `playerPosition` will reset back to 0.

This solution could be extended with the whole rendering system.

# Answer
> 13 votes
The canonical solution is to use **portals**. In your example, there is only one level, except there is a portal connecting the left and right ends.

Anything moving across that portal will have its coordinates translated to the other end of the portal, so that if something is moving left through the portal, it will reappear on the right side of the level and vice versa.

Your camera needs to support the portals too; if the portal is inside the camera, then it must render parts of the level on either side of the portal. If you're familiar with image editors for seamless tile graphics, it's the same deal here.

The tedious part is that everything dealing with distance or pathing will *also* need to support portals. This includes AI, line-of-sight algos, sound attenuation and so on.

The nice thing about portals though is that it's very powerful. The build engine used it to simulate multi-story levels, despite it not being a "true" 3d engine. Some modern engines use portals too to create non-Euclidean spaces; Portal and Antichamber are notable examples in 3D.

# Answer
> 6 votes
Remember that what you display on screen, and what's in memory are two totally different things. Imagine you have a window that you need to fill with data about the world. You fill the window from left to right. While you're parsing your data to fill the world, if you reach the end of the world, simply loop back around to the beginning of your data. Using a modulo operation is ideal. Remember you need to do this for **everything**. Projectiles, rays, players, physics; they all need to have their positions wrapped when crossing the world bounds.

Each player shares data, but has their own perspective of the data. Their windows are populated differently depending on where they're standing in the world.

This means there's no need to create clones, or teleport anyone. Essentially you *are* creating clones, just by rendering characters to each other's screens.

# Answer
> 3 votes
Disconnect the rendering from the world and you can do wraparound and correct rendering without resorting to any cloning or teleporting artifacts.

First, in your world you have a fixed size world, from `0` to `Width`. Anytime an object goes below 0 you wrap it to the end, and anytime an object is over `Width` wrap it to the start. This means that all logical objects in your world are always within the range `0...Width`.

Second, for rendering you'll do modulo on the position. So the left side of the screen is "Base" and the right side is "Base + Size". So you look through your world for anything within that range. You'll actually search for the modulo range, which maps it back to `0...Width`.

The trick while searching is to return the object's position relative to the `Base` on the left side. This converts to local coordinates of the screen so the renderer itself doesn't have to worry about the modulo, only the lookup does.

You don't need to clone anything since each renderer only deals with the object in one location.

If your world is produced in segments, or using 3D structures, you'll have to segment it. Thus it isn't one consitunous block, but can be moved to accomodate this rendering. You don't need many blocks, at a minimum 2.

# Answer
> 1 votes
I think the only reasonable approach would be to implement your wrapped world in an underlying data-structure completely transparent to the game and the user. So on some Low-Level you have a function mapCoordinate() which wrap your actual coordinates to your underlying map-resource...

So if your actual World is only 10units wide, the player and the game will not know it. For the player the world is infinite - and if the game asks what is at position 15 - the underlying function will translate this request, modulo10 and will give pack the item at position 5.

So for the whole game logic and everything else it is just like you have an infinite big world, where there just happen to be copies of everything.

# Answer
> 1 votes
It's not quite the same, but I implemented something similar at a game jam. The game had players moving on a small circular level, wrapped around when the player reached an 'x' position of pi. Rendering was easy because we just rendered everything and then rotated an offset camera to track what was going on. You could implement something similar, as has been suggested above:

* When drawing, check the camera position and determine what needs to be drawn, taking into account the camera position and its vision range.
* In cases where the camera sees past the 'edge' of the map, select an appropriate amount of content from the other side of the world to draw over that edge, usually just by adding or subtracting the width of the level to their position.
* Game logic needs to be aware of this seam and adjust for it as mentioned in other answers. Particular cases to be aware of are collisions where one object is on one side, but is colliding with an object on the other side.

---
Tags: 2d, camera, multiplayer, level-design, non-euclidean
---


# Question
Title: Doing imagemagick like stuff in Unity (using a mask to edit a texture)
There is this tutorial in imagemagick

http://www.imagemagick.org/Usage/masking/#masks

I was wondering if there was some way to mimic the behavior (like cutting the image up based on a black image mask that turns image parts transparent... )

and then trim that image in game...

trying to hack around with the webcam feature and reproduce some of the imagemagick opencv stuff in it in Unity but I am saddly unequipped with masks, shaders etc in unity skill/knowledge. Not even sure where to start.

# Answer
Ended up just taking the picture the mask and copying the pixels across if not a masked pixel:

```
Texture2D BuildMask(Texture2D tex)
{
    int x =0;
    int y=0;
    int width = Mathf.FloorToInt(maskTex.width);
    int height = Mathf.FloorToInt(maskTex.height);

    Texture2D tmpTexture = new Texture2D(maskTex.width, maskTex.height);
    //set all the tmpTexture to alpha

    int farthestLeft=0;
    int farthestRight=0;

    for(int yv=y; yv<height; yv++)
    {
        for(int xv=x; xv<width; xv++)
        {

            if(maskTex.GetPixel(xv,yv).a == 1)
            {
                if(farthestLeft <= xv)
                    farthestLeft = xv;

                if(xv>=farthestRight)
                    farthestRight =xv;

                tmpTexture.SetPixel(xv, yv, tex.GetPixel(xv,yv));
            }
            else
            {

                tmpTexture.SetPixel(xv, yv, new Color(0,0,0,0)); //0,0 bottom left.
            }
        }
    }

    tmpTexture.Apply();
    return tmpTexture;
  }

```
> 0 votes

---
Tags: unity, textures
---