title: Is C# different in Unity?

text:
# Question
Title: Is C# different in Unity?
Does Unity use a different version of C#, or is it all the same? It looks different from regular C# but there are some regular C# elements in there.

# Answer
> 9 votes
As stated in other answers Unity 4.x uses a **modified** version of Mono based on Mono 2.6

For the most part, this is compatible with the .Net 2.0, though I haven't managed to track down a Mono 2.6 specific compatibility list.

> It looks different from regular C# but there are some regular C# elements in there.

As mentioned in one of the comments on your question, this is likely due to Unity's particular scripting API rather than the language itself.

As an example, a lot of code in a typical Unity projects is contained in subclasses of a class called MonoBehavior. These are components that are dropped on GameObjects within the Unity Editor environment. This architecture leads to C# code that looks different to typical C# code (to me anyway) in a number of ways:

* Until Unity 4 was released, these objects could not be contained in namespaces, so they're always in the global namespace
* They expose fields to the editor environment by making them public (or by using the SerializeField attribute, but I find very few people use this), which leads to an unusually large number of public fields on classes
* Unity's privacy and case conventions don't follow Microsoft's, so this can also look strange to a "traditional" C# developer
* They make use of a number of special methods on these components, such as Start and Update, that are not overrides as one would typically expect, but are accessed by means of reflection instead.

Practically speaking, the biggest C# language feature I miss in Unity's current C# version is support for async and related keywords and functionality. A similar concept in Unity is coroutines. These execute on the main thread so aren't true async, but do allow long running code to be broken up over multiple frames. Lower level multithreading is still supported.

# Answer
> 21 votes
Unity 4 uses Mono 2.6, which is a full implementation of the .NET framework, including the C# language.

I'm not sure how it looks different, but keep in mind that Unity supports several languages, all of which work on top of the same Mono runtime. Is it possible you're confusing C# with UnityScript?

# Answer
> 3 votes
Unity uses regular C#.

Then again, when you write C# in Unity you will be using a lot of their libraries, but as far as I know, everything possible in C# is possible in Unity, other than the differences listed below:

* More specific areas of .Net relating to Windows Forms & ASP are off limits through Unity.
* While you can use Visual Studio for editing and compile-time errors, you have to build and run in the Unity IDE.
* Unity uses Mono which is an open source implementation of .Net which means there are slight differences.

# Answer
> 0 votes
The question whether the C# Version used by Unity is different from a "regular" C# has been answered by other posts. Since you are explicitly asking for certain elements which might differ from such a regular version I will share the only minor difference I noticed when comparing the C# I use at work (i.e. C# 4.0 in Visual Studio 2010 and higher) and C# in Unity, which is that I can't use default values for parameters in function definitions. which is that you have to set up your project more carefully in order to use a newer version of C#. See this link for further explanation.

**Edit:** I leave this answer since as far as I know this is a misunderstanding that happens to quite a lot of people.

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


# Question
Title: DirectX9 Drawing Sprites out of place due to offset
This is my very first time into DirectX. Im trying to make a simple 2D game, just for learning the basics. And i've achieved that. The next step is to draw an animation using sprites.

For that, i downloaded SpriteBuddy, a very simple and user friendly software that helps you creating the metadata for your spritesheet.

Ok, now, the problem im having is that, the metadata that i get from spritebuddy (and i know is not the spritebuddy data that is wrong because i downloaded a few more software and the result was the same) come with a offset for every sprite.

Now, when im drawing, i said, lets add the offset to the position of the sprite, that should do it. Annnnnd it didnt, so i started to manualy change the metadata to see how bad was it. The result was that on the y axis, if you doubled the ammount in the metadata, the drawing was a lot less messy.

Is there something im doing wrong?

```
SpriteData* metadata = this->m_pXMLTraductor->getSpriteDimension(numFrame);//the number of the frame we want the dimensions
RECT temp = metadata->position;
D3DXVECTOR3 vCenter(0.0f, 0.0f, 0.0f);
D3DXVECTOR3 vPosition(this->vPosition.x + this->metadata->offset.x, this->vPosition.y + (metadata->offset.y*2) , 0.0f);

this->m_pSprite->Begin(D3DXSPRITE_ALPHABLEND);
this->m_pSprite->Draw(
    this->m_pTexture->GetTexture(),
    &temp,
    &vCenter,
    &vPosition,
    D3DCOLOR_COLORVALUE(1.0f, 1.0f, 1.0f, 1.0f));
this->m_pSprite->End();
long long cont = 0;
this->numFrame++;
if (this->numFrame > this->m_pXMLTraductor->spriteCounter()){
    this->numFrame = 0;
}

```

This is how i render the model.

Is there any other way to do this? Srry about my english. Im working on it too ^^

# Answer
> 1 votes
I personally haven't used the method your using. But since you have asked if there is another way to do this...

Suppose you have a texture atlas (texture made up of sub-textures) where each sub-texture has the same dimensions:

Then if you create a `RECT R = {j*64, i*64, (j+1)*64, (i+1)*64};`

-\>Where `int j = currentFrame / 6 //row`

-\>Where `int i = currentFrame % 6 //col`

-\>(6 because of 6 sub-textures in a row)

-\>Where 64 is the width and height of the sub-texture

You would simply use this line to draw:

```
mSprite->Draw(yourTexture, &R, &mSpriteCenter, 0, D3DCOLOR_XRGB(255, 255, 255));

```

So as you update your `currentFrame` in an update method, this will effectively update your rect to be draw from the texture.

Additional note: I learned this method from *Introduction to 3D Game Programming With DirectX 9.0c A Shader Approach* \- by Frank D. Luna

---
Tags: c++, directx, sprites, spritesheet
---


# Question
Title: Detect which object conceals another one
I've searched for a while for a good solution and if I'd have found one I wouldn't be here. So there are the details: I have been working on my 2D game using XNA, and I'm aware of the way XNA renders objects(If "a" was drawn after "b", it will draw "a" above "b"). In the game I'm making there's a character that is able to move left, right, up and down. I'm, using Rectangle's "Intersects" method, when the rectangle on the character is placed on his feet, to detect collision detection. I would also like the character to be able to move behind a house(Just like you can in real life, and the house will hide a part of the character that is hidden behind the house). So far, all the things that I've mentioned are accomplished. Now, I would like to hear how would you recommend detecting whether the character is standing in front of the house, and hiding the part of the house that his standing in front of, or whether the character is standing behind the house. I understand it might be a little hard to understand, therefore I added a picture that will simulate the situation. (No I'm not the one doing the drawing) Any help, advices, or criticism would be appreciated. Thanks ahead!

# Answer
> 0 votes
This is easily accomplished by giving each object a Z value, a single value that determines how far away from the screen it is, if you want to look determine what object is in front of the other you just look at which one has the smaller z value.

---
Tags: algorithm
---


# Question
Title: HTML5 - multiple animations, different fps
I want to create an html5 game which contains multiple sprites.

For different elements I want to create an fixed fps.

For example:

Walk - 10 fps, so 10 sprites will be shown within 1 second

Run - 15 fps

Attack - 3 fps

How can I create this with requestAnimationFrame and not using set timeout or setinterval.

# Answer
> 1 votes
You could simply for every frame you get check the time and only draw a new frame when the right amount of time has passed. Though I don't think there is much point in using `requestAnimationFrame` when you are updating that slowly.

And for the record 3 fps is very slow. If you are doing so few sprites it might be better to not talk about fps, and instead talk about time between the individual frames, and then also realize that there doesn't have to be an equal amount of time between frames in any given animation. You can adjust the time that every individual frame is shown depending on what looks good, and if there is a visible glitch you can add in an extra frame right at that moment without having to change the rest of the animation.

---
Tags: html5
---


# Question
Title: How to gain visibility on the Play Store?
Sometime in the near future I'll release my first Android game. It's not going to be anything special, but I'm trying to make it as polished as possible and I would like to know what I can do to prevent it from falling into obscurity.

If you look hard enough, you can find some pretty well-crafted games on the Play Store that, nonetheless, are virtually unknown. I recently came across one developer that has published six well made games that are pretty fun and have good art as well; out of these six, two are moderately popular (10,000–50,000 downloads), while the rest have very few downloads (1,000 or fewer).

What are some techniques to increase your game's visibility on Google Play upon its launch?

# Answer
You need to find players somehow, the first obvious step is to tell your friends, if they like it enough to also tell their friends this can be a good start. A second point is to post about it on some forums, not on the general spammy "play my game now" way but more of a hello I'm and have made a new game and am looking for some advice ext. this can help you gain even more players. Once you have this going you can send it to some youtube game reviewers/let's players who will then hopefully play you game and get you enough media attention to get you to the top of the play list.

The basic system is that each download you get increases your chance of getting in the initial top so you need to use methods outside of the store to get a number of downloads required to do well in the store, use a combination of online and offline methods to increase your chance.
> 1 votes

# Answer
Marketing is basicly getting a connection with the target audience of your product, in this case a mobil app/game. This can be done in many ways including the following:

* Your friends, family and acquaint. Talk to them if they have any interest in mobile games, else try get them to recommend your app to people THEY know like mobile games. This personal marketing can be achieved by mouth, phone, facebook, twitter, a personal blog.
* Try reaching out to a more "professional" network, which will include your fanbase, or other interested audience. A good strategy can be to have a facebook page for your game, a website, or a blog for updates on development or new content or other types of communication (see bigger other similar games that already top what they post on their networks).
* If you are completely new to the market, setting up a fanbase would be the place to start and this is mostly done by the two above steps in addition to contacting "bigger/more famous" people that can spread the word of your game. A few ideas to how this is done is to contact youtubers (serach for game reviews and "let's play"s to find people who does what you want), *or streamers (does not really apply to mobile games)*, and have them do a review or playthrough of your game.
* Another little more costly effort can be add's, which you can purchase and place with help from google-ads or facebook-ads. It's then up to you to decide what kind of ad you want, where there are two major types of web adds. One is pay per click, and one is pay per view. They both have their advantages and disadvantages.
* Yet another strategy is to contact online magazines to write a review about your game, or a short article on who you/your company if any, are and what you do.

This are some good starting points, some more difficult than others. What you must begin with is learn to "speak for your product", which is basicly the content you want to display to other people, to have them interested in your product. A good place to start is by searching for other adds, and reviews, or basicly any material related to a well selling game and see how they give their game appeal to others.

Edit:
Here is a good post from reddit on promoting a game. It is relevant here.
Here is a guide on how to contact the press, written by and for indie developers.
> 1 votes

