title: Flash game on Steam

text:
# Question
Title: Flash game on Steam
I have almost completed a game written in flash/as3 using flixel. How can I sell it through steam ?

A few years back, (I was a full-time flash game dev back then..) there were 2 choices:

* Use Adobe Air to make the game downloadable.
* Use 3rd party flash wrappers like Zink, that are bit more poewrfull, but for a price.

And of course, there's the option to write it from scratch in some other language..

I wonder, since I've been hidden in cave these years, and I'm not really up-to-date with the flash-game market (I know it's dying..), what are my options to publish and monetize my as3 game to the desktop market ?

Feel free to drop any idea, even if it's not directly solving my problem.

# Answer
You could also try Haxe and cross compile it as an executable. There is a AS3 converter and using OpenFL you can keep using the flash API. fixel is ported as well. You still might end up in some troubles here and there but the community is active and helpful and a good source to get some quick help is their IRC Channel and Google Group.
> 4 votes

# Answer
Steam is possible, as long as the game is packaged into an executable. Quality of course has to be pretty strong to get there.

Steam Greenlight : http://steamcommunity.com/greenlight/faq/

Online platforms : https://stackoverflow.com/questions/8026503/popular-flash-games-on-stream
> 2 votes

# Answer
Just to round out ScrambleRK's answer, there is a more recent, OpenFl compliant version of as3hx available. You can find it here: https://github.com/openfl/as3hx

As3hx is essentially an command-line tool, but it's fairly simple to use. I recently ported an API using the tool. There was some post-editing that needed to be done on the generated hx files, but for the most part it was minimal (most issues had to do dynamic typing).

There is also a haxe port of flixel available called HaxeFlixel. You can check it out here: https://github.com/HaxeFlixel/flixel
> 1 votes

---
Tags: flash, porting, steam
---


# Question
Title: transformation before the perspective divide but after projecting perspectively
My problem is that I would like to confine a scene render to a (possibly rotated) rectangle without using `glViewport()`. I don't want to use it to save, if possible, some cycles that would otherwise be spent on state switching. Also, there is the tantalizing possibility of rotating the scene render, which is not possible with `glViewport`... Is it possible to confine a scene render to this (possible rotated) rectangle in this way?

# Answer
> 1 votes
You can adjust the scene position, rotation, and scale in the viewport, by simply concatenating the desired 2D transformations onto your projection matrix.

You can also mask out areas of the viewport you don't want to be rendered, by rendering some black geometry at the near clip plane, thus preventing anything else from showing up in those areas (since it will fail the depth test). The masked areas can be any shape you wish, since they're just geometry rendered like anything else. This will be pretty efficient, too, since modern GPU hardware has very efficient Z-culling.

All that being said, though, this question smells of premature optimization. :) Have you actually measured the time taken by `glViewport` and is it really a performance problem for your application? If not, that would be a good thing to do before spending a bunch of time implementing a subsitute method.

---
Tags: opengl, transformation, viewport
---


# Question
Title: How to execute a piece of code for X seconds in Andengine?
I need to execute some code in my game for 5 seconds using the Andengine framework. So far, I've tried with the **onTimePassed** update handler:

```
 scene.registerUpdateHandler(new TimerHandler(5f, true,new ITimerCallback() {

            public void onTimePassed(final TimerHandler pTimerHandler) {
                                    // code here
                }

```

But that only executes AFTER 5 seconds have passed by. I've also tried with the **onUpdate** but, keeping apart performance issues, there's no way I can count how many seconds have passed by since the execution entered the loop. If it helps, I only need the code to execute once per second for 5 seconds. Thank you!

# Answer
> 1 votes
You can register an `IUpdateHandler` that tracks the total amount of elapsed time by accumulating the value in `pSecondsElapsed` and then only executing your action if the accumulated time is less than 5 seconds. Also track the elapsed time in a delay counter to execute a timer action every 1 seconds.

For example

```
public interface TimerAction {
    void execute();
}

```