---
Tags: mobile, marketing
---


# Question
Title: XNA - Making 2D Hexagons Connect With Each Other
I'm working on a top-down 2D strategy game in XNA, and the tiles are hexagons. I can't have a grid because of the game mechanics, so everything has its own location, and every tile object is stored in a list. What I'm trying to do is have it so that if you place a tile close to the side of another tile, they will snap together and become one object. I can't seem to figure out how to get what side it should snap to.

The red represents the different sections I want to check for mouse clicks in (these would of course not be an actual texture in the game). The white represents the area where if you clicked, it wouldn't allow you to place a tile because it would be on top of another. The closest thing I can think of is to have a larger hexagon around the actual tile that's divided into triangles from the center to the edges, but I'm not sure how to do this.

And I'm gonna move it to Windows Phone with Monogame and I don't think the phone is fast enough to make some sort of thing that checks colors for each sector, so I don't think it can be texture based. I feel like there's some kind of relatively simple math to do this but I can't seem to figure it out.

# Answer
Compare a line between the center of the nearest hex shape within a close radius of the mouse and the mouse itself and get the angle of the line between them relative to the horizontal axis of the grid. Then you could use a function like.

```
public Vector2 CalcHexPositionFromAngle(double angle, Vector2 point, double radius)
        {
            //assume the angle is in degrees and shed any numbers over 360 eg: 427 becomes 67
            while(angle >= 360)
            {
                angle -= 360;
            }

            //This is a trick using the nature of truncation in most programming laguages
            int tempAngle = angle/60;

            //now we just multiply the number by 60 to bring it back up
            //to an increment of 60 degrees and add half that again to find an angle between
            //corners in the hex shape
            int angleOfPlacement = (tempAngle*60) +30;

            //assume the angle is in degrees (If angle is in radians forget this step)
            //sin uses radians not degrees.
            double newRadianAngle = angleOfPlacement*Math.PI();

            //calculate the new position.
            double P_X = point.X + radius * Mathf.Cos(newRadianAngle);
            double p_Y = point.Y + radius * Mathf.Sin(newRadianAngle);

            return new Vector2(p_X,P_Y);

        }

```

This should give you the new position for your hex given that it is handed the the

angle in degrees between the originating hex you are snapping to and the mouse

the vector2 that is the center position of the originating hex you are snapping to

and radius or (half the distance between opposing faces of your hex shapes)

Note: this function takes degrees but can easily be adapted for radians.
> 1 votes

# Answer
The way I might approach it is to create a list of all possible hex center locations during the initialization stage before the game loop starts. Then during the game loop, if there is a mouse click within 1.5 tile radius (or whatever dist you think is approp) of a white tile, simply iterate the list and find the closest list Point to the click point. If the mouse click is closer to the result than it is to the white tile center, use that result as the center of the new tile you want to place. It can all be done using distaceSquared to avoid a bunch of square rooting too.

Better yet, simply store 6 relative offset vectors for each possible neighbor's center location. Then when a mouse click occurs near a white placed hex, iterate through the 6 offests and find the one closest to (mouseClick - whiteHexCenter). The new Hex should be placed such that its center is at (offsetResult + whiteHexCenter).
> 1 votes

---
Tags: xna, 2d, collision-detection, tiles, hexagonal-grid
---


# Question
Title: Why won't my sprite move with this code?
When I ran the android application, The sprite image will not move when I press the input keys. I followed a tutorial based on input keys and wish to know what's wrong. Can anyone see what's wrong? Not sure if its my android emulator.

EDIT: website where the tutorial is located http://www.gamefromscratch.com/post/2013/10/15/LibGDX-Tutorial-4-Handling-the-mouse-and-keyboard.aspx

```
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;

public class otherSide implements ApplicationListener
{
    private SpriteBatch batch;
    private TextureAtlas textureAtlas;
    private Texture texture;
    private Sprite sprite;
    private Animation animation;
    private float elapsedTime = 0;

    @Override
    public void create()
    {
        float h = Gdx.graphics.getHeight();
        float w = Gdx.graphics.getWidth();

        batch = new SpriteBatch();
        texture = new Texture(Gdx.files.internal("image.png"));

        sprite = new Sprite(texture);
        sprite.setPosition(w/2-sprite.getWidth()/2, h/2 - sprite.getHeight()/2);
        //textureAtlas = new TextureAtlas(Gdx.files.internal("spritesheet.atlas"));
        //animation = new Animation(1/15f, textureAtlas.getRegions());
    }

    @Override
    public void resize(int width, int height)
    {

    }

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

        if(Gdx.input.isKeyPressed(Input.Keys.LEFT))
        {
            if(Gdx.input.isKeyPressed(Input.Keys.CONTROL_LEFT))
            {
                sprite.translateX(-1f);
            }else
            {
                sprite.translateX(-10.0f);
            }
        {

        if(Gdx.input.isKeyPressed(Input.Keys.RIGHT))
        {
            if(Gdx.input.isKeyPressed(Input.Keys.CONTROL_RIGHT))
            {
                sprite.translateX(1f);
            }else
            {
                sprite.translateX(10.0f);
            }
        }

        batch.begin();
        //elapsedTime += Gdx.graphics.getDeltaTime();
        //batch.draw(animation.getKeyFrame(elapsedTime, true), 0, 0);
        sprite.draw(batch);
        batch.end();

    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

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

    }
}

```

# Answer
> 0 votes
(Most) Android devices' input are from the touch screen. If that is your case, and you are trying to fetch touch events, you have two options:

1 - Poll every frame if the LEFT key is pressed. Basicly, instead of your

```
Gdx.input.isKeyPressed(Input.Keys.LEFT)

```

what you want to check is:

```
Gdx.input.isButtonPressed(Input.Buttons.LEFT)

```

From javadoc:

> boolean com.badlogic.gdx.Input.isButtonPressed(int button)
>
> Whether a given button is pressed or not. Button constants can be found in Buttons. On Android only the Button#LEFT constant is meaningful.
>
> Parameters: button the button to check. Returns: whether the button is down or not.

Libgdx kinda sees touch as "mouse clicks". Its similar if you think about it. I will explain the only difference in point 2.

The problem with this method is, it is kinda hard to do more advanced stuff. I doubt your game's only input will be touching your screen. You might want to detect swipes, for example. You can always check if the button is down and if it is, place the position in an array, but still its kinda lame and troublesome compared to the next way.

Still, if your game's input consists only of touching your screen in different positions, you can use that method and you can get the position the cursor is on by:

```
Gdx.input.getX()
Gdx.input.getY()
(Screen origin is Top-Left corner)

```

2 - Overwrite event listener methods by extending InputAdapter.

In your case, your class would be:

```
public class otherSide extends InputAdapter implements ApplicationListener

```

You can check here which methods you can overwrite: http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/InputAdapter.html

Example:

```
// Input Events
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button)
{
    //Do stuff
}

```

This method is usually better since you dont have to poll every frame if the button is pressed or not. When you touch the screen, you know that method will be called, and the parameters give you useful info about that touch.

Also, you can see an int "pointer" in the method. That is what distinguishes button clicks and android touches. That is what allows MultiTouch. Lets say you touch your screen with two fingers. Most likely, one of the finger's touch will have pointer value 0 and the second finger's touch will have pointer value 1. This way you can detect multiple touches and handle them in any way you wish. Of course, pointer is useless when you are making a Desktop game.

Ah, about the swipes, you can check here how it is done using InputAdapter: https://github.com/mattdesl/lwjgl-basics/wiki/LibGDX-Finger-Swipe#Input

That is all i believe, have fun coding :)

---
Tags: libgdx
---


# Question
Title: Swinging a sword in Xcode with Sprite Kit
I'm working on making an RPG in Xcode, and I'm having a major gameplay issue when it comes to having my character swing his sword in a way that is realistic and gameplay compatible.

Right now, when the player taps the screen and the sword is in one of the player's hand, it rotates the upright sword 90 degrees. The sword which is a parent of the player floats in front of the player because of a collision issue

I'm looking for any advice anyone can give on how to add a sword to the game and have it swing in a way that looks somewhat realistic and can damage enemies that are more than a single pixel away from the player

# Answer
> 1 votes
I think most of your problems might be solved by understanding the use of category masks. Simply set the masks to ignore contact and collision between the sword and player categories.

Specifically, this is done by assigning unsigned integers to the *categoryBitMask*, *collisionBitMask*, and *contactBitMask* properties of the **SKPhysicsBody** of the **SKSpriteNode** in question.

* *categoryBitMask* is the category of the physics body (e.g. swordCategory)
* *contactBitMask* is the product of the ORed categories of the types of nodes you want to test for contact (e.g. enemyCategory | breakableCategory | wallCategory)
* *collisionBitMask* is the product of the ORed categories of the types of nodes you want to resolve collision (e.g. enemyCategory | wallCategory)

---
Tags: collision-detection, ios, physics, xcode, spritekit
---


# Question
Title: Continous collision happening in Unity2d
I am working on Unity2d. I have a game object called `gameobject1` on screen. It holds an image (named "state"). When I drag a tree on a `gameobject1` collision is happening continuosly in the same layer instead of once. I already added Physics2Ds component `Rigidbody2D` on to tree object. Is there any solution for this issue?

# Answer
> 1 votes
You have to use OnCollisionEnter2d() method here so collision detection happen for one time only. If you want any collision detection then there is no requirement of rigidbody.

If I can't able to understand you question then ask it specifically.

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


# Question
Title: Is it possible to a create an Android game that uses the built in keyboard?
I know the keyboard is probably built into the Android OS and I have a simple game idea, sort of like a word game, but is it possible to create a game that uses this in the game itself?

# Answer
> 1 votes
Of course it is. I've only seen very few games implementing their own limited input buttons, but never a full keyboard. Based on the framework you're using this might be tricky to get it working, but overall, it shouldn't be a problem.

---
Tags: android, keyboard
---


# Question
Title: Is Table the only layout that I can use in libgdx?
I'm looking for the common way to handle the layout in libgdx. I searched google and found only table layout. Meanwhile I don't use any layout and just insert coordination into each visual object but I think that this is not the proper way to do it...
Is their any other layout that I can use?

p.s The game layout should split into two parts, left is smaller that the right and contains things like score time and info about stuff in the game. The right part will display the game-play itself

# Answer
Definitely not. `Table` is just a tool and you should use it when it fits your desired result. If your widgets are supposed to be laid out in a tabular way, then use `Table`. Otherwise, it's perfectly okay to position your widgets manually if that's what you need.