public class UpdateTimer implements IUpdateHandler { private final Scene scene; private final float delay; private final float duration; private final TimerAction action;

```
    private float totalElapsed;
    private float delayElapsed;

    public UpdateTimer(final Scene scene, final float delay, final float duration, final TimerAction action) {
        this.scene = scene;
        this.delay = delay;
        this.duration = duration;
        this.action = action;
    }

    @Override
    public void onUpdate(final float pSecondsElapsed) {
        totalElapsed += pSecondsElapsed;
        delayElapsed += pSecondsElapsed;

        if (totalElapsed >= duration) {
            scene.unregisterUpdateHandler(this);
        }

        if (delayElapsed >= delay) {
            android.util.Log.i("TAG", String.format("Timer tick @ %d", System.currentTimeMillis()));
            action.execute();
            delayElapsed = 0;
        }
    }

    @Override
    public void reset() {
    }
}

```

It would then be set up something like this

```
    scene.registerUpdateHandler(new UpdateTimer(scene, 1, 5, new TimerAction() {
        @Override
        public void execute() {
            android.util.Log.i("TAG", "Timer action executed!!!");
        }
    }));

```

---
Tags: android, andengine
---


# Question
Title: How can I use the graphics pipeline to render volumetric data based on a density function?
Both graphics APIs (OpenGL and DirectX) devise a well defined pipeline in which several stages are programmable. These programmable stages require to take a fixed minimum amount of data and are supposed to do a well defined range of operations on it, and output some defined minimum output, so that data can be passed on to the next stage correctly. It seems as if these pipelines are designed to work with only a limited amount of types of geometric data, which in the case of both D3D and OGL are vertex data and texture co-ordinates.

But, if given a case when the application I plan to make doesn't use vertices ( or even voxels ) to represent its geometric data and does not exactly do transformations or projections or rasterisation or interpolation or anything like that, such limitations of the APIs or the pipeline make things difficult.

So, is there a way in which we can change graphics pipeline in a way so that the functionality of what each stage does to the data and the type of data that is outputted in each stage is changed to my advantage? If not, then is there a way by which I can use the 'raw' API functions to construct my own pipeline? If not, then please mention why it isn't possible.

**EDIT** : My Application uses density functions to represent geometry. The function has a value at each point in space. I divide the frustum of the camera into a 3d grid, each block can be projected as a pixel. On each block, I integrate the density function and check if its value is more than a required value. If yes, then its is assumed that something exists in that block and that pixel corresponding to that block is rendered. so, now in my renderer, I want to pass the function ( which i represent with a string ) to the graphics hardware instead of vertex data in vertex buffers. this also implies that the vertex shader won't have vertices to transform into homogeniouse clip space and the fragment shader doesn't get pixel info. instead, now most of the looking up and evaluation happens per pixel.

# Answer
You can absolutely use the GPU to render volumetric data.

Since you want to evaluate a set of functions per pixel on the screen, a simple approach is to render a full-screen triangle. This is just a single triangle that covers the entire screen (actually, it covers more than the screen, since the screen isn't triangular, but the parts off-screen are discarded by the GPU). You can then use the pixel shader (which receives the screen coordinates of the pixel it's shading) to construct a ray through your volume, evaluate functions, whatever you need to do.

(In contrast to the other answers, I don't recommend a compute shader because it sounds like you want to do per-pixel operations, and a full-screen triangle + pixel shader is generally more efficient for that than a compute shader—although compute shaders will certainly also work.)

The full-screen triangle method is very common in real-time graphics for postprocessing operations, so you can probably find all the information you need on it with a bit of googling.

BTW, it may interest you to read Rendering Worlds with Two Triangles by Iñigo Quílez, a talk which describes how to render 3D scenes composed using mathematical functions (specifically, distance fields) using the full-screen pixel shader technique.
> 18 votes

# Answer
Ray tracing and other techniques are commonly done with Compute Shaders, which Direct3D has supported since the release of D3D11 and OpenGL has supported since 4.3 (and longer via the use of OpenCL and some contortions).
> 6 votes

# Answer
It sounds very much like you want to use a GPU compute shader, or utilize a "Shader Storage Buffer" object to help augment the pipeline to fit your needs. Mathematicians, scientists, and other people who look to the GPU for computation on things that don't exactly translate into standard graphics use this kind of thing.

> Although the contemporary graphics pipeline is very flexible, developers still tend to stumble on some restrictions. The compute shaders feature, however, makes life easier for us to not think about pipeline stages as we are used to thinking about vertex and fragment. We are no longer restricted by the inputs and outputs of certain pipeline stages. The Shader Storage Buffer Object (SSBO) feature for instance has been introduced along with compute shaders and that gives additional possibilities for exchanging data between pipeline stages, as well as being flexible input and output for compute shaders.

http://community.arm.com/groups/arm-mali-graphics/blog/2014/04/17/get-started-with-compute-shaders

If this does not point you in the right direction, would you mind expanding the concept of yours that doesn't fit the vertex/fragment paradigm?
> 5 votes

---
Tags: opengl, graphics, pipeline
---


# Question
Title: Henry Hatsworth kind of blocks minigame, std::vector sorting or alternative?
I'm not sure if this is the right place to post this, or if I'm doing it right. But I believe I've kept to the rules. If not, please let me know and I'll remove my post or edit it accordingly.

I'm building a mini game that's inspired by Henry Hatsworth and I'm trying to recreate the blocks part of the game. I've rewrote a huge part of it after coming up with a "better" way, but now I'm stuck with a problem I thought would be easier to solve.

My first implementation was a multi-array "grid" that each held a block entity, but at some point I rewrote a huge chunk of it and made each block entity be a thing of its own rather than being tied to a "grid", they could fall collide with each other freely without having to check with a grid system.

So my rework had me use a std::vector instead, saving each block in the field in it, and removing/adding them as they were generated and destroyed. Each frame I loop through the vector and execute each block's think() function.

My problem comes with needing to sort the vector, preferably from lowest x&y to highest. Or am I perhaps missing an easier way? Perhaps there's a way I haven't thought of yet or am unaware of. This is a screenshot of the field

I have two issues with this so far. The first is that I don't really know of a way to match the blocks while using a vector. At least not without very efficiently going through the vector many, many times. Secondly, when I poll through the vector, at some point the blocks are going to be crisscross in terms of x/y positions as making combinations will make other blocks above the ones destroyed fall down.

I have thought of building a grid to place the blocks into, but that will have me going through the vector a lot of times as well. But as I said, perhaps I'm going about this all wrong and I could be doing it much easier, or differently.

**Hopefully a better elaboration:**

In main.cpp I have a std::vector containing a Block, a Block being an object with its own properties like xpos, ypos, etc. Each Block has it's position on the screen. Each frame I go through the vector and execute each Block's think() function which moves them up on the screen (until they reach a certain position and are destroyed). Now in a grid, the positions are pretty logical. If you have a grid of \[8\]\[8\] you have a field that's 8 by 8 that you can easily match blocks by doing something as simple as:

```
int selectedBlockType = block[0][0].type;
if(selectedBlockType == block[0][1].type && selectedBlockType == block[0][2].type){
    // The 3 blocks match, destroy them and mark the blocks above these as "falling"
}

```

However in the vector you don't really have a grid you can easily reference off of, especially not since the blocks are moving up by 0.1px each frame. So far I've been using colission rects I've named blockBeacon (as seen in block.h), but I'd still have to go through the vector many times to check for colliding collision rects of blocks that are next to each other.

In every frame I do:

```
// This is defined at the start, before the game loop, but for the
// sake of explanation I'll just include it down here
std::vector<block> blocks; // This holds our blocks I erase and push other blocks into

// Loop through the vector
for(int i = 0; i < blocks.size(){
    blocks[i].think();
}

```

Then a bit further down, I'd use:

```
// Pass through the vector containing all the blocks in the field
fieldManager.pollField(blocks);

```

Which is where my problem would be I don't actually know how to efficiently (without going through the vector many times) see if the blocks are next to each other. I hope this better explains my issue.

The noteworthy files explaining my problem are main.cpp and fieldmanager.cpp. entity.h and block.h/cpp may also help better understand what I'm doing. (I'd link them but apparently I need more rep to be able to post more than 1 link, so I included my GitHub URL below.)

The entire source of the project is at my github: https://github.com/AeriusOhara/legend-of-elements/tree/master/legend-of-elements I apologize in advance if the codebase is terrible, I'm self-taught and still learning (tips or criticisms are always welcome though!)

# Answer
From your question I think you want a way to efficiently access a block's neighbours vertically.

I'm not sure why you decided you want a std::vector instead of a grid made of a 8x8 array (you know you can iterate through every block in an array too), but I think the array is the better choice. If you really want to use a std::vector, then you may want to sort all the blocks by x-coordinate, then y-coordinate and you will actually now end up with a grid, where you have block\[x\]\[y\] = vector\_name\[x + y\*blocks\_per\_line\]. With a decent sorting algorithm like quicksort you can do this every frame incredibly fast. If you don't want to sort them, then the only way is to iterate through all of them.
> 0 votes

---
Tags: c++, sfml
---


title: GLSL Processed Image to OpenGL

text:
# Question
Title: GLSL Processed Image to OpenGL
I've tried wording and rewording this question in various forms of search and can't seem to find an answer to it. If I'm wording it wrong and/or just not finding the right information, feel free to throw me a link.

Here's what I'd like to accomplish: I want to do several different processing effects with GLSL, on several different images - each image a different effect - and then retrieve the end result and combine all the images to form a finished result.

Then, I want to save the finished product to an image I can later reuse.

So basically:

* Make non-transparent blurry, greyscale, whatever else...
* Do different effects on 3-10 images...
* Layer all images on top of one another...
* Flatten the images to result in a single image that looks identical...
* Save to PNG.

I know 'save to PNG' isn't one of those things OpenGL can do and I have something I can use for that. However, I'm running into problems thinking up a way to retrieve the pixels from the end result (From the shader) and flatten them into a single result (in language of choice/OpenGL), and then get the final pixel data.

This doesn't have to be done in near realtime (Of course). It'll only happen when specific events are triggered, and only when absolutely necessary during those events. The events trigger 'permanent until further notice' situations, which is why this would be useful - on top of the idea of having multiple images being drawn over one another every frame being reduced to one, of course.

Thanks!

# Answer
If the final shader outputs the image to the framebuffer, have a look at the glReadPIxels function (This function is often used to create screenshots in games example 1 | example 2)

If you wish to get the data from a texture (in case the texture is larger than the screen resolution, this might be a better solution), have a look at the glGetTexImage function.

```
// Create a buffer large enough to store a R, G, B value for every pixel
GLfloat* pixels = new GLfloat[width * height * 3];
// Request the pixels from the framebuffer. Make sure the shader outputted it's
// results to the framebuffer first.
// If this is not the case, make sure the required texture is bound and use
// glGetTexImage instead.
glReadPixels(0, 0, width, height,GL_RGB, GL_FLOAT, pixels);
// Pass on the pixels array to the png processing library
// clean up the pixel array
delete[] pixels;

```
> 3 votes

---
Tags: opengl, glsl, software-engineering, image-processing
---


title: Animal Crossing-like Map Data Structure

text:
# Question
Title: Animal Crossing-like Map Data Structure
I've been looking closely at how Animal Crossing (for GameCube) creates town maps, and as far as I can tell, it's something like this:

The town is made up of a 5x6 grid of acres. Each acre is 16x16 "tiles" in size.

That's the easier part. As for the actual map generation, it seems to use what I'll call "acre templates." That is, the acres seem to be selected somewhat randomly from a predefined list, with predefined layouts. So there are, for example 2 different layouts of what an acre containing the Museum will look like.

Or if an acre has a river running through it, top-to-bottom, there might be 3-4 different templates of how the river flows through that acre, with optional ponds nearby, etc.

The question is... What is a good suggestion or method for how to organize the data structure to handle all of this?

Another thing to keep in mind is that there's a "second layer" of objects on top of the basic terrain info, such as trees or rocks or inventory objects dropped/buried on/in the ground. How would I store that information in relation to the acre templates?

# Answer
> 4 votes
Actually, after thinking about it for a bit, here's what my solution would be for both disk and memory storage; a mock-up in JSON:

```
{
"map_segments": [
    ["upper_left", "top",           "top",          "upper_right"],
    ["left",       "empty",         "town_center",  "right"],
    ["left",       "shopping_area", "player_house", "right"],
    ["left",       "npc_house",     "empty",        "right"]
]
"variants" : {
    "upper_right" : [
        {
            "tiles": [
                "xxxxxxxxxxxxxxxx",
                "  .  .   . .   x",
                "  .. .    ..   x",
                "  .    * . .   x",
                "     .   . .   x"
            ],
            "default_floor": "floors.grass",
            "legend": {
                "x": "walls.townwall",
                " ": "floors.dirt",
                ".": "floors.grass",
                "*": "objects.tumbleweed"
            }
        }
    ]
    "town_square": [
        {
            "tiles": [
                "xxx          xxx",
                "xx2  .   . .xx1x",
                "  .. .%   ..|==x",
                "xx2      . .xx=x",
                "xxx  .   . . xxx"
            ],
            "default_floor": "floors.grass",
            "legend": {
                "x": "walls.townwall",
                " ": "floors.dirt",
                ".": "floors.grass",
                "|": "objects.doorv",
                "=": "floors.wood",
                "1": ["floors.wood", "spawn.village_eelder"],
                "2": "objects.herostatue",
                "%": "objects.townwell"
            }
        },
        {
            "tiles": [
                "x!!        !!!= ",
                "!x3  . 1 . !=!! ",
                "  .. .%   .==== ",
                "!x2      . =!!! ",
                "x!x  .   . !!!= "
            ],
            "default_floor": "floors.grass",
            "legend": {
                "x": "walls.townwall",
                " ": "floors.dirt",
                ".": "floors.grass",
                "!": "walls.townwall_ruin",
                "=": "floors.wood_burned",
                "1": "spawn.village_elder",
                "2": "objects.herostatue",
                "3": "objects.herostatue_broken",
                "%": "objects.townwell"
            }
        }
    ]
}
}

```

Basically you have a lookup mapping for each type of map segment, which contains a list of variants for that segment which you can do a random pick from. This also includes a very simple hand-editable map format similar to that I've seen in several roguelikes or other randomized games in the past; handy if you don't want to build a in-depth map editor. (StarBound also does basically the same thing, except they use several bitmaps and a color lookup table instead of an ASCII lookup table.)

---
Tags: tilemap, maps, data-structure
---


title: Node.js 3D game?

text:
# Question
Title: Node.js 3D game?
Would it be suitable for making 3D games in an open world?

Of course provided that I :

* create a node add-on in order to bind opengl
* code a native layer for making threads and processes

I can almost hear you: why node? Because I love coffeescript and I am more experienced in that language (I can't get pointers in c++) and mostly because I want it to be cross platform and **hackable**.

But is node fast enough? Are programming patterns such as data locality working in node? What about CPU load?

# Answer
> 2 votes
In my opinion using node for a game client is not the best option. Node.js is usually used for the server side of a game and not the client.

If you like CoffeScript why don't you create an HTML 5 game with one of the tons of free JavaScript game engines out there?

This would also spare you the hassle of creating OpenGL bindings (you'd have to use WebGL which is basically a subset of OpenGL).

---
Tags: node.js
---


title: GLFW mouselook under OSX

text:
# Question
Title: GLFW mouselook under OSX
I'm continuing to port an OpenGL app from Visual Studio 2012 to XCode 5.

The only major issue I'm having is mouselook. It "doesn't work" under OSX (Mavericks).

Here's the (pseudocode):

Pre-update, executed at the start of the frame:

```
void Dispatcher::PreUpdate(GameTime &time)
{
    m_currentKeyboardState = m_nextKeyboardState;
    m_previousMousePosition = m_currentMousePosition;

    GetMousePosition(m_currentMousePosition);
}

```

Post-update, executed, well, after input processing, at the end of the frame:

```
void Dispatcher::PostUpdate(GameTime &time)
{
    m_previousKeyboardState = m_currentKeyboardState;

    if (m_captureMouse)
        RecenterMouse();
}

```

Method to recenter the mouse:

```
void Dispatcher::RecenterMouse()
{
    glfwSetCursorPos(m_window, m_windowSize.x / 2.f, m_windowSize.y / 2.f);

    GetMousePosition(m_currentMousePosition);

    if (m_previousMousePosition != m_currentMousePosition)
        cout << "Mouse: " << m_currentMousePosition.x << "," << m_currentMousePosition.y << endl;

    m_previousMousePosition = m_currentMousePosition;
}

```

And, jut for completeness:

```
void Dispatcher::GetMouseMotion(Vector2 &movedBy)
{
    if(m_captureMouse)
    {
        movedBy.x = (m_currentMousePosition.x - m_previousMousePosition.x);
        movedBy.y = (m_currentMousePosition.y - m_previousMousePosition.y);
    }
    else
    {
        movedBy.x=movedBy.y=0;
    }
}

```

If `m_captureMouse` is `true`, and `m_previousMousePosition != m_currentMousePosition`, the y delta is always 1, no matter how far I've moved the mouse. (Actually, using the trackpad, but should be indentical.)

This code works perfectly under Win7, but never returns anything other motion than `(0,1)` under OSX.

Suggestions? I've seen other questions regarding glfw and osx, but no solutions.

**EDIT**

It's worth noting if I turn off mouse capture (which basically does everything *but* recenter the mouse at the end of the frame), mouselook works correctly but, of course, the cursor is free to wander outside of the window, which doesn't really work for a first-person app.

# Answer
This is usually solved by changing `glfwSetInputMode` with `GLFW_CURSOR` from `GLFW_CURSOR_HIDDEN` to `GLFW_CURSOR_DISABLED`.

The behavior differences are due to the differences in OS APIs that GLFW uses and how they interact with the windowing system. In the documentation, it says that `DISABLED` should be used for 3D camera controls, and `HIDDEN` should be used when rendering a custom cursor.
> 3 votes

---
Tags: opengl, mouse, glfw
---


# Question
Title: Should Animations in Turn-Based Games Happen Before or After State Transitions?
I'm planning a roguelike game and I'm unsure how to design for animations. Since a roguelike is turn-based, the game model is discrete and would have no intermediate states during an animation(?). I've come up with two possible approaches:

1. Perform state transitions immediately upon input and compute the animations that occurred. In the case of a moving character, draw the animation as a member of the destination tile (instead of the static sprite) and coming from the origin tile.
2. Compute animations before transitioning and transition the state asynchronously after the animation completes. Draw moving objects as members of their origin tile so that they arrive immediately before the state transition.

Do developers of this type of game tend to prefer approach 1 or 2 (or some third option) and why?

# Answer
> 2 votes
I'm somewhat confused from your question. The general rule and i don't think this is defined by game style but rather the game architecture itself, is that rendering(animations) should happen independently in your game. And the switch between animations should be triggered by state changes. If you arrange your game architecture like this then it's only a matter of when a state change is triggered. I hope i did provide some insight.

**Edit: *updated with more info.***

---

You have to change your point of view on this matter. When you are saying that this type of game doesn't have many animations, you should really be thinking about the game/object state changes, which in such a type of game is usually correct, many things remain static for extended periods of time. I will try to give you a very brief example of how a state change interacts with animations but really, you should further look this up on the net. Maybe check how animations are handled in general.

So in my example i have a player object/class with a private member named current\_state of type PLAYER\_STATE. PLAYER\_STATE could be an enum could be class, how you architecture your game is on you. I prefer to use enums.

```
enum PLAYER_STATE
{
    IDLE,
    RUNNNG,
    JUMPING
};

```

Now you should probably have some kind of system to handle your animations. And that system would check on the players state (current\_state) to see what action is the player currently performing and re-adjust your animation(frame sequence for sprites) to the one corresponding to the action that is stored on your player (IDLE, RUNNING, JUMPING). I hope i gave you an idea but really, this is an extended topic that needs further research.

---
Tags: animation, turn-based, roguelikes
---


title: Integration error in high velocity

text:
# Question
Title: Integration error in high velocity
I've implemented a simple simulation of two planets (simple 2D disks really) in which the only force is gravity and there is also collision detection/response (collisions are completely elastic). I can launch one planet into orbit of the other just fine.

The collision detection code though does not work so well. I noticed that when one planet hits the other in a free fall it speeds backward and goes much higher than its original position. Some poking around convinced me that the simplistic Euler integration is causing the error.

Consider this case. One object has a mass of 1kg and the other has a mass equal to earth. Say the object is 10 meters above ground. Assume that our dt (delta t) is 1 second. The object goes to the height of 9 meters at the end of the first iteration, 7 at the end of the second, 4 at the end of the third and 0 at the end of the fourth iteration.

At this points it hits the ground and bounces back with the speed of 10 meters per second. The problem is with dt=1, on the first iteration it bounces back to a height of 10. It takes several more steps to make the object change its course.

So my question is, what integration method can I use which fixes this problem. Should I split dt to smaller pieces when velocity is high? Or should I use another method altogether? What method do you suggest?

**EDIT:** You can see the source code here at github:https://github.com/elektito/diskworld/

# Answer
> Say the object is 10 meters above ground. Assume that our dt (delta t) is 1 second. The object goes to the height of 9 meters at the end of the first iteration

Here lies your problem. It is true that the velocity at the end of the first iteration is \\$1 m.s^{-1}\\$. However during that time the object has not travelled \\$1 m\\$.

In fact, since the acceleration is constant, the *average* object velocity is simply \\$0.5 m.s^{-1}\\$ and thus the object has only travelled \\$0.5 m\\$. The next frames will be:

$$ \begin{array}{c|c|c|l} \text{time} & \\;\\; v \\;\\; & v(avg) & \text{height} \\ \hline 0 & 0 & - & \\;\\;10.0 \\ 1 & 1 & 0.5 & \\;\\;9.5 \\ 2 & 2 & 1.5 & \\;\\;8.0 \\ 3 & 3 & 2.5 & \\;\\;5.5 \\ 4 & 4 & 3.5 & \\;\\;2.0 \\ 5 & 5 & 4.5 & -2.5 \text{(collision happened)} \end{array} $$

So, to know the new object position, **use the average velocity** instead of the new velocity. It will greatly improve your accuracy (in fact, in the case of constant acceleration, it will even give you *exact* results).

> At this points it hits the ground and bounces back with the speed of 10 meters per second.

This is incorrect, too. Where does the value 10 come from? With your integration method, the velocity should be 4.
> 3 votes

# Answer
Just guessing from the description of your issue, since I don't have any actual code, I would also look in to the following if you haven't already:

What happens if you use a smaller time step, say 1/30 sec?

Check that you apply the time step variable (dt) in the appropriate parameters of your simulation calculation. Since you mentioned that the "combination causes the problem" and the physics are mangled with the collisions it might be necessary to apply the time step to both physics and collision detection/response code.

Make sure that the objects **don't overlap** during the collision. So the collision detection code will not run multiple times that may add the collision response force multiple times.

Make sure that physics calculations occur in **fixed time step** because if you use variable time step the integration produces small errors proportional to each time step that sum up during multiple frames.

Try to **smooth** the results of the physics calculations by averaging the results of the last two or three frames. That way you will also average the small errors and the end result will be perceived as more accurate.
> 0 votes

---
Tags: collision-detection, mathematics, physics, numerical-methods, integration
---


title: Unity display message upon keypress?

text:
# Question
Title: Unity display message upon keypress?
Hi I'm trying to get NGUI's HUDtext to display a set of text message one of which being "Try using WASD to move" and displaying "Well done!" upon input of any of the four keys. Unfortunately I'm not well versed in C# and am currently stuck and unsure how to implement this.

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

//public KeyCode KeyCode.Alpha2;

public class Test : MonoBehaviour {

    public int seen = 123;
    public HUDText hudText;

    void Start() {

        StartCoroutine(MyCoroutine());
        //Debug.Log(KeyCode);
        Tutorial ();

    }

    void Tutorial() {

        while (true) {
            while (!Input.GetKeyDown(KeyCode.Return)) Debug.Log ("Hit return");
        }

    }

    IEnumerator MyCoroutine() {

        hudText.Add("Welcome", Color.white, 3f);
        yield return new WaitForSeconds(3);    //Wait one frame

        hudText.Add("This is System Defence", Color.white, 4f);
        yield return new WaitForSeconds(4);

        hudText.Add ("Try using WASD to move", Color.red, 3f);
        yield return new WaitForSeconds(3);

    }

}

```

I would appreciate it if someone could tell me how would I go about doing this.

# Answer
> 3 votes
Considering you have a `while(true)` loop in your code, you're not going to allow the game loop to move to the next frame. You'll need to move to the next frame to update the screen and gather new input.

You can use the `void Update()` method to check for stuff like keyboard input every frame.

```
void Update() {
    if(Input.GetKeyDown(KeyCode.W)
     | Input.GetKeyDown(KeyCode.A)
     | Input.GetKeyDown(KeyCode.S)
     | Input.GetKeyDown(KeyCode.D)) {
         hudText.Add ("Nice work! Now try...", Color.red, 3f);
     }
}

```

Obviously you'll also want to keep track of the state of the users progress, so you don't keep showing the same messages over and over. But, the `Update()` method is the place for those types of things.

---
Tags: unity, hud, ngui
---


title: How to enable/ disable GameObject

text:
# Question
Title: How to enable/ disable GameObject
I have child object with ParticleSystem component. I want to have particles disabled until I press button.

I unchecked child object to make it disabled but when I press play it enables automatically(with no scripts attached). Then I made this script below (with .SetActive(false) part only) and it worked.

But then I needed to activate it somehow, which I did, but now when I press play, object is automatically enabled/ activated again.

Is there another way of doing this because I need it haha.

```
var particle1: GameObject;
var particle2: GameObject;
var particle3: GameObject;

public var triggered : boolean = false;

function OnTriggerEnter() { triggered= true; }
function OnTriggerExit()  { triggered= false;}

function Start()
{
    particle1.SetActive(false);
    particle2.SetActive(false);
    particle3.SetActive(false);
}

function Update()
{
    if (triggered && Input.GetKeyDown(KeyCode.JoystickButton1))
        particle1.SetActive(true);
        particle2.SetActive(true);
        particle3.SetActive(true);
}

```

# Answer
> 1 votes
It might be related to your Update function:

```
function Update()
{
    if (triggered && Input.GetKeyDown(KeyCode.JoystickButton1))
        particle1.SetActive(true);
        particle2.SetActive(true);
        particle3.SetActive(true);
}

```

Having no brackets, only particle1.setActive(true) is in the condition. The other two will be called on each Update() loop. Try adding brackets and see if the problem persists:

```
function Update()
{
    if (triggered && Input.GetKeyDown(KeyCode.JoystickButton1))
    {
        particle1.SetActive(true);
        particle2.SetActive(true);
        particle3.SetActive(true);
    }
}

```

---
Tags: unity, javascript, particles, gameobject
---


# Question
Title: How to make blocks like "redstone" working in a minecraft-like game when the chunks are not loaded
I'm working on a 2D minecraft-like game, I use chunks to save my world and each chunk has 128\*128 blocks in it. And infinite chunks can create an infinite world.

Memory should never be infinite and only several chunks near the character are shown on the screen and loaded into memory. How can I handle logic based blocks like red stone signals when they are in chunks far away and so not loaded in memory?

# Answer
> 16 votes
What you need to do is separate terrain from live blocks. For example you could store the live blocks in a dictionary that uses a point as key. And then unload the terrain. This way your live blocks stay in memory in a way you see fit, and you can still look them up based on position, but the terrain is stored on disk for later retrieval.

This will increase memory a bit, but you can't avoid it entirely.

# Answer
> 5 votes
In Minecraft, circuits in unloaded chunks simply do not work. Especially with pistons and other ways of interacting with the environment, it could get expensive quickly to keep far-away circuits running in an infinite world.

I see three main possible choices for your game:

* Keep all chunks loaded. This is just a big nope.
* Keep nearby chunks loaded. For chunks too far away, save the state of the chunk. When coming close to the chunk, load the state again.
    + This means that the circuit will continue where it left off. Complex circuits won't break this way.
    + On the downside, the circuit won't run when the player is too far, though this is generally acceptable.
* Store active components separately. For chunks too far away, unload the terrain data but keep circuitry active.
    + This will cause things such as sensors, timers, etc... working all the time.
    + Bigger resource hit. An infinite world means possibly infinite circuits constantly running.
    + This would only work if circuits cannot interact with the terrain, or if they can only interact with the terrain within proximity of the player.

Of course there may be other ways to work around this, but those are likely going to be some form of hybrid between these ideas.

# Answer
> 4 votes
Tekkit (a popular minecraft mod) does this by allowing players to build anchors that keep a few blocks around them in memory regardless of player proximity.

It might be a good choice if there is clear distinction between dynamic blocks that require the presence of the player (an automatic door) and others that don't (a generator of some sort).

http://tekkitclassic.wikia.com/wiki/World\_Anchor

# Answer
> 0 votes
Just an idea on a way to handle this without it bogging the game down too much.

What you could do instead is enforce a game mechanic that only runs that "redstone block" when it is connected to some sort of rare or hard to craft "Power" block, suggesting that the presence of the player powers the "redstone" and is required to run it.

I believe that how it actually works is dependent on what your "redstone" does. Does it physically move the block and do you handle moving blocks in unloaded chunks? What if it throws TNT into 10 chunks away, how would the "redstone" handle that?

I believe that to get a serious suggestion on a particular issue the question about the logic will have to be more specific.

# Answer
> 0 votes
I will just focus on just one topic in this answer: If you want to unload distant circuits to save CPU time and/or memory, what will happen to complex circuits that spred across multiple chunks?

1. Igore this problem. Easy to implement, but unsatisfactional behaviour.
2. Let player be aware of this problem, and give him a tool to display chunk bounds. I think there was such item in one of Minecraft's mods. Player then can build circuits only on one chunk if he needs to.
3. Create some connective block, when placed, it will guarantee that all circuits in a set redius will be always loaded/unloaded at the same time. Assuming that radius is smaller than chunk size, one such block will connect maximally 4 chunks together. However overusing these blocks can lead to infinitely many connected chunks.
4. In `Tekkit` mod, there was World Anchor block, that kept surrounding chunks loaded all the time. Good choice if you want to have some machinery running away from player.

**Summary:** Depends on what you need, I wouldn't be afraid of combining 2, 3 or 4 (or all) together, you can also nerf 3 to connect maximally N chunks.

---
Tags: minecraft-modding, memory-efficiency, memory
---


# Question
Title: Setting up a camera to make the world look large
I am attempting to configure my camera to give the impression of a normal sized player in a giant room. Since units are arbitrary, I figured this should be possible (despite the fact that the room is technically 24x24m big and I want it to feel more like a hangar).

I have tried tweaking down the FOV (to about 40 degrees) which has helped some, but I can't shake the feeling that I am a tiny person in a normal sized room rather than a normal sized person in a giant room.

What about the way the scene is being rendered is giving away this to my eye. Or is it just a lack of reference points?

I am using Unreal Engine if that affects the answer.

# Answer
> 1 votes
You need to add details to show the scale of the world. In terms of rendering, there's no difference between a tiny person in a normal room and a normal person in a large room. If there's any fog, you should decrease the distance for it so as to make the space look larger.

It could also be the height of the ceiling in the room relative to the player height, which is going to be one of the main references people use to figure out the size of the player/room.

If you're making a hangar, add planes/helicopters/service vehicles at the correct scale relative to the player and the scale of the world should feel correct.

Also a side note, I'm not sure about the Unreal engine, but most physics engines don't like it when you scale the world size up or down a lot.

# Answer
> 0 votes
First, the technical stuff that probably goes without saying, but...

* Camera very low to ground (TPPOV (Tiny Player Point Of View))
* Player movement speed scaled down

Second, the art stuff, that probably is what you're missing. This translates into...

* Brand new textures are required that show in fact what something looks like very close up. It has to be REALLY super fine detail. All the little lumps in the linoleum, fine wood grain, tiny details in a potted plant's leaf, etc.
* Brand new little details like dust bunnies, small items on floor that you normally don't see (paper clip, finger nail clipping, dead bug, dropped pencil, etc.)

Go lay on the floor in a room and look at what you can see close up. Do it with a magnifying glass. It's all that little stuff that's going to make a huge difference.

---
Tags: rendering, camera, unreal
---


# Question
Title: How to write "Hello World" for N64 purely from scratch?
As an experiment I want to code a "Hello World" program for N64 using only assembly code, using no headers, tools, helper files, etc.

I just want to write the assembly code bare bones from absolute scratch, assemble it and have it run through a demanding emulator that can show me the output.

I can't find enough info on how to send the correct data to the RSP for video output though. Can anyone offer me a hand here? Not on helping me program, but with information regarding N64's RSP and how to program it to display text, etc.

# Answer
To do something basic like a Hello World program on a console like the Nintendo 64 you wouldn't need to use the GPU to do the rendering, you can just write your message directly to the framebuffer. The framebuffer is were the rendered image is stored before it's scanned out to the TV.

The RCP Documentation linked to at the bottom of this page does a very good job of describing the registers you'd need to modify in order to setup the framebuffer: http://www.dragonminded.com/n64dev/

After setting it up just copy your message as a bitmap to the framebuffer and you're done.
> 1 votes

# Answer
Like this:

```
lw 0bRRRRRGGGGGBBBBBA, 0x04400000
lw 0x0140, 0x04400000
sw 0x0140, 0x04300000
sw 0bRRRRRGGGGGBBBBBA, 0x04300000

```

This sets up the framebuffer using 16-bit color depth, 320x240, and interlaced video with 60Hz timing signals; writing to the screen afterwards can be done various ways.
> 0 votes

---
Tags: software-engineering, graphics-programming, console, nintendo
---


# Question
Title: How to apply game progression changes on screen loading in a Zelda like game
I'm trying to develop a 2D game like Zelda. The game is divided in screens with exits linking each other. I store each screen data (including objects and NPC positions) on a separate file, and when the main character steps on the exit, the next screen data is parsed and the screen is loaded. Everything works just fine so far.

I'm now trying to implement the game progression system, along with the save system. I've read a lot about some ideas on how to do that, finite state machine design, what to store on save files, serialization and everything, but I'm kind stuck here.

Let's say that action X triggers event Y, moving some NPC from point A to point B. The player then saves and quits the game. When the game is loaded, it must position that NPC on point B. To achieve that, should I rewrite the files that contains screen data so when the screen is parsed it draws the NPC on its new place? Or should I store its new position on a separate file, and apply the changes on the screen after its loaded? Or maybe there's a better and less ugly way.

Any suggestions are welcome.

# Answer
A common solution for this is to have variables you save together with the players state and objects which have a conditional state depending on these variables.

Example:

1. When the player flips the switch on screen 42, you set the persistent variable `"switch_42_state"` to `"flipped"`.
2. On screen 76, you have a conditional door tile. When `"switch_42_state"` is `"flipped"`, it is loaded as an open door, otherwise it is loaded as a closed door.

Similarily, you can have NPCs which only spawn when certain variables are set to specific values or which have different dialog depending on the variables.

**Implementation detail**: It is usually advisable to not use "real" programming language variables for this. It is usually better to store the variables and their states in a key/value data structure (binary tree, hash map, dictionary, associative array or whatever is available in your programming language), because it allows you to add new variables just by mentioning them on a screen file, makes saving and loading more straight-forward and avoids name collisions with internal variables.
> 3 votes

---
Tags: savegame, progression
---


# Question
Title: multiple flash timeline animations with actionscript
I am not new to AS3 and Flash but new to Flash timeline animations and controlling them with AS3. Had posted a similar question last week but the solution did not work. Hope someone could help me out here.

I am trying to control two different animations separately for one of my horse gameobjects inside the timeline through AS3.

For now, I have inserted really basic keyframes that hold all my animation frames. I have labelled them appropriately. Please look at the image below. These are not full animations, for now I am just playing around and testing it out.

I have named all the frames labels like "startwalk" "endwalk" "startTurnBack" and so on..

Now I want to control these animations and play them individually using AS3. I have added an enter\_frame listener and started with a basic code as below but it does not seem to be working.

```
// this is the Event.ENTER_FRAME named gameLoop
private function gameLoop(event : Event) : void {
            trace(" current label " +horseTwo.currentLabel);
            var currLabel:String = horseTwo.currentLabel;
            var next:String;
            next = currLabel;
            horseTwo.gotoAndPlay(next);
            if(currLabel == "endwalk"){
                horseTwo.stop();
            }
        }

```

Nothing gets played. But if I do horseTwo.play(), it plays the animation throughout which is not what I want. I want to be able to control the keyframes via labels separately each for Walk, TurnBack and few more animations. Anyone got any ideas?

# Answer
> 2 votes
**Put the horse animation on play and remove the `horseTwo.gotoAndPlay(next);` line from the event listener.**

The problem is the `horseTwo.gotoAndPlay(next);` line. With that you are always returning to the beginning of the current label, end the animation never goes forward. The animation plays automatically when it is on play. So you dont need the `var next:String;` and `next = currLabel;` lines either. The event listener will stop it on label *"endwalk"*.

In my test the code works with these changes.

---
Tags: flash, actionscript-3
---


title: Health bar in unity

text:
# Question
Title: Health bar in unity
I have created a button as my health bar and it must decreasing after a specified time.Here is the code I have written.But the problem,this code is working in the form "Its decreasing the button bar,but when it decreases I mean when the healthbar=0,the bar is extending to the left most side.I need to stop it when the healthbar=0.Can anybody found solution for this please?

```
var healthbar=500;
var bar;

function Start () {
    Invoke("decreasebar",1);
}

function decreasebar(){
    if(healthbar!=0){
        healthbar-=30;
        Start();
    }
}

function OnGUI(){
    bar=GUI.Button(new Rect(200,200,healthbar,10),"");
}

```

# Answer
Your error is on these lines

```
if(healthbar!=0){
    healthbar-=30;

```

Because 500 is not divisible by 30, you get something like this:

50, 20, -10, -30...

What you really mean is

```
if(healthbar>0){
    healthbar-=30;

```

Because you want to decrease if it is bigger than 0, not if it is different than 0 (very important distinction!).

Also, in order to make the logic complete:

```
if(healthbar>0){
    healthbar-=30;
}
// Alternatively, put an equivalent check inside the previous if.
if(healthbar<0){
    healthbar=0;
}

```

That way you make sure that it never goes below 0.
> 2 votes

# Answer
You are only checking to see if healthbar is not zero (`if(healthbar!=0)`), you should rather check if it is greater than 0, like so:

```
if(healthbar>0)
{
   //Do something
}

```

But it might be easier to check if it is less than or equal to zero, so that you can use it to end the game easier, like so:

```
if(healthbar <= 0)
{
   EndGame();
} else {
   healthbar-=30;
}

```

Also, this should not be run inside the Start() function, this is very bad practice, you should rather implement this in its own function and call it inside the Start() function in Unity. I have an example you can try, it is in C#, but you can easily use the Unity documentation to change it to javascript, should you be having problems:

```
public int healthTimer; //Can set in the editor, how often do you want the HP to decrease?
private bool gameOver;

void Start()
{
   ReduceHealth(healthTimer);
}

IEnumerator ReduceHealth(int waitTime)
{
   while(!gameOver)
   {
      yield return new Waitforseconds(waitTime);
      if(healthbar <= 0)
      {
         gameOver = true;
         break;
      } else {
         healthbar-=30;
      }
   }
}

```

This will start when your game initializes, wait the set amount of seconds before checking if your player is dead, he won't be at first so no problem move on and decrease his HP by 30. It will then wait again, and then check if you are dead, or decrease it again and so on until you do die, where it will end the game and break out of the while loop.

Hope this helps you out.
> 1 votes

---
Tags: unity, javascript
---


# Question
Title: How small should touch triggers be at minimum?
Is there a known minimum physical size for reliable touch select triggers, considering *only* selection (no long-press or drag). From personal experience, I would *guess* it to be about 5x5 mm (0.2x0.2 inch). Is there a canonical answer?

Context: I want to make my chess-like game board have as many cells as possible, but I still want users to be comfortable selecting cells, as it will be a frequent action.

# Answer
> 16 votes
There's a comprehensive question on UX about touchscreen button sizes. The recommended size depends highly on your game, but the minimum size is quoted as **9-12mm, about half an inch**, and this is based on the size of fingers.

Keep in mind that this is a guideline, and the cost of ignoring it is that your users *will* tap the wrong thing on occasion.

Depending on your game, you may need to go bigger - sometimes much bigger - than this minimum guideline. Here are some factors that will affect accuracy:

* Do you need to tap quickly? Faster means less accurate
* Will players use their thumbs? Less accurate
* Is your demographic experienced gamers or younger? They may have above-average accuracy
* Will your touch zones be right next to each other or have gaps in between? Gaps make it easier to use

You may also decide to accept a certain amount of input errors, as long as you make it easy for your players to correct themselves. Consider:

* Allowing players to adjust their input after the initial tap
* Add a "confirm" step
* Add an "undo" function
* Add clear feedback during the input to show what the game thinks the input will be
* Reduce the impact of errors

---
Tags: touch, user-experience
---


# Question
Title: Ensuring that a randomly generated galaxy wont place stars inside one another?
I'm attempting to build a game with a spiral galaxy design. In doing so I followed a short guide on making the rough layout of the galaxy.

My code works, but the "stars" (I'm bad with variable names, in this code "star" refers to the central star of a solar system) often clip into one another. Is there a way for me to ensure that no stars will intersect?

Code below is what I'm using to generate my galaxies.

```
    for(var i = 0; i < starCount; i++) {
    var distance : float = Random.Range(minDistance, maxDistance);
    distance = Mathf.Pow(distance, 2);

    // Choose an angle betweeen 0 and 2*PI
    var angle : float = Random.Range(0.0 , 1.0) * 2 * Mathf.PI;
    var armOffset : float = Random.Range(0.0,1.0) * armOffsetMax;

    armOffset = armOffset - armOffsetMax/2;
    armOffset = armOffset * (1/distance);

    var squaredArmOffset : float = Mathf.Pow(armOffset, 2);
    if(armOffset < 0) {
        squaredArmOffset = squaredArmOffset * -1;
    }
    armOffset = squaredArmOffset;

    var rotation : float = distance * rotationFactor;

    angle = Mathf.Round(angle/armSeparationDistance) * armSeparationDistance + armOffset + rotation;

    //Convert polar coordinates to 2D cartesian ones
    var starX : float = Mathf.Cos(angle) * distance;
    var starY : float = Mathf.Sin(angle) * distance;

    var randomOffsetX : float = Random.Range(0.0, 1.0) * randomOffsetXY;
    var randomOffsetY : float = Random.Range(0.0, 1.0) * randomOffsetXY;

    starX += randomOffsetX;
    starY += randomOffsetY;

    var newStar : Transform = Instantiate(star, Vector3(starX, starY), Quaternion.identity);
    newStar.transform.parent = center;
}

```

# Answer
The only way to ensure that is to check previously generated stars coordinates, or make (some of) the variables semi-random, e.g. your angle and radius for next star would constantly grow (radius will reset for next angle of course) for a random value, thus ensuring that no intersection would occur.
> 3 votes

# Answer
You could use some kind of distribution algorithm, like grid-based distribution (overlay Grid, place one star randomly in each grid), cell-based Distribution (same as Grid, but not with squares, but with custom shaped cells) or use a given algorithm like poisson disk sampling.

## ------

Simple, fast and efficient, the grid-based approach is probably your way to go.

Simply overlay a grid, and generate one star in each grid-unit.

**However**, this is highly visible in large-scale projects. If your player can zoom out far enough, he will eventually see that the stars are distributed in a grid and you dont want him to see this, because it looks bad in a topdown-view (my opinion). If the player only sees a small portion of the galaxy or the galaxy as whole so the stars blur together, this should be no problem.

**Bonus:** You can prewrite your grid in an Image. If you take every pixel as a grid-unit, you can easily generate a whatever shaped galaxy simply by generating stars only in the white pixels. If generating several galaxys from the same Image, you get different outputs which share a common shape.

---

More complex with little gain, the cell-based approach has its uses. If the gridshape is to uniform for you, try grouping several grids into one cell, and generate only one star somewhere in this cell. This will break up the grid pattern and make it look a bit nicer.

**However:** This needs more space per star. Instead of utilizing every unit in the grid, you'll only use 1/2, 1/3 or less, depending on the size of your cells. Also creating images to generate from becomes more difficult, as you need more colors to seperate neighboring cells in your image. If going hardcore, you can do it with 4 Colors, even though more colors is better in this case to increase the usability of the image for humans.

**Bonus:** If you create small cells in the arms and large cells in the void between the arms of a galaxy, you can create small wanderers in the void, alone in the dark, housing tremendous treasures and deadly dangers. Just a plot hook.

**Additional Info:** Generating the cells from a regular grid is maybe the easiest, but not necessarily the best approach. But I believe this would lead to far here and would require a new question.

---

Best results, longest way. Algorithms like the Poisson Disk Sampling are advanced distribution algorithms which lead to far better results than the described ones, however require usually more time and/or memory. I will not go into detail about the exact implementation here as it is already described in detail in the link.

The Poisson Disk Sampling is not zhe only distribution algorithm, but the one I'm best familiar with. Googeling Disk Sampling should give hints about other algorithms.

---

**TL; DR** Follow the link and implement this.
> 1 votes

# Answer
Stars are typically separated by distances much greater than the size of a solar system. You could snap the coordinates of each star to some fraction of a light year, and ensure that your solar systems are no larger than that fraction. Keep a hash map of all star positions to ensure that no two stars share the same position.
> 0 votes

---
Tags: unity, procedural-generation, random
---


title: Using libraries in libgdx

text:
# Question
Title: Using libraries in libgdx
This is the first time I'm using libgdx and I've got one problem. I am confused by the web of dependencies and the number of projects and I'm not sure how and mostly where to add a third party library I want to use. It should work both for desktop and android. How is this done?

# Answer
Ashes999 is right there but I took some extra steps in order for it to work so here they are:

1) Create a libs folder inside the core project's root folder and add whatever JARs you got inside it.

2) In the build.gradle file which is inside the main root folder that contains the various platform projects find where it declares the dependencies of the core project and add this:

```
dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
}

```

3) Now you need to refresh your projects for the dependencies to work. An easy way I found to do this is to install this plugin. After you're done right click the `projects -> configure -> convert` to gradle project. Now that they are gradle projects `right click them -> gradle -> refresh all`.

4) By now it should work for the desktop but for some reason android will still not recognize the dependencies and crash. What you need to do is `right click the android project -> properties -> build path -> "libraries" tab` and point it to the jars you placed inside the core/libs folder. After that you also need to go to the "order and export" tab and tick any jars you added. I'm not sure if this is the best way to do it but it works.
> 4 votes

# Answer
It depends how you want to do it. libGDX "recently" moved to Gradle, which, among other things, manages dependencies for you. Your options:

# Do it the Gradle Way

* Open up `build.gradle` for both projects
* add the right dependency under `dependencies`

You find the exact string, you need to use Maven Search, then click on the version number, then click on `Gradle/Grails`.

For example, for JUnit, you would write:

`dependencies {
 compile 'junit:junit:4.12-beta-1'
}`

# Do it the Pre-Gradle Way

* Make a directory called `libs` (or `lib`, Android is particular about this but I can't recall which one) in your projects
* Download and drop your JAR files within them
* Add the dependencies (as above for Gradle, to to Eclipse via `Java Build Path` setup.)
> 3 votes

---
Tags: libgdx
---


# Question
Title: Rendering order for units behind objects?
Im developing a 2D game with some fake 3D effects (parallell projection). 2D-units are able to walk in front of buildings aswell as behind them, although themselves being just 2d-objects. This leads to a problem I will show you with a series of images (1-5). Can you tell me how to solve it?

Image 1: Animation for objects used in this example: Unit and Building.

Image 2: Unit and Building with animations and the physical bodies used in the game engine. Note the extruding arms and the building overhang enabling units to walk behind it.

Image 3: By using rendering order ground(0), units(1), buildings(2) the overall goal is reached. But as you can see the limbs of the unit is hidden by the building. This is my problem. How to solve it?

Image 4: I have tried splitting the building in a "front side" and a "back side" for rendering, but that leads to another issue - the corners. (Notice the penetrating hand on the rightmost unit.)

Image 5: So the final quick fix which I would rather avoid is this method: Enlarged buffered physical buildings and shortened unit limbs.

Please, what are youre ideas on how to solve the issues? If it matters, the game is continious and not built on grids or discrete values.

# Answer
You need to enable some kind of z-buffering: first render unobstructed units, then buildings, then units that are obstructed (complete or just partially) by buildings and then the ground. If you render them in this order make sure no pixel is overwritten: do not draw over a pixel that has already been drawn, else only the terrain will render. Flush the buffer when beginning the render process and once a pixel is assigned a value, do not write over it until you flush the buffer again.

> By using rendering order ground(0), units(1), buildings(2) the overall goal is reached. But as you can see the limbs of the unit is hidden by the building. This is my problem. How to solve it?

If you really want to overwrite the pixels (that's what you do from what I can tell), then you need to render them in the inverse order, but it isn't very efficient since some pixels will get assigned some values that will get overwritten by other values. So, the rendering order is ground(0), obstructed-units(1), buildings(2), unobstructed-units(3).

You now need to know if a unit is obstructed or not. You can check the circle of every unit with the square in my image. If they collide then mark the unit as obstructed.
> 2 votes

---
Tags: rendering, projection, objects
---


# Question
Title: How do I deal with floating-point error given a far-away camera?
Whenever a camera is "far" away (its location is some "large" vector), trouble arises when rendering objects close to it: It is the classic precision loss from subtracting 2 floating point numbers.

I know these ways around it:

* **using doubles** for projection/viewing transformations (may not be feasible/possible on mobile devices),
* **doing the subtraction on the CPU** (with doubles or integers) and uploading the (relative) position of the object into the shader. This position vector is then added to the vector, that is to be transformed in the vertex shader,
* **tweaking the camera view matrix or model matrix**. These matrices are then combined on the CPU and uploaded.

How do these methods compare? Have I missed some other approach?

# Answer
I think you could look at how the Infinity Engine (now I-Novae Engine) solved this issue. (Unfortunately I can not find the blog post anymore.)

First the engine maintains multiple levels of resolution, depending object importance. For the outermost scale it uses 128 bit floating points, which is enough to model the solar system reliably at meter scale. (I did not do the math...)

The underlying problem is, that anything the scale of planets, even 32 bit floats start to quickly loose resolution. But on the other hand using anything other than 32 bit floats for rendering is unbearably slow. (At least it was at time.) Since they wanted "infinite" view distance, this posed a real problem.

They approached the problem with three solutions:

First the engine create a separate scene for rendering that is centered around the camera. This ensures that the little objects where precision matters are correctly placed. (Little details are procedurally filled in.)

Really large and far away objects, like space stations, planets or an entire nebula are rendered separately. In many cases they are scaled so that they properly fit into the range of the 32 bit floats. This is then put into a the final scene using billboarding.

Finally everything that is farther away than a certain threshold is submitted for rendering using a logarithmic scale. This is primarily done, to preserve z-buffer resolution for near objects while still being able to render the space station in front the gas giant.
> 3 votes

---
Tags: transformation, projection, floating-point
---


title: Setting bounds to a label in libgdx

text:
# Question
Title: Setting bounds to a label in libgdx
```
textStyle = new LabelStyle();
textStyle.font = font;
textStyle.fontColor=Color.GREEN;

EnterTextCasheir= new Label("",textStyle);
EnterTextCasheir.setBounds(AssetsHelper.convertWidth(158),
        AssetsHelper.convertHeight(162),
        AssetsHelper.convertWidth(180),
        AssetsHelper.convertHeight(55));
EnterTextCasheir.setWrap(true);
EnterTextCasheir.setFontScale(1f, 1.5f);
EnterTextCasheir.setSize(CashierCounterEnterBoxZoomImage.getWidth(),
        CashierCounterEnterBoxZoomImage.getHeight());

table4.addActor(EnterTextCasheir);

EnterTextCasheir.addListener(new InputListener() {
    private boolean EnterTextCasheirBol;

    public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
        if(!EnterTextCasheirBol)
        {
            EnterTextCasheirBol = true;
            Gdx.input.getTextInput(new TextInputListener() {
                private String CasheirBoxStg;

                @Override
                public void input (String text) {
                    EnterTextCasheirBol = false;
                    EnterTextCasheir.setText(text);

                    CasheirBoxStg = (String) text;
                }
            }
        ...
        }
    }
}

```

Its my brief code;I am not able to display the text into single line ;its coming in 2 lines can anyone help me to resolve.Thank you

# Answer
> 0 votes
If you don't want multiple lines change:

```
EnterTextCasheir.setWrap(true);

```

to

```
EnterTextCasheir.setWrap(false);

```

You'll likely also have to increase the width of your text box. Wrapping occurs when the text doesn't fit in the specified width, it wraps to a new line.

Alternatively you can use less text or just make the text box wider.

---
Tags: java, libgdx
---


# Question
Title: How to move towards a point in 2D, stopping at obstacles
I want to do a 2D game, where you can mouse click anywhere on the map and the player will go there. If there is obstacle in the way, the player will go as close as possible to where you clicked without going into the non-walkable area. What would be the optimal way to accomplish this?

# Answer
> 1 votes
If you want, you can predict your movement with the **Periodic Interference Test (PIT)**, which is fancy for *"Place myself in the next position and if I collide with something, revert me to the last safe position"*. This is fast, easy, relativly safe and should be sufficient for your game as long as you don't move to fast (aka make two big jumps in a frame).

**However:** I can guarantee you that you never will come as close as possible to your obstacle. Simply the fact that you make jumps of a fixed size guarantees that you are somewhere in the Interval `[0,stepSize)` next to your target.

---

If you want the best possible answer, use **Predicted Instant of Collision (PIC)**. This will compute your way before you actually take your step, and, if it finds an obstacle, moves you only as close as possible without colliding the obstacle. This will bring your Player nearly to `0` distance to the obstacle.

**However No. 1:** This works only for linear pathes! For a solution for non-linear pathes relate to this question at stackoverflow.

**However No. 2:** PIC is relativly trivial for round objects (disk/spheres). You seem to use a Square as player, which might lead to a problem. You can use a *bounding disk* around your Square to get close and then use really small steps to approach the obstacle (aka a tiny PIC).

---

A good explanation for PIT and PIC can be found here and here.

An alternate solution is described here

# Answer
> 0 votes
Given you can do a discrete collision check between the agent (that is you player) and all the obstacles you can do something like this:

```
while ( not_found_collision )
{
    move the agent a distance D along the path; // D must be small enough to prevent
            // tunneling - the radius of a sphere that is fully contained in the agent
            // shape should be enough --- for a square, that is its edge length
    check if it now collides with any obstacle;
    if it does
        execute bisection until the error is small enough
}

```

For what bisection actually is take a look here

Also, did you considered using a 2D engine, like Box2D?

---
Tags: collision-detection, movement
---


title: LibGDX ShapeRenderer rotated

text:
# Question
Title: LibGDX ShapeRenderer rotated
I'm having a weird problem with the LibGDX ShapeRenderer where it draws everything rotated. Here are some images to show you what i mean:

This is what it looks like in Tiled(Map Editor):

This is how it looks like in game:

As you can see, its rotated.

Heres the Code i use to render the mapobjects:

```
    shapeRenderer.setProjectionMatrix(cam.combined);
    shapeRenderer.setColor(1, 1, 0, 1);
    shapeRenderer.begin(ShapeType.Line);
    for (RectangleMapObject o : MovementSystem.objects.getByType(RectangleMapObject.class)) {
        Rectangle rect = o.getRectangle();
        shapeRenderer.rect(rect.x, rect.y, rect.height, rect.width);
    }

    shapeRenderer.end();

```

The rectangle is positioned at the right place and it is definitely NOT rotated! I checked this with a small collision detection test where i moved another rectangle over this one. So it just gets drawn like this and i have no idea why^^ Would be nice if anybody could help me :)

Thanks for your help in advance!

# Answer
> 1 votes
Swapping the width and height in ShapeRenderer.rect should fix the problem, see the documentation.

---
Tags: java, libgdx, rendering, map-editor
---


title: Consistent Space Gravity Simulation

text:
# Question
Title: Consistent Space Gravity Simulation
I have done some reading into this subject but haven't been able to come to a conclusion that I'm really satisfied with so far, so here is the situation. I have a game set in space, its top down and essentially 2D as far as physics is concerned and it revolves around the gravitational interaction between planets and black holes. I'm using Unity, so I have the ability apply forces to bodies. However, I have to do all the gravity calculations myself... This is where I get stuck.

Now it's not the maths that I'm having trouble with, maths I can do, its general game "feel" that is the sticking point. Originally I tried Newtons standard gravitational equations but I found that to a general user they produce unexpected behaviour. If you place two different mass planets on either side of a central black hole, both the same distance away, they will reach the central black hole at the same time (which "feels" odd). I also played around with more primitive implementations that just manipulate distance and mass in different ways but I always ended up with the same issue; as the planets im using undergo dramatic shifts in mass over the course of the game, the effect of the black holes always starts off being overly erratic (at low body masses) and then moves to being overly sluggish (at high masses) giving the game a very inconsistent feel at the moment.

Has anyone run into the same issue here and come out with a good way of simulating gravity in space? Does anyone know of examples of where this has been done before? What are some things that I may have overlooked or may want to take into consideration in the calculations? Remember that realism isn't the main concern here, its game "feel".

I'm open to any and all suggestions here so don't hesitate to put forward any sort of crazy answers!

# Answer
The problem is that bodies only ever move towards stable orbits in 3D. In 2D they will not tent to move towards stable orbits using "realistic" physics. If you do want to get a stable orbit you will need to mess with the formula's that dictate speed. Completely forgoing Newton's laws in favour of a system with completely different exponents. For more information on orbits in various situations see here A second method is the just create a 3D model where all objects have very similar z-values, this is actually very close to how the actual milky way and solar system are.
> 1 votes

---
Tags: unity, physics
---


# Question
Title: Does `yield return false;` have special meaning in Unity3d C# scripts?
In Unity, we have some special things for coroutines that are additional to normal C#.

for example, we can use

`yield return WaitForSeconds(5.f);`

to have a coroutine wait 5 seconds before continuing.

What do `yield return false;` and `yield return true;` do?

# Answer
> The only possible yield values the scheduler understands are:
>
> * Classes derived from `YieldInstruction` (`WaitForSeconds`, `WaitForEndOfFrame`, `WaitForFixedUpdate`, `AssetBundleCreateRequest`, `AssetBundleRequest` and Coroutine
> * a `WWW` object
> * **"any other value"** which isn't one of the above.
>
> If **"any other value"** is yielded (which includes "null" a string value any other basic type such as int, **bool**, ... or a reference to an arbitrary object which isn't one of the above mentioned) the scheduler will **"schedule" the coroutine for the next frame**.
>
> *\- Bunny83 answer: Prominent member on Unity Answers*

The `WaitForEndOfFrame` and others of the like, are just blank functions that tag the `YieldInstruction` in order to decide what to do in the engine.

The default case seems to be `WaitForEndOfFrame`. So if you `yield return` something that doesn't have a special meaning, such as a bool, it is the same as `WaitForEndOfFrame`.

There doesn't seem to be any official documentation on this behavior.

---

## Update

**rutter** commented about another special case: `yield return null`

All of the Unity Coroutines including `yield return null`, run before the frame renders except for `WaitForEndOfFrame`. You can find **rutter**'s awesome answer over at Unity Answers explaining this further (nice diagrams included).
> 19 votes

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


# Question
Title: (XNA) Possible to hide, compress, or rename .XNB files?
I'm fairly new to XNA (only a week into C# and XNA at this point) but I have been developing games for a while now, and the program I used did not require any/many external files in creating an executable. I am perfectly fine with external files (for the most part) but reading around, it seems as if .XNB files are easily accessed for others to pull your resources out of.

After some thinking, I was wondering if it was possible to do any of these 3 things: 1. Hide the .XNB files within the .exe in which case it would likely create them in an external location only during run-time (wouldn't really solve the main issue, but still)? 2. Compress many of the .XNB binaries into a single binary (such as 1 for sounds, 1 for sprites, etc.) 3. (This one is one simply for my own OCD) Change the extension name from .XNB to something of my choosing? For example, to .DAT instead to make it less of a direct indicator I used XNA and/or these files can be accessed with an .XNB ripper?

None of these would particularly solve my initial problem, but I still wonder if they are possible. Anyhow, thanks in advance guys!

# Answer
> 1 votes
To answer the three of your questions with one answer: sure you could, but you wouldn't be able to use the default content manager.

However, you can create custom content processors to output file data in a format that only you would immediately know. This would still allow you to use the default XNA content manager (`this.Content` in any Game-derived class) as well as allow you to protect your assets in any way you want. The generated content files would still have the `.xnb` extension, but they would not have the typical `.xnb` format. (You may be able to change the extension, but I'm not sure.)

# Answer
> 0 votes
Yes, you can implement your own content manager.

http://romsteady.blogspot.com.es/2011/07/use-zip-files-to-hold-your-xna-content.html

```
public class ZipContentManager : ContentManager
{
  private ZipFile zipFile = null;

  public ZipContentManager(IServiceProvider services, string zipFile) : base(services, "")
  {
      this.zipFile = new ZipFile(zipFile);
  }

  protected override System.IO.Stream OpenStream(string assetName)
  {
      var entry = zipFile.GetEntry(assetName.Replace('\\','/') + ".xnb");
      if (entry != null)
      {
          return zipFile.GetInputStream(entry);
      }
      return null;
  }
}

```

---
Tags: xna, compression, binary, extension, reinforcement-learning
---


title: Bullet - objects falling through

text:
# Question
Title: Bullet - objects falling through
I have problem with bullet collisions. You can see problem on this video (around 0:18):

http://goo.gl/DiVP8l

Objects are "embeded" inside vertical bars - that is not correct - they should be bouncing like at the beggining of the video. I am using sphere and box as bullet bodies. I have also enabled CCD, that improves stability a little, but problem is still there.

Pulsing bars are controlled with this code:

```
dist = distance I need the bar to change its position in a single frame
float g = (2 * dist) / (times.dTime); //dTime = 1/60
bars[i]->GetBulletBody()->setLinearVelocity(btVector3(0, 0, 0));
bars[i]->GetBulletBody()->setGravity(btVector3(0, speedUpFactor * g, 0));

```

I have constant update rate of physics and world, set to be 1/60 s.

# Answer
The problem is objects movement in digital world is discrete. In real world, it seems natural if a bar extends, it does is over time - computers cannot "move" objects, so they simulate this behaviour by setting their position by small steps *dS*.
However, if the movement of an object is too fast, it can produce weird resulst like shown on video - bars actually trapped balls below if extended too quickly.
There are generally three solutions:

* make smaller steps - instead of moving *t * dS* each frame, move *n* times *t/n * dS*
* non-discrete intersections - instead of point intersections use line segments
* repair what is broken - if there is an illegal state (ball inside bar), fix it
> 3 votes

---
Tags: physics, bullet-physics
---


title: Controlling depths of objects in Flash

text:
# Question
Title: Controlling depths of objects in Flash
I am trying to change depths/ layers of my gameobjects inside the game using flash. To be more specific, I have a horse object and a fence object. I set them up initially on stage and the horse layer is in front of the fence which is correct like shown below

Now at some point in my game, the horse moves behind the fence. So the Fence layers should now be in Front. Right now, when the horse moves behind the fence, it is still in front because of course its layers has not changed like shown in image below. How do I control this using ActionScript?

Hope someone could throw some ideas here!

# Answer
I figured it out.

I used the DisplayObjects function `swapChildren()` and it did the job!
> 1 votes

---
Tags: flash, actionscript-3
---


# Question
Title: How do I detect a destroyed object in Unity?
I have an object in unity which is spawn through a script. Upon detecting that the object has taken substantial damage, objectDestroy is called and the object is removed.

However, I would like for a message to appear upon having this object destroyed. The code I posted below doesn't work.

```
hudText.Add ("Use Mouse 1 to fire !", Color.red, 2f);

while(trigger==false){
    if(enemy==null){

        Debug.Log ("Gone");

        yield return new WaitForSeconds(1);
        hudText.Add ("Nice work!", Color.green, 3f);

        trigger = true;
    }
    Debug.Log (trigger);
    yield return null;
}

```

I suspect that this has to with the fact that the object is destroyed at the end of the frame, but the while loop here never allows the loop to test for the following frame.

How do I do this?

# Answer
You could use two approaches here; directly calling a function when the object is destroyed, or handling an array of objects yourself.

In the first approach, you could take advantage of the OnDestroy function that belongs to MonoBehaviour.

```
using UnityEngine;
using System.Collections;

public class YourClass : MonoBehaviour {
     void OnDestroy() {
         Debug.Log("I'm gone! (bye, bye)");
     }
}

```

And that function gets called when you do something like

```
Destroy(myGameObject);

```

The second approach is similar but it requires a little more work. It always depend on what you're trying to achieve but I'll give you an example

```
using UnityEngine;
using System.Collections;

public class YourClass : MonoBehaviour {
     public int energy;
     void Update() {
         if (energy <= 0) {
             // you're comparing against a value you know beforehand
             Debug.Log("Gone! (bye, bye)");
             // this will just 'hide' the game object visually, for example
             gameObject.GetComponent<MeshRenderer>().enable = false;
             // or just go with it as usual
             Destroy(this.gameObject);
         }
     }
}

```
> 2 votes

---
Tags: unity, gameobject
---


title: Smooth decelerate, interpolation?

text:
# Question
Title: Smooth decelerate, interpolation?
I have two points A and B. I want to perform a smooth deceleration from A stopping at B over time t. The only thing I managed to do so far was a lerp, which isn't right of course because it's unnatural. I also tried multiplying the velocity by some factor (0.9 or similar), but then I don't know how to choose the factor such that the end point B is reached (or as near to it as some epsilon value seems reasonable).

Does anyone have something relatively simple that I could use? I can read C++ and C# code.

# Answer
Compute the ratio `x` in \[0,1\] of the current animation time and the animation duration `t`. Then use something like `sqrtf(x)` to decelerate. Compute the current position `C = A + x * (B - A)`. You can make it decelerate more rapidly by using e.g. `powf(x, f)` with `f = 1.0f / 3` or smaller.
> 1 votes

# Answer
I would use the "Arrive" behavior from Millington's book *Artificial Intelligence for Games*.

It's important to say that you need to constantly update positionB in order for it to work correctly.

```
float targetRadius = 0.1f;
float timeToTarget = 0.1f;
float maxSpeed = 10.0f;

Vector3 positionA;
Vector3 positionB;
Vector3 agentVelocity;

// calculation for slow radius given the initial
// distance between the two positions
Vector3 dist = positionB - positionA;
float slowRadius = dist.Length();

public Vector3 GetVelocity ()
{
    Vector3 velocity = new Vector3();
    Vector3 direction = positionB - positionA;
    float distance = direction.Lenght();
    float targetSpeed;
    if (distance < targetRadius)
        return velocity;
    if (distance > slowRadius)
        targetSpeed = maxSpeed;
    else
        targetSpeed = maxSpeed * distance / slowRadius;
    velocity = direction;
    velocity.Normalize();
    velocity *= targetSpeed;
    velocity -= agentVelocity;
    velocity /= timeToTarget;
    return velocity;
}

```
> 1 votes

---
Tags: interpolation
---


# Question
Title: Correct method for choosing the user's video cards?
My game uses DirectX 10, and I'm having a problem where users are reporting that my game isn't picking up on their graphics card. Instead it prefers to run on their integrated Intel card, ruining performance. It's possible that this is related to Windows 8. It could also be related to mobile cards.

Until now, I've been creating the DirectX 10 device with no adapter specified (as I've seen in all the examples/demos so far), to allow DirectX to choose its own adapter. Apparently I'm going to have to change that.

I already have a function which runs through all of the available adapters, and chooses the one with the highest amount of dedicated memory. That works great for correcting the problem, but is it correct in general?

Unfortunately, I cannot rely on the card having valid video output (i.e: a monitor hooked up) as the machines affected by this problem report no outputs for the desired card.

What algorithm can I use to properly choose which adapter to use with DirectX?

# Answer
> 11 votes
Selecting the adapter with the highest available dedicated memory might work in a lot of cases, but in some cases a GPU with less processing power might have more dedicated memory, and your game will still run on the "wrong" adapter.

This brings me to a counter-question, what is the right adapter? The one with the most computational power? The one with the most memory? The one where the main display is attached to? The one that consumes the least power? All these questions probably have different answers per user. Someone using a laptop might prefer long battery life over better graphics. Someone might prefer playing on his secondary monitor (e.g. a TV) instead.

Therefore, lots of games let the user decide what GPU they want to use. Most GPU manufacturers have control panels where the preferred GPU (even per application) can be chosen. Some games have a startup dialog that allows the user to explicitly select the preferred GPU. This startup dialog is often only shown on the first run or after crashes, so it can also act as a nice recovery tool.

Nvidia preferred GPU selection, AMD preferred GPU selection, Flatout 2 preferred GPU selection

# Answer
> 3 votes
I would allow the player to choose which video card to use, i.e. through a drop down list in the options menu. You can use the GPU with the highest detected VRAM, clock speed, etc. as a sane default. You could go further and prompt the player to choose between "high performance" and "power saving" (chooses the lowest-spec card) for the default when the game is first started up, and then let them be more specific with their choice in the options menu.

This is a simple solution that also won't annoy the player if it chooses the undesired video card, as it is easy enough for them to change it if it picked the wrong one.

# Answer
> 2 votes
If you are picking the adapter based on the one with the most memory, you may be having trouble accurately detecting the amount of memory used by Intel HD Graphics. Intel HD Graphics has access to two banks of memory; one dedicated and one shared with the CPU. The size of the two banks are reflected in the DXGI\_ADAPTER\_DESC structure as DedicatedVideoMemory and SharedSystemMemory. For purposes of comparison with other adapters, you might use just the dedicated bank or you might use both.

Intel has a GPU detect sample that also shows how to measure both banks of memory.

---
Tags: directx, directx10, gpu, windows-8
---


# Question
Title: How do I move my character using accelometer (android)?
I created a class for accelerometer, and there are no errors, my game does not crash when I run it, but my character does not move when I tilt my phone. I have been trying to figure out how to use the accelerometer for some days now, but every tutorial uses it in an activity, and there is no activity in my application.

Here is the code:

```
package com.saladchef.bananasplit;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

public class MyAccelerometerClass implements SensorEventListener {
private SensorManager sensorManager;

public float x, y, z;

public MyAccelerometerClass(Context context) {
    sensorManager = (SensorManager) context
            .getSystemService(Context.SENSOR_SERVICE);
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
    // TODO Auto-generated method stub

}

@Override
public void onSensorChanged(SensorEvent event) {
    x = event.values[0];
    y = event.values[1];
    z = event.values[2];

    if (y == 0.0){
        Banana.stop();
    }
    if(y >= 1.5){
        Banana.moveRight();
    }

    if (y <= -1.5){
        Banana.moveLeft();
    }

}

public SensorManager getSensorManager() {
    return sensorManager;
}

public void setSensorManager(SensorManager sensorManager) {
    this.sensorManager = sensorManager;
}

public float getX() {
    return x;
}

public void setX(float x) {
    this.x = x;
}

public float getY() {
    return y;
}

public void setY(float y) {
    this.y = y;
}

public float getZ() {
    return z;
}

public void setZ(float z) {
    this.z = z;
}

// codes

```

}

# Answer
You need to register listener and get sensor, see official site.

```
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mLight = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);

@Override
  protected void onResume() {
    super.onResume();
    mSensorManager.registerListener(this, mLight, SensorManager.SENSOR_DELAY_NORMAL);
  }

  @Override
  protected void onPause() {
    super.onPause();
    mSensorManager.unregisterListener(this);
  }

```
> 1 votes

---
Tags: android
---


# Question
Title: "Running" against a steep slope on a Box2D Platformer
Ive seen alot of pages talking about how to emulate a platformer on Box2D, specially about how people dont want to slide down a slope. Well, my problem is different and Im surprised I cant find posts/solutions about it.

The problem happens when I have a very steep slope and I run against it. This is what happens:

Being the square a common platformer hero fixture, since in a Box2D platformer the movement is based on applying impulses or setting the velocity, what happens when I "move" torwards such a slope, its like im pushing against it, which creates a vertical force and therefore the square moves UP (specially since friction is 0 to avoid the "sticking to a wall" thing).

I've solved most of Box2D's non-platformer-proficient issues. This one seems unsolveable.

So, how do I avoid my object to go up a steep slope when pushed against it, and instead slide down since its too steep to be climbed?

# Answer
> 1 votes
I think you are approaching this the wrong way. Box2D is doing exactly what you want it to do, the problem may be with what you want. I assume you are applying gravity? If the force of gravity is less than the upward velocity from your character running against the slope, you are probably applying too much force (or too little gravity) while making your character run. Try adjusting the mass of your character and the strength of forces being applied to it.

Also, if you do not want your character to run up a slope, maybe he should not be running? Maybe it is your design that should change, not the physics. However, it is hard to tell since your question mentions little about the game design. If you want him to stop running while the player is giving the input that the character should be running into a steep slope, one solution is to put a sensor in front of the character that will slow or stop his forward velocity. Sensors for exactly this type of thing are a built-in part of Box2D.

Edit: Another suggestion is to add friction to the slope. This will help allow a weaker gravity to stop the player from pushing up the slope.

---
Tags: box2d, platformer, jbox2d
---


# Question
Title: How to have an event occur after x seconds?
I want a method to run after every 10 or 15 seconds.

My timer is set to:

```
timer = (double) gameTime.ElapsedGameTime.TotalSeconds;

```

What would be the logic to check for every 10 or 15 seconds?

# Answer
There's no magic way to do this in MonoGame that I know of. The basic idea is fairly simple though; create a variable to keep track of the delay and when it gets to zero fire your method.

The simplest way to do this is to introduce a member variable in your Game class to keep track of the remaining delay and have it fire your method when the delay reaches zero, then reset the delay each time.

```
    private const float _delay = 15; // seconds
    private float _remainingDelay = _delay;

    protected override void Update(GameTime gameTime)
    {
        var timer = (float) gameTime.ElapsedGameTime.TotalSeconds;

        _remainingDelay -= timer;

        if(_remainingDelay <= 0)
        {
           MyMethod();
            _remainingDelay = _delay;
        }

        base.Update(gameTime);
    }

```

A slightly more fancy approach is to create a class to encapsulate the logic. I have one in my engine called a DelayedAction.

```
public class DelayedAction
{
    public DelayedAction(Action action, float delay)
    {
        TimeRemaining = delay;
        Action = action;
        Delay = delay;
    }

    public Action Action { get; private set; }
    public float Delay { get; private set; }
    public float TimeRemaining { get; private set; }

    public bool Update(float deltaTime)
    {
        TimeRemaining -= deltaTime;

        if (TimeRemaining <= 0)
        {
            Action();
            return false;
        }

        return true;
    }
}

```

The idea here is very similar, except that you can create more than one instance of it and run them in a loop. One difference with this implementation though is that it returns false after the action has fired rather than repeating the action over and over. I'm sure you could make the modifications to make it repeat if so desired.
> 4 votes

---
Tags: c#, monogame, timer
---


title: Slots Machine Matching feature

text:
# Question
Title: Slots Machine Matching feature
I'm designing a slot machine.

I need to find the number of combinations that two matching icons will appear side-by-side in a 3X5 window (3 rows, 5 reels (columns))

A match gives the user some payout.

Having the following assumptions: Icons: H1, H2, X (all the rest). Matching Icons: should meet on the same row (side by side) (wild doesn't count here)

Window is as follows:

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

```

I have listed all possible options, and now I would like to get the exact number of combinations per each option.

Example of what I need:

The number of possibilities for this kind of scenario (1 of 72 possible ones):

```
| H1| H2| X | X | X |
---------------------
| X | X | X | X | X |
---------------------
| X | X | X | X | X |

```

Number of H1 icons on reels 1-5: R1\_H1, R2\_H1, R3\_H1, R4\_H1, R5\_H1

Number of H2 icons on reels 1-5: R1\_H2, R2\_H2, R3\_H2, R4\_H2, R5\_H2

Number of all icons on reels 1-5: RL1, RL2, RL3, RL4, RL5 (respectively)

Some more examples:

```
| H1| H2| X | X | X |
---------------------
| X | X | X | X | X |
---------------------
| X | X | X | H1| H2|

| H1| H2| H2| H1| X |
---------------------
| X | X | X | X | X |
---------------------
| X | X | X | X | X |

```

And so on.. the only limitation I put is that H1 and H2 icons on the same reel have distance between them so I won't have kind of the following scenario:

```
| H1| H2| X | X | X |
---------------------
| X | X | X | X | X |
---------------------
| X | H1| H2| X | X |

```

# Answer
First you need the probability they'll be on the same line at all.

Then, go through each possible position on a line for H1, counting the number of possible H2 positions that pay out, and those that don't. The probability is payouts/(payouts + non-payouts).

Multiply the two probabilities and you'll have your answers.

There are more mathematically elegant ways to do this, or you could write a small program to brute force it, but for small numbers like this it's not really necessary.
> 0 votes

---
Tags: game-mechanics
---