**Two alternatives to `Table`**

* HorizontalGroup: Just one example of a component made specifically for helping with with your layout. It seems to be what you are looking for.
* Two Stage instances: have one `Stage` for the game area and one for the interface. Each `Stage` will have its own camera, which means you can move the game camera around the world while the interface camera stays still. To control how large each `Stage` is and where it is positioned, read about Viewports on the LibGDX wiki.

**When positioning manually**

One piece advice, though, if you decide to position your widgets manually: don't use absolute pixel coordinates. If you your screen is 400px wide and you want a widget's X coordinate to be 200px, set it to `0.5f * screenWidth`, instead. This will allow your widgets to be position correctly, even if the screen size changes and it takes no extra effort on your part.

---

**Edit:** The `HorizontalGroup` should have two children: a `InterfaceWidget` and a `GameWidget`. The `InterfaceWidget` will have as children all the things you want to appear in the left of the screen, such as score. The `GameWidget` will be the parent of the `PlayerActor` and any other actors you have in your game.

```
HorizontalGroup
  InterfaceWidget
    ScoreWidget
    SomeOtherWidget
  GameWidget
    PlayerActor
    SomeOtherActor

```
> 3 votes

---
Tags: libgdx
---


# Question
Title: How to fix this existing shadow shader/material with alpha textures?
I hope I could get some help here in finally resolving this problem of mine re: shadow casting with alpha textures.

Here's a screenshot on what I am hoping for as a result:

A friend of mine just sent this shader program to help out but I still can't get it to work properly. The alpha textures such as leaves still leave a rectangular shadow. I'm using a custom built Ogre based engine but overall the material and compositor system is still the same.

Attachment: Alpha\_Shader.zip

Any help would be greatly appreciated.

Thanks.

# Answer
> 1 votes
To do this, you must sample your alpha texture in the depth buffer creation fragment shader, which is ShadowCasterFP in your code. When you sampled the texture, you should discard pixels below a certain alpha level, or do a clip:

```
if( color.a<0.1 )
 discard;

clip( color.a<0.1?-1:1 );
//where color is your sampled texture at the current fragment

```

These two will do the same, which is not outputting any color to your rendertarget/depthmap.

**EDIT:** You'd have to insert the above code (either the discard or the clip) to your MVSMShadows.hlsl to the beginning of the ShadowCasterFP function. But you also have to sample a texture resource and a sampler there which you must declare and upload to the GPU beforehand. You can declare a texture and a sampler like this:

```
Texture2D<float4> myTexture : register(t0); //texture bound to the first texture slot
SamplerState mySampler : register(s0); //sampler unit bound to the first sampler slot

```

Then you must sample that texture while creating the shadow map:

```
float4 color = myTexture.Sample(mySampler,In.texCoords);

```

So you have your fragment color which contains an alpha. You check that alpha and discard if it is too low with clip or discard.

---
Tags: shaders, hlsl, ogre, fragment-shader, mogre
---


# Question
Title: Passing variables down the pipeline glsl
I am sorry to post a question that may be easily tested, but I don't have an OGL4+ hardware at the moment and I have to make some design decision beforehand so I wanted a clear scenario.

Looking at various tutorial that involve tessellation shaders, each single parameter that I want to send from the texture shader to the fragment shader are before passed through tessellation shaders as well (as they always needed in the case I saw). If I have a variable that I want to send from vertex shader to the fragment one, but that's not needed by TCS and TES, can I just do something like

```
//// Vertex shader

out vec3 foo;

// Ignore foo in tessellation control and eval shader

//// Fragment shader
in vec3 foo;

```

or I have to pass `foo` through the tessellation shaders as well? I always understood the `out` variables are just being passed to the next stage, but what if the variable is not "picked" until another non-consecutive stage?

Thank you!

# Answer
> 0 votes
I'm not using a tessellation shader but I just ran a quick test trying to skip a variable past the geometry shader:

```
// vertex shader
out float foo;
//[...]
foo = 0.5;

// ignore foo in geometry shader

// fragment shader
in float foo;

```

The result was a warning and an error:

WARNING: Output of vertex shader 'foo' not read by geometry shader

ERROR: Input of fragment shader 'foo' not written by geometry shader

# Answer
> 0 votes
I think you'd have to setup a seperate program object where the shader chain doesn't have a tesselation shader, but I suppose this isn't desirable most likely.

Just simply letting the variables pass through the shader would be the best option I guess, I don't know about tesselation shaders specifically but if they're like the vertex shader a simple line of code saying something like this should suffice:

```
in vec3 inFoo;
out vec3 outFoo;

void main() {
    outFoo = inFoo;
    ...
}

```

---
Tags: opengl, glsl
---


# Question
Title: Changing the object material without clicking on it
How can I change the object material automatically without clicking on it? The object material should change based on a timer.

# Answer
> 1 votes
This is how you do it!

```
Invoke("ChangeMaterial", 2); // Time is 2 seconds

function ChangeMaterial () {
/* Change Material */
}

```

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


title: Adaptive vs progressive mesh

text:
# Question
Title: Adaptive vs progressive mesh
Is there any distinction between these two? I couldn't find anything in google under "Adaptive vs progressive mesh", but googling them both separately gives results as if they were likely the same.

# Answer
**Definitions:**

Progressive meshes: This method involves the saving of mesh as a collective structure which contains several copies of the same mesh in different LOD. In this technique, the whole of the mesh is made into one with lower resolution.

Adaptive meshes: Rather than enumerate the huge number of polygons that would be required to get an accurate discrete approximation of such a complex shape, mesh refinement techniques split the surface representation into a coarse polygonal mesh combined with a continuous displacement function. This means that you get different LOD/resolution while rendering the same mesh in the same frame according to the distance from the camera. Here's an example of Adaptive Meshes:

As you can see here in this image, the mesh is tested on each vertex for the distance from camera/ depth into scene. the portions of the mesh which are closer to the camera are rendered with high detail, while those portions away are rendered with low detail. In contrast to this,

Progressive meshes, like in this elephant image, change the whole mesh at once when the distance from camera changes.

**Thus** to summarize, Progressive meshes change resolution of the whole mesh whith distance from camera and adaptive meshes change only part of the mesh's resolution with distance, so the same mesh can have different Levels Of Detail in the same frame.

Hope that helps as a basic difference.
> 13 votes

---
Tags: mesh
---


# Question
Title: Using Behavior Trees and Events together
I am beginning to work with behavior trees and am unsure how events should be handled within the tree. Lets say we have a space game where the player is dogfighting with a handful of other ships, some friendly some not. The player destroys a ship and the rest of the hostile ships should then start to retreat.

How was should the `shipWasDestroyed` event effect the other ship's behavior trees so that they start running the retreat behavior?

One way I could think of doing this is have all the conditions I care about be high level nodes that effectively state change the ship. This would mean I'd have to check all of these state change conditions on every frame the behavior tree was run, even if they are very rare occurrences. I'd prefer not doing this for performance and complexity reasons.

From looking at the Halo papers on behavior trees it seems that they handled this by dynamically placing nodes into the tree when the event occurred. It seems like calculating where the new node should go could be problematic depending on the current state of the running behavior.

How is this normally handled?

# Answer
Behavior Trees are a great way to structure your behavior, but they can suffer from excessive "checking", as you point out. By design, a BT will jump to another branch in the tree if a higher priority behavior becomes available, so the implementation needs a way to check if that's the case.

The easiest and safest way to do it is by **polling**. The BT will reevaluate the conditions from the top until it either lands on the current node, or somewhere else. This can lead to performance issues, although it won't typically affect your complexity in the same way it would with a state machine, as in a BT you don't have to encode all the connections manually.

A more sophisticated approach is to make the BT **event-driven**. A possible implementation is that as you traverse the tree, you register observers for the conditions that aren't true (like `shipWasDestroyed`), until you find a valid node. If any of those observers triggers, you could at that point reevaluate that subtree, to see if you need to switch nodes or not. This approach requires you do to a lot of (error-prone) bookkeeping, but it can be more efficient than simple polling.

An option, somewhat **in between**, is to cluster certain events and trigger a full reevaluation when they fire. You can call that the "something interesting happened" approach. Traversing the tree then would resolve how to react to that event.

Note that in either case, you'll probably still need to do polling for things like distance checks and whatnot, so it's best to structure your tree so you can combine both approaches (and event-driven conditions are free or very cheap).

Finally, you could keep an external system and **inject** behavior like Halo. In this case, you won't be able to rely on the natural ordering of the tree, so you'll have to represent priority in a different way. This approach is valuable for reactions that should override normal behavior, like taking a hit or dying. In your case, you could have a list of behaviors with relative priorities associated that trigger based on individual events and override the tree, but be aware that as the complexity of the logic grows, you'll essentially be recreating the BT outside of the tree.
> 5 votes

# Answer
Every game has different design challenges. I would start by drawing out a flow diagram of events. A Behavior Tree typically uses high level "composite" nodes. You can then build out these "composite" nodes into sub-trees.

For instance:

```
[sequence] --> [Am I Under Attack?] --> [Flee]

```

The nodes "Am I Under Attack" and "Flee" are composite nodes. You could then build out sub-trees that define how each node works.

```
[Am I Under Attack] --> [Enemies in range?] --> [return true]

```

I would consider using both a behavior tree and a state machine to handle game state. Use the behavior tree to "sculpt" low level interactions, then set the state machine based on the result.

Like I said early, every game requires different setups. Always try the simple first approach (K.I.S.S), keep it simple stupid :)
> -1 votes

---
Tags: c#, unity, ai, behavior
---


# Question
Title: How can I draw a specific GameObject into a texture in Unity?
I need to draw only a few specific objects into a texture (with their material) and then use that `RenderTexture` as a texture for an another object. I think `Graphics.DrawMesh()` and `Graphics.SetRenderTarget()` would be helpful, but I'm not sure.

Ultimately I'm trying to create refractive water, which will refract only specified `GameObject`s, not layers. How can I do this?

# Answer
I'd probably use layers for this: put all objects that you want to reflect onto a 'Reflectable' layer. You can set the regular scene camera to render that layer like any other, but then you set the camera that renders your RenderTexture to only be able to see that layer.
> 1 votes

---
Tags: unity, graphics, rendering
---


# Question
Title: How can I ensure I still get correct touch inputs when my scene is offset?
How can I accept touch input beyond the scene's bounds, so that no matter what I set `self.position` to, touches can still be detected?

I'm creating a tile based game from Ray Winderlich on Cocos2d version 3.0. I am at the point of setting the view of the screen to a zoomed in state on my tile map. I have successfully been able to do that although now my touches are not responding since I'm out of the coordinate space the touches used to work on.

This method is called to set the zoomed view to the player's position:

```
-(void)setViewPointCenter:(CGPoint)position{
    CGSize winSize = [CCDirector sharedDirector].viewSizeInPixels;
    int x = MAX(position.x, winSize.width/2);
    int y = MAX(position.y, winSize.height/2);
    x = MIN(x, (_tileMap.mapSize.width * _tileMap.tileSize.width) - winSize.width / 2);
    y = MIN(y, (_tileMap.mapSize.height * _tileMap.tileSize.height) - winSize.height / 2);
    CGPoint actualPosition = ccp(x, y);

    CGPoint centerOfView = ccp(winSize.width/2, winSize.height/2);
    NSLog(@"centerOfView%@", NSStringFromCGPoint(centerOfView));
    CGPoint viewPoint = ccpSub(centerOfView, actualPosition);
    NSLog(@"viewPoint%@", NSStringFromCGPoint(viewPoint));

    //This changes the position of the helloworld layer/scene so that
    //we can see the portion of the tilemap we're interested in.
    //That however makes my touchbegan method stop firing
    self.position = viewPoint;
}

```

This is what the `NSLog` prints from the method:

```
2014-01-30 07:05:08.725 TestingTouch[593:60b] centerOfView{512, 384}
2014-01-30 07:05:08.727 TestingTouch[593:60b] viewPoint{0, -832}

```

As you can see the y coordinate is `-800`. If i comment out the line `self.position = viewPoint` then the `self.position` reads `{0, 0}` and touches are detectable again but then we don't have a zoomed view on the character. Instead it shows the view on the bottom left of the map.

Here's a video demonstration.

How can I fix this?

**Update 1**

Here is the github page to my repository.

**Update 2** Mark has been able to come up with a temporary solution so far by setting the `hitAreaExpansion` to a large number like so:

```
self.hitAreaExpansion = 10000000.0f;

```

This will cause touches to respond again all over! However, if there is a solution that would not require me to set the property with an absolute number then that would be great!

# Answer
> 1 votes
It appears that setting self.hitAreaExpansion might be the answer, however it only needs to be set to the difference between the edge of the view field and the edge of the map, for the largest difference on either axis.

In this case the map is square, 1600 x 1600, and the view port is 320 x 480, so the greatest distance is 1600 - 320 = 1280.

```
self.hitAreaExpansion = 1280;

```

However as this is dependent on the screen size we should probably do something like :

```
CGSize winSize = [CCDirector sharedDirector].viewSize;
int widthExpansion = (tileMap.tileSize.width * tileMap.mapSize.width) - winSize.width;
int heightExpansion = (tileMap.tileSize.height * tileMap.mapSize.height)  - winSize.height;
self.hitAreaExpansion = (widthExpansion < heightExpansion)
     ? heightExpansion
     : widthExpansion

```

Although setting a massive expansion also works just fine ;).

You may have already noted this but the root cause of the issue comes from CCNode.m, in hitTestWithWorldPos which uses hitAreaExpansion to expand the view port, which by default returns false for anything outside the physical limitations :

```
- (BOOL)hitTestWithWorldPos:(CGPoint)pos
{
    pos = [self convertToNodeSpace:pos];
    CGPoint offset = ccp(-_hitAreaExpansion, -_hitAreaExpansion);
    CGSize size = CGSizeMake(self.contentSizeInPoints.width - offset.x, self.contentSizeInPoints.height - offset.y);
    if ((pos.y < offset.y) || (pos.y > size.height) || (pos.x < offset.x) || (pos.x > size.width)) return(NO);

    return(YES);
}

```

Perhaps it would make more sense if self.position had a setter which does the math automatically assuming self is able to access the dimension of the background layer and the dimensions of the view port.

# Answer
> 0 votes
First: are you actually zooming? this looks like an offset not a zoom. A zoom changes the scale whereas an offset just changes the origin (or center if you prefer).

Second: in either case you need to adjust the touch coordinates by the same adjustment as the scene was adjusted in order to map the coordinates. (Either just a pure x/y offset or an x/y offset and a scale if you are zooming as well as changing the center).

# Answer
> 0 votes
Just worked through the tutorial by myself and came up with another solution (inspired by http://forum.cocos2d-swift.org/t/cocos2d-v3-replacement-for-cclayer/11705/3):

First I am adding all my content to a new node named ContentNode. After that, instead of moving the whole scene (which is not the right way in cocos2d 3.X because scenes are not equal to layers), I am only manipulating (i.e. translating) my ContentNode in case of touch events.

I've created a GitHub-Repository (https://github.com/danurna/TileGame) where you can clone the working tutorial code using cocos2d 3.X. Some minor changes where necessary but basically it is still the steps shown in Ray Wenderlich's tutorial.

---
Tags: cocos2d-iphone
---


# Question
Title: Unity mouse input not working in webplayer build
I have a button script with the following code

```
void OnMouseDown()
{
    animation.Play("button-squish");
    enlarged = true;
    audio.PlayOneShot(buttonSound);
}

void OnMouseUpAsButton()
{
    if (enlarged)
    {
        SelectThisButton();
        enlarged = false;

        animation.Play("button-return");
    }
}

void OnMouseExit()
{
    if (enlarged)
    {
        enlarged = false;
        animation.Play("button-return");
    }
}

```

It works great in the editor, but when I made a build and tested it in Chrome none of the buttons had any response. Further testing revealed that it did work in Firefox. Rather than telling people to change their browser if they want to play, I want to make the button code work. How else can I get the buttons to know when they're being pressed if the built-in stuff isn't working?

# Answer
> 1 votes
After switching over to 2D raycasts, it still didn't work. After selecting \[Build Settings -\> Player Settings -\> No Context Menu\] it worked.

---
Tags: unity, web
---


# Question
Title: Detect which key was pressed last each frame
Why hello there, im developing a 2D game using XNA. My character movment is currently based on the keyboard state. Example (in the right order):

```
if (state.IsKeyDown(Keys.W))
    {
          //Do stuff
    }
else if (state.IsKeyDown(Keys.D))
    {
          //Do Stuff
    }
else if (state.IsKeyDown(Keys.A))
    {
          //Do Stuff
    }
else if (state.IsKeyDown(Keys.S))
    {
          //Do Stuff
    }

```

That way I am able to deny diagonal movment. So my problem is, if "W" is pressed, meaning the character is moving up, And a frame after that while W is still pressed and I press "S" for example, It will keep moving up. I've been looking for a solution for a while and didn't come up with anything good enough. What I need help with is ideas about how to detect if a different key was pressed after W (because it is the first one to check, it doesn't check the others), while denying diagonal movment. Any help would be sincerely appreciated, Thanks in advance.

# Answer
> 2 votes
I believe you want something like the below. It will keep track of the most recently pressed key in the variable `_movementKey` and set the movement key to none when the most recent key is released.

So the end result should be \_movementKey contains the key that dictates direction, it will always be most recently pressed key and will be reset to Key.None when the most recent key is released.

```
// ######################
// non local variables
// ######################

private KeyboardState _oldState;
private Key _movementKey; //This keeps track of the key that was pressed last.
                          //It is reset to Key.None id released no matter what
                          //other keys are pressed.

// ######################
// function to update input
// ######################

var newState = Keyboard.GetState();

if (!newState.IsKeyDown(_movementKey) && _oldState.IsKeyDown(_movementKey))
{
    //If the current key that dictates the moment was released (down last
    //frame and up this frame) then set the moment key to none.
    _movementKey = Key.None;
} else {
    //Else use this if else chain to detect when a button is pressed (definition
    //of pressed being it was up last frame and is down this frame). When it
    //detects a button being pushed it sets the value of _movementKey to
    //that key;
    if (newState.IsKeyDown(Keys.W) && !_oldState.IsKeyDown(Keys.W))
    {
        _movementKey = Keys.W;
    }
    else if (newState.IsKeyDown(Keys.D) && !_oldState.IsKeyDown(Keys.D))
    {
        _movementKey = Keys.D;
    }
    else if (newState.IsKeyDown(Keys.A) && !_oldState.IsKeyDown(Keys.A))
    {
        _movementKey = Keys.A;
    }
    else if (newState.IsKeyDown(Keys.S) && !_oldState.IsKeyDown(Keys.S))
    {
        _movementKey = Keys.S;
    }
}

_oldState = newState;

// ######################
// using the input to dictate direction
// ######################

//The above code simply keeps track of which key should be dictating the
//movement. Each frame check the '_movementKey' and use it to dictate the
//movement. You could do this in the above code but I like to separate
//handling the the input into 2 parts: interpreting it and applying it.

//This applies it while the above function interprets it.
switch (_movementKey) {
    case Keys.W:
        //move up
        break;
    case Keys.D:
        //move right
        break;
    case Keys.S:
        //move down
        break;
    case Keys.A:
        //move left
        break;
    case Keys.None:
        break;
}

```

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


# Question
Title: How to use setInterval and clearInterval
I have a game that I am making and cannot seem to get the `setInterval` and `clearInterval` methods to work. When I debug it in the browser console it shows that the method is still being called over and over again. I am wondering how can I get it to **actually stop** and then **restart afterwards** without going faster than it was before (which often happens with `setInterval` and `clearInterval`). Notice that when it goes back to the menu, and you click **Start** again that the timer is running multiple times on the money. Any help is much appreciated, please take a look at this fiddle demo: http://jsfiddle.net/Xn4qT/

# Answer
> 0 votes
Your `increaseMoney` and `gameTimerEnd` variables are local variables so they only last the duration of the function they are declared in. Thus, when you try to call `clearInterval()` using them, the variables no longer exist.

The way your code is currently structured, you need those variables to be global variables (declared outside any function) and not declared within a function. This will allow the variables to exist across your different function calls.

Also, it does not make sense that you're using `setInterval()` for the `gameTimer` because you're just clearing the interval the first time it fires. Perhaps you should use `setTimeout()` instead and then you won't even have to clear it because `setTimeout()` just fires once.

---
Tags: javascript, html5, timer, html, css
---


# Question
Title: Moving multiple hingejoints based on joystick input
I'm controlling a 2D side-viewed (facing right) stickman with a joystick. The movements are fairly intuitive:

* Joystick down -\> Stickman crouches down
* Joystick up -\> Stickman stretches out
* Joystick right -\> Stickman leans forward
* Joystick left -\> Stickman leans back

The stickman consists of various rectangles, representing the limbs (legs, thighs, torso, head, upper arm, lower arm), which are connected with hinge joints.

The joint movements, based on joystick input, is defined like this:

```
//                                  xMin   xMid   xMax    yMin  yMid  yMax
        this.knee     = new Expo2(  -90,   -60,     0,   -120,  -60,    0);
        this.hip      = new Expo2(    0,    60,    90,    120,   60,    0);
        this.shoulder = new Expo2(  -90,    45,   -90,    -90,  -45,   90);
        this.elbow    = new Expo2(    0,   -60,     0,   -120,  -60,    0);
        this.neck     = new Expo2(    0,     0,   -30,     30,    0,    0);

```

`Min`/`Mid`/`Max` corresponds to the joystick axis minimum, center and maximum, respectively. The first three represent the X axis, and the next three are for the Y axis. The number is how many degrees that joint should try to hold, for that particular joystick input, relative to the starting position. For when the stick is not at the axis minimum, maximum or center, the corresponding angle is interpolated from the values, above.

**The actual problem:**

This approach works fine, when only processing the axis. If I ignore the Y-input, the stickman stretches out and crouches as expected. However, since the X axis also needs to be taken into account, there's a conflict of interest between the two.

For example, when moving the stick up, the arms should go to -90 (straight up). Now, since the stick is still center on the X axis, it wants to hold 0 degrees just as much.

Another example: When crouching the stickman tucks in his arms (sholders down, elbows up), but if leaning back, the arms should stretch out. This creates a conflict if you move the stick down and left.

**The actual question:**

Up until now, for testing purposes, I've simply averaged the two, but this is far from ideal, as a limb will rarely bend or stretch to its max, unless both axis want it to do so. Is there a different approach that might be better for what I am trying to do?

---

**Potentially viable alternative, please advice**

Instead of setting joint angles individually for each axis, I could define various stances (such as crouching, stretching, idling, leanback, leanforward) and place them in a coordinate system representing the joystick. When the stick is moved, the final stance is determined by the stances closest to the stick position, with others that are relatively close also having an effect. These coordinates can be defined as `Vector2` seeing as this is done in AndEngine, but basically, just a `float` pair.

For the sake of this example, let's presume that the stick is moved 75% to the upper left corner. How would i pick the three closest stances (which would be stretch, leanback, and idle), and weight their joint states based on how close that stance is to the stick position? In this case, it should be equally as stretching as leaning back, but with a little influence of the idle position as well, seeing as the stick isn't all the way out.

# Answer
I spent a day refactoring and trying the approach listed as Potentially Viable above, and it worked!

Basically, it functions like this:

* I made a Class named Stance, which defines an angle for all of the joints. The class also has a Vector2 coordinate, corresponding to a position on the joystick.
* A class named StanceMap keeps track of all of the stances (an arbitrary amount can be added to allow for more accuracy. I'm using 9. 8 around the edge of the joystick, and one in the center
* When it's time to set the joint positions based on the joystick, the StanceMap picks the three closest stances, and weighs their input based on their distance to the stick position.
* The joint-state for those three stances are then summed (after adjusting for the calculated weight)

This has the advantage of simply adding an intermediate stance between the stance you're trying to achieve and a semi-close stance ruining the setup. This will result in the offending stance not being included when looking up the three stances.
> 0 votes

---
Tags: physics, input, joystick
---


# Question
Title: Work flow for modelling a city(open world)
This seems like a massive task, do each individual building/object have to be modeled individually. If so are the model imported into the world editor and places accordingly.

Or are other techniques used like laser scanners, GPS google maps data, or whatever, it just seems to big a task to model a whole city, model after model.

Can somebody give me an idea or how it is done and a typical team size/day for a modeler?

# Answer
> 1 votes
It depends, if you want to build a city you can either do so procedurally (which also allows endless regeneration) or you can do so manually. But even if you do so manually you will likely want to duplicate a lot of things, for example you probably don't want to model each lamppost individually but instead keep one model for all of them. You can do the same for entire building especially when you copy over a building and then make some small changes (change the number position of tables in the houses ext).

But no matter how you do this you will have to model every object.

A good system if you want to do this procedurally is by first generating a region map (this part is rich this part is poor industry goes here and shops there). Then one you know what region you are in creating a road map. You can then divide the free regions in areas where buildings go and then look into a folder with different buildings you have created, each building in this folder should contain regions and parameters for where various objects inside the building can go (and maybe even make the buildings slightly dependent on the space they occupy so that a 2 by 3 version of the building is slightly different but still generated from the same basis as the 3 by 3 building). You then add is details to the streets and maybe some people and you are done.

Be warned that if not carefully managed a procedural city can end up feeling very bland. To prevent this apply the following techniques:

1 many different types of regions, to somewhat offset the cost of this remember that you reuse some of your old buildings.

2 a great deal of variation between regions (and maybe between streets). This can be the simple things like changing street lights or by making different cars stand in different regions (what is a Ferrari doing in the poor part of town?)

3 some uniqueness to regions, allow buildings/objects that normally shouldn't be that this can create a feel that something is going on here, maybe that is and old factory standing near the rich part of town, maybe that Ferrari standing in the poor part of town really does belong there (just a lot fewer then in the rich part).

Manually you will likely want to follow the space steps but instead of having a computer do it you do it.

---
Tags: 3d, models, 3d-meshes, map-editor
---


# Question
Title: LibGDX - Textures rendering at wrong position
Update 2:

Let me further explain my problem since I think that i didn't make it clear enough: The Y-coordinates on the bottom of my screen should be 0. Instead it is the height of my screen. That means the "higher" i touch/click the screen the less my y-coordinate gets. Above that the origin is not inside my screen, atleast not the 0 y-coordinate.

Original post:

I'm currently developing a tower defence game for fun by using LibGDX. There are places on my map where the player is or is not allowed to put towers on. So I created different ArrayLists holding rectangles representing a tile on my map. (towerPositions)

```
for(int i = 0; i < map.getLayers().getCount(); i++) {
            curLay = (TiledMapTileLayer) map.getLayers().get(i);

            //For all Cells of current Layer
            for(int k = 0; k < curLay.getWidth(); k++) {
                for(int j = 0; j < curLay.getHeight(); j++) {
                    curCell = curLay.getCell(k, j);

                 //If there is a actual cell
                if(curCell != null) {
                    tileWidth = curLay.getTileWidth();
                    tileHeight = curLay.getTileHeight();
                    xTileKoord = tileWidth*k;
                    yTileKoord = tileHeight*j;

                    switch(curLay.getName()) {

                     //If layer named "TowersAllowed" picked
                    case "TowersAllowed":
                        towerPositions.add(new Rectangle(xTileKoord, yTileKoord,  tileWidth, tileHeight));

// ... AND SO ON

```

If the player clicks on a "allowed" field later on he has the opportunity to build a tower of his coice via a menu. Now here is the problem: The towers render, but they render at wrong position. (They appear really random on the map, no certain pattern for me)

```
for(Rectangle curRect : towerPositions) {
            if(curRect.contains(xCoord, yCoord)) {

                //Using a certain tower in this example (left the menu out
                if(gameControl.createTower("towerXY")) {

                    //RenderObject is just a class holding the Texture and x/y coordinates
                    renderList.add(new RenderObject(new Texture(Gdx.files.internal("TowerXY.png")), curRect.x, curRect.y));
                }
            }
        }

```

Later on i render it:

```
game.batch.begin();
    for(int i = 0; i < renderList.size() ; i++) {
        game.batch.draw(renderList.get(i).myTexture, renderList.get(i).x, renderList.get(i).y);
    }
game.batch.end();

```

regards

# Answer
This is a well-known feature of libGDX: the Y-axis has 0 at the bottom of the screen, not the top. (This is to be more consistent with 3D coordinate systems, which do likewise.)

There are a couple of ways to "fix" this.

1. Use a camera. You can transform the view.
2. In your `render` method, calculate the Y position as `screen.height - y - sprite.height`. This is easier, and often, faster.

NB: I spent about two days trying the camera method last week, and it seems to draw inverted. I recommend the second option. You can get the screen height from `Gdx.graphics.getHeight()`, and the sprite height from the `Texture` instance.
> 1 votes

---
Tags: java, textures, libgdx
---


# Question
Title: How to detect collision on specific part of the sprite node
I have a spike and a ball is falling down, when the ball touches the top point of the spike, I want to make the ball invisible, and when it touches on the other part i.e on the sides I don't want to make it invisible.

I have two sprite nodes - Ball and spike.

How can I make the collision detect only on specific part i.e only on top of the spike in spritekit?

# Answer
> 6 votes
Remember that SpriteKit's physics system is based on "SKPhysicsBody"s, which are added to "SKSpriteNode"s. Those physics bodies, however, needn't be attached to visible nodes.

The simplest method is to create a *SpriteNode* with no actual sprite or visible body, add it as a child to the area you want on the visible shape, and categorize it differently from the visible body.

In your specific case, create a tiny node, add it to the "Triangle", position it at the top, and treat it as a separate category with a different contact behavior for the "Circle". In that contact method, you define the unique contact behavior you desire (whether you want to lower the alpha, set the alpha to 0, remove the "Circle" from the scene, or any other form of "invisibility" appropriate to your situation).

# Answer
> 0 votes
I'm just learning SpriteKit myself, however I think the following would be faster:

```
- (BOOL)checkCollisionForSpikePoint:(GCPoint)spikePoint
                         ballCenter:(CGPoint)ballCenter
                         ballRadius:(CGFloat)ballRadius
{
    CGFloat hypotenuse = sqrt(exp(spikePoint.x-ballCenter.x,2) + exp(spikePoint.y-ballCenter.y,2));
    return hypotenuse < ballRadius;
}

```

Call this in your collision handler and pass it the relevant info (the point representing the tip of the spike, the point representing the center of the ball, and the radius of the ball). It will return a BOOL indicating if the tip of the spike rests inside the ball.

This is extremely fast (and admittedly untested) code and doesn't add any new nodes to the scene.

---
Tags: collision-detection, ios, physics, xcode, spritekit
---


title: GLSL - one-pass gaussian blur

text:
# Question
Title: GLSL - one-pass gaussian blur
It is possible to implement fragment shader to do one-pass gaussian blur? I have found lot of implementation of two-pass blur (gaussian and box blur):

and so on.

I have been thinking of implementing gaussian blur as convolution (in fact, it is the convolution, the examples above are just aproximations):

http://en.wikipedia.org/wiki/Gaussian\_blur

# Answer
Yes, you *can* implement Gaussian blur in one pass, by sampling all n^2 pixels in the kernel (for kernel width n). It's usually *faster* to run it on the rows and columns in two passes, since then you have O(n) pixels to sample rather than O(n^2). This is not an approximation, since Gaussian blur is mathematically separable.
> 37 votes

# Answer
The trick for rapid Gaussian blurring with GLSL is to take advantage of the fact that the GPU provides linear interpolation in hardware. Therefore, you can effectively sample four 2D pixels with a single prefetch or eight 3D voxels. By deciding where to sample you can weight the output. The definitive reference is Sigg and Hadwiger's "Fast Third-Order Texture Filtering" which you can find online.

For a readable explanation find the web page "Efficient Gaussian blur with linear sampling". As noted, since the Gaussian blur is separable with wide kernels it is most efficient to do one pass per dimension.

However, you can also use this trick to approximate a Gaussian with a tight kernel in a single pass. In the example below I emulate the 3D kernel with the top slice = \[1 2 1; 2 4 2; 1 2 1\]; middle slice = \[2 4 2; 4 8 4; 2 4 2\]; bottom slice = \[1 2 1; 2 4 2; 1 2 1\]. By sampling +/-0.5 voxels in each dimension you do this with just 8 texture fetches rather than 27. I am demonstrating this in GLSL as a MRIcroGL shader file - just drop save the script below as "a.txt" and place it into MRIcroGL's "Shader" folder. When you relaunch the program you will see your ray cast image blurred. Clicking the "doBlur" checkbox toggles the blurring on and off. Using my integrated Intel GPU in my laptop and the "chris\_t1" image that comes with MRIcroGL I get 70fps without blurring (1 texture fetch) and 21fps with blurring (8 fetches). Most of the code is just a classic ray caster, the "doBlur" conditional encapsulates your question.

//-------a.txt file follows

```
//pref
doBlur|bool|true
//vert
void main() {
    gl_TexCoord[1] = gl_MultiTexCoord1;
    gl_Position = ftransform();
}
//frag
uniform int loops;
uniform float stepSize, sliceSize, viewWidth, viewHeight;
uniform sampler3D intensityVol;
uniform sampler2D backFace;
uniform vec3 clearColor;
uniform bool doBlur;
void main() {
    // get normalized pixel coordinate in view port (e.g. [0,1]x[0,1])
    vec2 pixelCoord = gl_FragCoord.st;
    pixelCoord.x /= viewWidth;
    pixelCoord.y /= viewHeight;
    // starting position of the ray is stored in the texture coordinate
    vec3 start = gl_TexCoord[1].xyz;
    vec3 backPosition = texture2D(backFace,pixelCoord).xyz;
    vec3 dir = backPosition - start;
    float len = length(dir);
    dir = normalize(dir);
    vec3 deltaDir = dir * stepSize;
    vec4 colorSample,colAcc = vec4(0.0,0.0,0.0,0.0);
    float lengthAcc = 0.0;
    float opacityCorrection = stepSize/sliceSize;
    //ray dithering http://marcusbannerman.co.uk/index.php/home/42-articles/97-vol-render-optimizations.html
    vec3 samplePos = start.xyz + deltaDir* (fract(sin(gl_FragCoord.x * 12.9898 + gl_FragCoord.y * 78.233) * 43758.5453));
    //offset to eight locations surround target: permute top/bottom, anterior/posterior, left/right
    float dx = 0.5; //distance from target voxel
    vec3 vTAR = vec3( dx, dx, dx)*sliceSize;
    vec3 vTAL = vec3( dx, dx,-dx)*sliceSize;
    vec3 vTPR = vec3( dx,-dx, dx)*sliceSize;
    vec3 vTPL = vec3( dx,-dx,-dx)*sliceSize;
    vec3 vBAR = vec3(-dx, dx, dx)*sliceSize;
    vec3 vBAL = vec3(-dx, dx,-dx)*sliceSize;
    vec3 vBPR = vec3(-dx,-dx, dx)*sliceSize;
    vec3 vBPL = vec3(-dx,-dx,-dx)*sliceSize;
    for(int i = 0; i < loops; i++) {
        if (doBlur) {
            colorSample = texture3D(intensityVol,samplePos+vTAR);
            colorSample += texture3D(intensityVol,samplePos+vTAL);
            colorSample += texture3D(intensityVol,samplePos+vTPR);
            colorSample += texture3D(intensityVol,samplePos+vTPL);
            colorSample += texture3D(intensityVol,samplePos+vBAR);
            colorSample += texture3D(intensityVol,samplePos+vBAL);
            colorSample += texture3D(intensityVol,samplePos+vBPR);
            colorSample += texture3D(intensityVol,samplePos+vBPL);
            colorSample *= 0.125; //average of 8 sample locations
        } else
            colorSample = texture3D(intensityVol,samplePos);
        colorSample.a = 1.0-pow((1.0 - colorSample.a), opacityCorrection);
        colorSample.rgb *= colorSample.a;
        //accumulate color
        colAcc = (1.0 - colAcc.a) * colorSample + colAcc;
        samplePos += deltaDir;
        lengthAcc += stepSize;
        // terminate if opacity > 95% or the ray is outside the volume
        if ( lengthAcc >= len || colAcc.a > 0.95 ) break;
    }
    colAcc.rgb = mix(clearColor,colAcc.rgb,colAcc.a);
    gl_FragColor = colAcc;
}

```
> 8 votes

---
Tags: glsl, fragment-shader, blur
---


# Question
Title: How to properly generate walls simulating perspective around stone in a cave-like level made of squares?
Long story short. My levels tiles currently look like this:

And i want them to look like this:

My levels are designed as 400x400 squares of proceduraly generated 0's and 1's, 0 representing dirt(walkable by player), 1 represeting stone(impenetrable). Game itself looks a lot like **this**.

At first, my method was to run another loop - after generating the world that **replaced stone** tiles, depending on directions of empty tiles were, with wall. The method doesn't work so bad up to the point where there are 1 wide walls sticking out, which are impossible for it to convert, check picture:

As you can see, in my method, the wall is an another texture, taking one tile itself. I can't replace air with walls, as that could possibly obstruct a passage. It basically fails every time there are 3 or more dirt tiles directly next to it.

This is the place at which i wondered if i chose the right method or if i should change the whole design for the walls, if so - to what? Should i create some textures for the 1-wides alone? Or maybe i shouldn't generate 1-wides at all? How do games generally deal with this?

I've looked for the answer to my problem, and haven't found it. Probably because it's hard for me to word it(sorry for messy post).

# Answer
While it might not be ideal or the most performant option depending on your actual use case, you could just create a single "3d tile" that is actually bigger than your real tile (due to having the 3d part attached):

While the tile size would be 32 × 32 pixels, this tile image is actually 40 × 40 pixels big (the fake depth is 8 pixels in every direction).

When rendering, you just render the tiles from left to right, top to bottom, with the tile's delta (in this example 32 pixels).

For example, to render a "T", you'd render the tiles in the following order:
> 1 votes

---
Tags: 2d, procedural-generation, level-design, levels, perspective
---


title: HLSL - Voxel texturing

text:
# Question
Title: HLSL - Voxel texturing
I'm currently trying to develop a Voxel Engine using Direct3D 9 and C++. To keep the memory usage low, i'm only passing the position, the orientation and the offset of the current voxels texture in the texture atlas of each vertex to the vertex shader.

The vertex shader then calculates the normal and passes it to the pixel shader. I found this article which covers, how to texture voxels with just their position and normal in glsl.

This is the part that calculates the texture coordinates in my pixel shader (SM3):

```
float2 tileUV = float2(dot(input.normal.zxy, input.pos3D),
    dot(input.normal.yzx, input.pos3D));
float2 texcoord = input.texOffset + tileSize * frac(tileUV);

```

This code works fine for faces that point in negative z-direction (normal \[0,0,-1\]), however, the back is flipped by 180° and the sides and top/bottom squares are flipped by 90°/270°.

I am not sure, if this is correctly translated from glsl, because this behaviour should be the expected one in hlsl, if I calculate it by hand. Is there anything that I have overseen or should I aim for a different approach?

Edit:

I have now managed to successfully texture the faces by replacing the previous calculation with the following:

```
if(input.normal.y != 0.0f) // handle top/bottom surfaces as front/back faces
{
    input.pos3D.y = input.pos3D.z;
    input.normal.z = -input.normal.y;
    input.normal.y = 0.0f;
}
texcoord.x = input.texOffset.x + tileSize * frac(float3(1.0f, 1.0f, 1.0f) +   cross(frac(input.pos3D), input.normal)).y;
texcoord.y = input.texOffset.y + tileSize * (1.0f - frac(input.pos3D.y));

```

Is there any way that I can simplify/optimize the equation? I may also mention that the voxels are all axis aligned and clamped to integer coordinates.

Edit2:

This is the modified formula of zogi's answer which works as expected.

```
float3 n = abs(normal.xyz);
float2 texcoord = float2(input.texOffset.x + tileSize * dot(n, frac(input.pos3D.zxx)),
    input.texOffset.y + tileSize + tileSize * dot(-n, frac(input.pos3D.yzy)));

```

# Answer
The first formula you mentioned is not suitable for the result you want to achieve. I suggest the following formula instead:

```
float3 n = abs(input.normal.xyz);
float2 tileUV = float2(dot(n,  input.pos3D.zxx),
                       dot(-n, input.pos3D.yzy));

```

The `n` vector basically selects the side of the cube, as exactly one coordinate is 1, the others are 0. Because the origin in texture coordinate space is at the top left corner of the texture in DirectX, while it is at the bottom left in OpenGL, the second texture coordinate has to be negated.
> 2 votes

---
Tags: textures, hlsl, voxels
---


title: HLSL 5.0 vector interpolation issues

text:
# Question
Title: HLSL 5.0 vector interpolation issues
I'm having issues with the depth components of my shadowmapping shaders. The shadow map rendering shader is fine, and works very well. The world rendering shader is more problematic. The only value which seems to definitely be off is the pixel's position from the light's perspective, which I pass in parallel to the position.

```
struct Pixel {
    float4 position : SV_Position;
    float4 light_pos : TEXCOORD2;
    float3 normal : NORMAL;
    float2 texcoord : TEXCOORD;
};

```

The reason that I used the semantic 'TEXCOORD2' on the light's pixel position is because I believe that the problem lies with Direct3D's interpolation of values between shaders, and I started trying random semantics and also forcing linear and noperspective interpolations.

In the world rendering shader, I observed in the pixel shader that the Z value of light\_pos was always extremely close to, but less than the W value. This resulted in a depth result of 0.999 or similar for every pixel.

Here is the vertex shader code :

```
struct Vertex {
    float3 position : POSITION;
    float3 normal : NORMAL;
    float2 texcoord : TEXCOORD;
};

struct Pixel {
    float4 position : SV_Position;
    float4 light_pos : TEXCOORD2;
    float3 normal : NORMAL;
    float2 texcoord : TEXCOORD;
};

cbuffer Camera : register (b0) {
    matrix world;
    matrix view;
    matrix projection;
};

cbuffer Light : register (b1) {
    matrix light_world;
    matrix light_view;
    matrix light_projection;
};

Pixel RenderVertexShader(Vertex input) {

    Pixel output;

    output.position = mul(float4(input.position, 1.0f), world);
    output.position = mul(output.position, view);
    output.position = mul(output.position, projection);

    output.world_pos = mul(float4(input.position, 1.0f), world);
    output.world_pos = mul(output.world_pos, light_view);
    output.world_pos = mul(output.world_pos, light_projection);

    output.texcoord = input.texcoord;
    output.normal = input.normal;

    return output;
}

```

I suspect interpolation to be the culprit, as I used the camera matrices in place of the light matrices in the vertex shader, and had the same problem. The problem is evident as both of the same vectors were passed to a pixel from the VS, but only one of them showed a change in the PS.

I have already thoroughly debugged the matrices' validity, the cbuffers' validity, and the multiplicative validity. I'm very stumped and have been trying to solve this for quite some time.

Misc info : The light projection matrix and the camera projection matrix are the same, generated from `D3DXMatrixPerspectiveFovLH()`, with an FOV of 60.0f * 3.141f / 180.0f, a near clipping plane of 0.1f, and a far clipping plane of 1000.0f.

Any ideas on what is happening?

# Answer
Turns out, the depth values were correct the whole time. I was looking at a bad image for reference, where objects would get darker as they got further away from you. Of course, this is completely incorrect.

After seeing how crazy normal depth precision is, I decided to use my own linear depth, which worked much better for shadow mapping.
> 0 votes

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


# Question
Title: Trying to understand the XNA fixed time step game loop logic
I came across the blog post Understanding GameTime, and after lots of reading on fixed time steps in game loops this is the approach I would like to take. In summary, this is the logic from the post:

1. Set the desired time spent in Update + Draw as 1/60 of a second (fixed 60 fps).
2. If time elapsed since last Update + Draw is exactly 1/60 of a second:

* Call Update
    * Call Draw
    * Tick (Game loops.)
3. If time elapsed since last Update + Draw takes less than 1/60 of a second:

* Call Update
    * Call Draw
    * Look at the Clock (Time left over? Wait.)
    * Tick (Game loops.)
4. If time elapsed since last Update + Draw takes more than 1/60 of a second?

* Call Update (Until we catch up.)
    * Call Draw
    * Tick (Game loops.)

I guess the two parts I'm having trouble understanding is in #3, how would the waiting be accomplished since thread sleeps are often not accurate enough, and what does it mean in #4 to call update until we catch up? Catch up to what since the time elapsed is already greater than our target 60 fps?

# Answer
> 0 votes
> I guess the two parts I'm having trouble understanding is in #3, how would the waiting be accomplished since thread sleeps are often not accurate enough?

Can't answer this for sure as I haven't seen the XNA source code.

MonoGame uses thread.sleep

```
// NOTE: While sleep can be inaccurate in general it is
// accurate enough for frame limiting purposes if some
// fluctuation is an acceptable result

```

From my understanding `System.Diagnostics.Stopwatch` is likely the highest resolution timekeeping utility you have access to as a part of .net.

> What does it mean in #4 to call update until we catch up? Catch up to what since the time elapsed is already greater than our target 60 fps?

Lets say each |----| is a 60hz tick. * is when update is actually called. For some reason a first update took way to long (perhaps it loaded a bunch of new stuff). Basically all 4 is saying is its going to call update as fast as possible with no waiting until the number of times update has been called has caught up to the number of times it ought to have been called optimally .

```
*       *    *    *    *   *   *   *<---- Caught up here
|----|----|----|----|----|----|----|
0    1    2    3    4    5    6    7

```

---
Tags: xna, game-loop, fixed-timestep, timestep
---


# Question
Title: Should character actions be considered states?
So I've been on a team that has been working on a game for quite a few months now and we're hitting some really nasty bloat problems with our character actions.

Question in bold. Accompanying information below it.

**For complex character actions with concurrency of other actions, how would I end up refactoring our current system (see below) using a HSM. As what I've done so far poses concurrency issues.**

We currently have these 'states/actions' for the characters.

* Idle
* Running/Movement
* Attacking
* Jumping
* Falling
* Attacking While Jumping
* Attacking While Falling
* Movement While Jumping
* Movement While Falling
* and more...

We started using a FSM to keep track of all the states for the character, but it's become massive and unmanageable. When we create a new action that can only execute based on some pre-requisites and/or causes current states to be changed, we have to make sure we check all the states.

Here is a small piece of code from our movement code that tries to determine if the character should move into an idle state.

```
    if (CurrentPosition == PreviousPosition &&
            animator != null &&
            mState.CurrentHas(StateFlags.Landed) == false &&
            mState.CurrentHas(StateFlags.InAir) == false &&
            mState.CurrentHas(StateFlags.Attacking) == false &&
            mState.CurrentHas(StateFlags.Stunned) == false &&
            mState.CurrentHas(StateFlags.Hurting) == false &&
            mState.CurrentHas(StateFlags.Falling) == false &&
            mState.CurrentHas(StateFlags.FallingNonJump) == false &&
            mState.CurrentHas(StateFlags.Charging) == false &&
            mState.CurrentHas(StateFlags.Idle) == false)
        {
                mState.Add(StateFlags.Idle);
                animator.AddToQueue(idleAnimation);
        }

```

Clearly this is smelly, ugly, and I know there are better ways. I've been trying to refactor into a HSM (which I don't believe I am doing correctly).

Here is an excerpt.

```
public interface UnitState
{
void Update(UnitStateBehavior usb);
void Enter(UnitStateBehavior usb);
void Exit(UnitStateBehavior usb);
}

public class IdleState : UnitState
{

public IdleState()
{

}

public void Update(UnitStateBehavior usb)
{
   // Can run while idle (move)
   // Can attack while idle
   // Can jump while idle
}

public void Enter(UnitStateBehavior usb)
{

}

public void Exit(UnitStateBehavior usb)
{

}
}

```

I feel like I'll start to run into concurrency issues with other actions, such as in the above mentioned list. If I am jumping and start to attack, I'll play my attack animation and do other appropriate things that deal with now being in an attack state. However when the attack is over, what then? I could still be 'jumping' or increasing in Y, or 'falling' decreasing in Y. What if I've hit the ground while in the middle of an attack, I'd need to then go into an idle state and play its animation among other things. Nearly any action and be combined with another at any time dependent on user input. From all I've read about HSM I thought it would be the best decision, but I'm lacking in knowledge of proper implementation.

**My implementation based off Aludor's Conversation**

Instead of thinking of a stack of states as a literal stack, I bent it to be more of a collection of states, but still sticking mostly to a stack implementation. First in, last out.

I have an Actor class which keeps a reference to a StateCollection class. This StateCollection class keeps a list of states, with various methods for manipulating the list. Peek, Pop, Push, Remove, Replace, Clear. In-addition to manipulating the list, it offers methods for updating the states. FixedUpdate, Update, LateUpdate, for the various states of the game loop.

Each state derives from an abstract class UnitState. The UnitState holds methods for FixedUpdate, Update, LateUpdate, Enter, and Exit. This base class also keeps a reference to the Actor which owns it. The Actor also keeps a list of valid states for that particular Actor type.

Now when input is received by the Actor it is passed onto the StateCollection. This input is then traversed 'down' the stack. The input is consumed by the first state that uses it, so conflicting states do not act on the same input.

Each time a state is pushed to or removed from the stack the appropriate Enter/Exit method is called. Overall, this allows me to fully remove states, replace states (such as turning a jump into a fall), and allows states to run concurrently.

# Answer
What if implementing the HSM with a stack of states for each entity you have in the game?

```
public final class StateStack {
    private List<State> states = new List<State>();

    public void PushState(State newState) {
        states.Add(newState);
    }

    public State PopState() {
        State topmostState = null;
        if (states.Count > 0) {
            int lastIndex = states.Count - 1;
            topmostState = states[lastIndex];
            states.RemoveAt(lastIndex);
        }
        return topmostState;
    }
}

```

I guess the biggest problem you are facing is, the interface lacks certain ways to retrieve previous states of entities, right? Let's say, the character first jumps into the air and then swings his sword before landing, you will have a stack of states in the following order:

1. Idle
2. Jump
3. Attack

Where (1) is the state at the bottom of the stack.
> 1 votes

# Answer
First off, I think you should clearly define which are the states of your character and what are just actions that can be executed but don't change the state of the player. For instance, running is a state. But I wouldn't consider using a potion a state, just an action that affects the character in some way.

Usually I would consider attacking an action and not an state, but if your gameplay requires you to define it as an state (as in attacking is a different state that the player can be in), then you need to consider its relationship with other states.

What I understand from your question is that you don't know how to transition from "jumping" to "attacking" and then back. In that case you have two conditional transitions out of attack. For instance, in one branch, you transition to jump if the character is not touching the ground, otherwise you transition to idle. I would also consider defining a different state "jump\_attack" to use while jumping instead of just a generic attack.
> 0 votes

---
Tags: state, character, behavior, fsm
---


# Question
Title: Mathematics of difficulty acceleration in endless runners
I'm currently working on an endless runner and was wondering about the growth of difficulty in the game. Is the acceleration of difficulty highly specific to games or are there standard growth functions that most endless runners adhere to and fine tune above and beyond that?

# Answer
> 3 votes
The difficulty of an endless runner is dependent on a few things, first of all the size of the obstacles and different types of obstacles, typically it's best to just hardcode when different obstacles can appear and use a formula for sizes (especially when you can only use a given dodge ability for a certain amount of time).

A good formula for the size of obstacles is \[time you can use ability to dodge\]*\[speed\]*(1-(\[scaling constant\])^\[time\]) or d\*v\*(1-C^t) remember that the scaling constant (C) must be between 0 and 1. This will create a difficulty scaling that always starts easy but moves to more and more difficult never becoming impossible.

Second scale is speed, moving faster means having less time to react means a more difficult game, here a less complicated formula is needed and this can be done fairly linearly (or a similar formula, maybe a root experiment here).

Third is number of obstacles, note that speed also increases number of obstacles, a good way of determining whatever or not to create an obstacle is to first determine the minimal distance theoretically required between obstacles, this is likely to be the time needed to complete an animation between key release and key press for next dodge ability and then multiplied by speed to get a distance (or just use raw time). You can then generate a random value and if it' s smaller then (1-C^t) you generate a obstacle here (and reset the minimal distance until after the obstacle).

Of course you don't have to scale all 3 things at the same time (doing so makes for a very fast phased game). Each of these methodes will likely feel somewhat smooth (if you get the parameters right, especially C which you might want to start with something like 0.99 just to see how it behaves and maybe plot it on wolfram alpha and look at what values it is at given time points (maybe scale time accordingly)).

# Answer
> 0 votes
From what I've seen it depends on the target audience of your game and your content.

For example Flappy Bird has almost no content, with an insane difficulty level and no difficulty growth. It's meant to appeal to persons who want to have fun trying something difficult as a quick time sink.

However if you're building something like an adventure game with loads of beautiful content the game might start out easy and never get much harder except for the learning of new tricks every once in a while. Most of the enjoyment comes from experiencing the game.

The games in between usually have the biggest difficulty growth curves. You can have split content or achievements, and increase the difficulty level between them. You'd start out real easy to get them hooked on the game play, and increase the difficulty real slowly too to get them hooked on receiving the rewards (new content, achievements). Only towards your last good rewards will you increase the difficulty more steeply, to really make it a challenge to get those last rewards. After that it's just high scores, so you could increase the difficulty linearly, or superlinearly if you hate your players ;)

Note that the only difference here between an adventure side scroller and an infinirunner is that there's no stop between level transitions, and they can forever keep on playing after the last level.

The only way to make the game predictably good is by having it play tested, often and always by new persons that are in your target audience. They'll let you know if they feel your game is too easy or too hard, and if it gets boring at all. Ask questions like if they ever give up because it's too hard whether they're going to pick it up later and try again.

---
Tags: game-design, game-mechanics, cocos2d-iphone
---


# Question
Title: filling the empty spaces in a certain region in a grid using c++
Hi guys i am struggling to find the optimal way to fill the grid of a certain region.

In the above example lets say my player is at (7,5) and traveled (2,0) and i have the information of all the points he went through. for example: (7,5)-\>(6,5)-\>(4,5)-\>(4,4)-\>(4,3)-\>(3,3)-\>(2,3)....(2,0).

Here what i want to do is fill in either top side of the path with some color and bottom path with some other color.

and same goes for the other cases as well if player travels from (7,3)-\>(5,0) i want to color the insides with one color and out sides with another.

can any body explain me the logic to do this in c++ please thank you.

i went through that flood filling but not sure how to implement that for this one :( .

# Answer
> 0 votes
An easy way to do this if your tiles are objects is to set a bool for whether a tile has been visited, which you trigger when the player coords match a "visitable" tile's. Then at render time you can go through your tileList and make any bulk actions to all tiles which have been visited or not.

---
Tags: c++
---


# Question
Title: Hash Distance & Angle To Produce Unique Value
I have many vertices drawn on my Unity3d C# application window (thousands). I am attempting to come up with a fast way to detect which vertex has been clicked.

My idea is to use a sorted list. The list will be ordered by a vector/vertices distance to (0,0,0):

```
List <KeyValuePair<double, GameObject>> vectorMap = new List <KeyValuePair<double, GameObject>>();

```

I use a binary search to order, search and add to the list.

Add/Insertion Method:

```
public void recordElementVertices(Element ele) {
    // Element is a Sub-Class of GameObject

    foreach (Vector3d v in ele.WorldVertices) {
        double distFromZero = Vector3d.Distance(Vector3d.zero, v);

        int index = -1;
        if (Algorithms.LowerBounds(vertexDistanceList, distFromZero, out index, DEF_PRECISION) != Algorithms.SearchResult.FOUND_TARGET)
            vertexDistanceList.Insert(index, new KeyValuePair<double, List<GameObject>>(distFromZero, new List<GameObject>()));

        vertexDistanceList[index].Value.Add (ele.gameObject);
    }
}

```

Hit Test (Search) Method:

```
public List<GameObject> hits(Vector3d mousePos) {

    int     index           = -1;
    double  distFromZero    = Vector3d.Distance(Vector3d.zero, mousePos);

    // Binary search will search for an exact hit or find the closest vertex to the mouse pos
    if (Algorithms.BinarySearch(vertexDistanceList, distFromZero, out index, DEF_PRECISION) == Algorithms.SearchResult.FAIL || index < 0)
        return null;

    return vertexDistanceList[index].Value; // return all game objects that occupies that vector position
}

```

This all works nicely and is fast but there is a major flaw. The algorithm doesn't take into account the vertices angle from (0,0,0). So 2 points that are the exact same distance from (0,0,0) but have different angles will be considered the same vertex when they are not.

For example; these 2 points lie 5 metres from (0,0,0) but have different angles. My algorithm will consider these 2 points as occupying the same place in space when they are in a completely different position.

Do you have any suggestions how I can hash a distance and angle to produce a unique result that describes that point in space? Some simple like doing **Distance ^ Angle** could produce a unique result but they would also produce huge numbers. A restriction is that my list sorting algorithm requires that two points close to each other should produce a hash that is similar in order to find points close to the mouse position. Hope that makes sense.

I've heard about Locatily Sensitve Hashing but it looks like implementing this algorithm would be very tricky.

Any advice would be greatly appreciated.

# Answer
> 1 votes
The question you ask is ill posed: the problem is you are trying to map from a fundamentally 2 dimensional data set (positions on the screen) to a 1 dimensional data structure (your list). Binary search does not work in two dimensions, regardless of the mapping or hash. This is because for any potential hash, we can find points that are nearby in space but arbitrarily far away in the ordering. There exist ways to hash points using space filling curves so that nearby points *tend* to be near each other, but this isn't strong enough for what you need. Further, even with these solutions, binary search won't do what you need.

Thousands of points should be no problem for a properly written search loop to just linearly scan through all the possibilities, especially because your application does this at most once per frame. (You wouldn't want this if it was used for sight of many AI agents, for example.) If your points change every frame, then the fastest solution is to just a linear scan, because the cost of building any data structure will be at least what it costs to do the brute force search, and you will only use the structure once.

If you have a very large number of points (100,000+), then what you need is a proper space partitioning data structure, specifically a grid or a quadtree. These data structures are very well covered elsewhere. Basically rather than a list, you would store your points in one of these structures, and then make your queries using the nearest neighbor lookup function from that data structure.

---
Tags: algorithm
---


# Question
Title: Fixing game loop to 60fps makes animation very jittery
ns is 1000000000 / amountOfTicks;

```
    long now = System.nanoTime();
    delta += (now - lastTime) / ns;
    lastTime = now;

    if (delta >= 1) {
        tick(glad);
        updates++;
        delta--;
        fps_counter = 0;
    }

    if (delta >= fps_counter / FramesPerTick) { // render
        fps_counter++;
        frames++;
        render(glad);
    }

    if (System.currentTimeMillis() - timer > 1000) {
        timer += 1000;
        frame.setTitle("Ticks: " + updates + " Fps: " + frames);
        updates = 0;
        frames = 0;
    }

```

So if i have 20 ticks and 3 FramesPerTick i get 60fps it checks whenever delta is bigger than 1/3, 2/3 and 3/3, so every tick has 3 frames

Everything is jittery, movement, mouse look. Animation gets more and more jittery the lower the FPS, i dont understand why.

Also when i take the render(glad) method out of the if, it goes up to 400 fps and runs very smoothly.

EDIT: If i put Thread.sleep(13) instead of if (delta\>=fpscounter/FramesPerTick){} i get around 60 fps and smooth animations.

# Answer
> 3 votes
Ah! I missed the obvious reason for the odd behavior while first looking at your code (I think). Essentially, there are three potential problems here:

## First: Missing Updates

Each and every iteration you'll update your game logic only once (or not at all). In a similar way, you draw your screen (or skip drawing).

However, this causes one problem:

* Let's assume you'd like to update the game 100 times per second (makes it easier to explain/compare).
* This means there are 10 ms between updates.
* As long as each and every iteration is faster than 10 ms, you won't notice any problem.
* Now assume there's some stuttering for a moment (don't know, let's say you connected some device or whatever).
* This iteration, 25 ms have passed. This means that you'd have to do two updates before rendering again, i.e. `update(); update(); render();`.
* Due to your design, you won't do this. Instead you'll get `update(); render(); update(); render();`.
* This might cause visual/noticeable stuttering (especially if we're talking about more than just two updates!) since the game now obviously lags a bit (till you've cleared your update backlog; assuming you're able to do so).
* This also means you're essentially connecting your logic updates to the framerate. If you can't render at the intentional framerate, your game logic will slow down as well.

## Second: Race Conditions

This is something you can't really avoid if you'd like to do fixed timesteps:

* Let's assume you're rendering 60 times per second and updating 30 times per second.
* Theoretically, this should trigger one call to `update()` for every second call to `render()`.
* However, this is essentially just an average number.
* It's possible, that between two frames you miss your update since you're like 5 ns too fast.
* Rather than calling `update(); render(); render(); update(); render(); render();` you'd at once call `update(), render(); render(); render(); update(); render();`. Overall you're still at 60/30 fps, but your timing is still off a bit (especially if you've got vertical sync enabled).
* This can cause minor inconsistencies that might become noticeable, especially when things on screen are moving quite fast.
* Fix Your Timestep! elaborates a bit more and also provides a solution to this.

## Third: Rounding/Precision Issues

While I can't say this for sure, you might be running into precision issues with your variables.

If `delta` is some floating point variable (due to the `/ ns` step?), you might run into rounding issues here.

Also `System.nanoTime()` doesn't necessarily return a very precise time value - it's implementation dependent. It could be in nanoseconds, but it could as well just return whole milliseconds or even less (could also depend on the system's energy saving settings):

> This method provides nanosecond precision, but not necessarily nanosecond resolution (that is, how frequently the value changes) - no guarantees are made except that the resolution is at least as good as that of currentTimeMillis().

Depending on your actual number of frames/updates this might be neglectable though. (And there isn't really anything you can do about this, other than trying to pick sane numbers/scaling that will work for you.)

---
Tags: java, game-design, game-loop
---