title: Putting items into a 3D space

text:
# Question
Title: Putting items into a 3D space
Imagine a fridge and a bunch of random foods. I want to take one food item, automatically put it somewhere in the fridge, and repeat. I can stop at any time.

Basically, the filled fridge should look like it has been gradually stocked over the course of a week or so (as opposed to deliberately organized at once) by a calm human being (as opposed to by someone who's just thrown things into it).

Formally, this procedure has to satisfy the following:

* Similar items should stack or be next to each other given that there is sufficient space (ex. egg cartons cases go in one stack, 2L milk cartons go side by side)
* Other items should not stack until there is no more space left at the bottom
* Placed items should be as upright as possible (ex. plastic-wrapped leftovers shouldn't be sideways), unless limited space requires rotation
* Items should be put somewhere in the center of the fridge when it is relatively empty (instead of being squished to one side)
* The procedure should automatically stop when the fridge no longer has any room left

Ignoring any dividing racks that may be present in the fridge (say it's just one big container), how should this be done? What variables would I need to define with an `Item`, and/or what algorithms should I use to determine where to put the next item and how to find out which angle of rotation will give me the fit?

# Answer
This appears to be a "do my homework for me" type of question. There is no special algorithm or a clear answer. Still, it's a somewhat interesting piece of homework. :)

And since there is no special algorithm, I'd implement it using the equivalent of constraint relaxation in physics. All the things you have stated as requirements are rules, or constraints. Which basically means that you can insert any new item anywhere, and then adjust the positions of all items to fit the rules:

* Items too close to each other? Move them further apart.
* Eggs are placed near some milk cartons and now you've got no space for more milk? Swap them.
* Can't insert a new item because of lack of continuous space? Move other items closer together, trying to make space at the best-fit position first.

Just like in real life people have limited amount of time and interest to deal with their fridges, you can assign a cost to every action and use that to limit the number of actions to take.

The complexity of the simulation is very much up to you, though. I wouldn't go for packing algorithms for placement, at least not at first - moving things further apart or closer together is much easier to do on a straight line, followed by collision resolution of convex polygons. It's pretty much unnecessary for a tiled grid of the right size, so that's a good option as well.

The reason for me being against packing algorithms is that every one of them I've seen requires a complete repack of all items on any change, always tightly together, which I think you wanted to avoid. Since most packing algorithms tend to fill a side or two first, scaling the packed data to the full size for proper spacing probably won't work as well.
> 1 votes

# Answer
You might want to look into Packing Problems, specifically Bin Packing (google for more sources).

Angle of rotation is a little more difficult and the easiest you can do is to use an axis-aligned bounding box (AABB) to represent objects with non-axis-aligned orientations. These AABBs then are what you pack:

...which means things will look a little strange, with spaces between the objects (space between blue and red wireframes in diagram). For better accuracy than this, you'd have to use some sort of physics engine, place the object and let it settle according to it's actual shape and the shapes of its neighbours, and then lock the physics state to ensure no further perturbations - a lot of trouble but perhaps worth it for you. If you want accuracy, a physics engine is the only sane approach.

As for uprightness, placing near centre etc., it should become clear to you how to tackle those issues once you have basic bin packing working, which applies whether or not you use physics.
> 0 votes

---
Tags: 3d, algorithm
---


title: Making a house in jogl java eclipse?

text:
# Question
Title: Making a house in jogl java eclipse?
here's what I'm trying to do: One house, with 3 rooms, a window in two rooms, doors in the front and back of the house and into each room (the back door has to be through one of the rooms). I've added a picture as an example I'm using JOGL 2.0, in eclipse.

Clarification: my question is how do I code it in java using jogl?

This is what I have so far:

```
    glBegin(GL_QUADS)
    /* Floor */
    glVertex3f(-1,-1,-1);
    glVertex3f(1,-1,-1);
    glVertex3f(1,-1,1);
    glVertex3f(-1,-1,1);
    /* Ceiling */
    glVertex3f(-1,1,-1);
    glVertex3f(1,1,-1);
    glVertex3f(1,1,1);
    glVertex3f(-1,1,1);
    /* Walls */
    glVertex3f(-1,-1,1);
    glVertex3f(1,-1,1);
    glVertex3f(1,1,1);
    glVertex3f(-1,1,1);

    glVertex3f(-1,-1,-1);
    glVertex3f(1,-1,-1);
    glVertex3f(1,1,-1);
    glVertex3f(-1,1,-1);

    glVertex3f(1,1,1);
    glVertex3f(1,-1,1);
    glVertex3f(1,-1,-1);
    glVertex3f(1,1,-1);

    glVertex3f(-1,1,1);
    glVertex3f(-1,-1,1);
    glVertex3f(-1,-1,-1);
    glVertex3f(-1,1,-1);
    glEnd();

```

# Answer
> 2 votes
You should model the house in a 3D modeller like Blender and export it into .obj and read it into your application. Listing vertices for complex objects is cumbersome and listing them here as an answer doesn't add value.

---
Tags: opengl, java, eclipse
---


title: Render time only equal half of fps

text:
# Question
Title: Render time only equal half of fps
I'm working on a project that remakes mario 3 (NES). In my game loop, i face a strange thing. Here is my code:

```
 while (true)
{
    if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
    {
        if (msg.message == WM_QUIT)
        {
            break;
        }
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    else
    {
        //Game logic
        c1++;
        _Mario.Update(1.0 / FPS);

        //Render
        _Timer.SetBeginTick();
        _LpD3dDevice9->Clear(0, 0, D3DCLEAR_TARGET, D3DCOLOR_XRGB(102, 255, 255), 1.0f, 0);
        if (_LpD3dDevice9->BeginScene())
        {
            c2++;
            _Mario.Render();
            _LpD3dDevice9->EndScene();
        }
        _Keyboard->GetState();
        _Mario.Move(_Keyboard);
        _LpD3dDevice9->Present(0, 0, 0, 0);
        _Timer.SetCurrTick();
        _Timer.UpdateGameTIme();
        if (_Timer.ElapsedTime < (1.0 / FPS))
        {
            Sleep(1000.0 / FPS - _Timer.ElapsedTime * 1000);
        }
    }
}

```

Update function :

```
void ImageMove::Update(float t)
{
    _Image_X += _Image_Vx * t;
    _Image_Y -= _Image_Vy * t;
    _SpriteTimer.SetCurrTick();
    _SpriteTimer.UpdateGameTIme();
    if (_SpriteTimer.ElapsedTime >= 1.0 / ANIMATE_RATE)
    {
        if (_Image_Vx > 0) _Image_Right.Next(); //change to next sprite
        if (_Image_Vx < 0) _Image_Left.Next(); // change to next sprite
        _SpriteTimer.SetBeginTick();
    }
}

```

Render Function :

```
void ImageMove::Render()
{
    int vpx = _Image_X - 400;
    int VIEW_PORT_Y = _Image_Y + 500;
    _SpriteHandler->Begin(D3DXSPRITE_ALPHABLEND);
    if (_Image_Vy > 0 && _Image_Vx_Last > 0) _Image_Jump_Right.Render(_Image_X, _Image_Y);
    else if (_Image_Vy > 0 && _Image_Vx_Last < 0) _Image_Jump_Left.Render(_Image_X, _Image_Y);
    else
    if (_Image_Vx > 0)_Image_Right.Render(_Image_X, _Image_Y);
    else if (_Image_Vx < 0)_Image_Left.Render(_Image_X, _Image_Y);
    else if (_Image_Vx_Last < 0)_Image_Left.Render(_Image_X, _Image_Y);
    else _Image_Right.Render(_Image_X, _Image_Y);
    _SpriteHandler->End();
}

```

I put c1 and c2 in my game loop to measure how many times Update and Render are called. I set fps = 60, while debuging, I let my game loop run for 5s, then set a breakpoint to view c1 and c2. The value of c1 = 320, and c2 = 160 ( = 1/2 c1 for sure, i have run it many times, so the times render is called only ~1/2 fps, i think with fps = 60, it should be ~300 for 5s, shoudn't It?).

If i debug with F10 (on Visual studio) , I can see a loop will execute with `_LpD3dDevice9->BeginScene()` success, and `_LpD3dDevice9->BeginScene()` in next loop always failed.

Is it error? Because i have tested on another small project, and c2 = 1/2 c1 too. This problem cause an issue in my game. In Update() function, I change my sprite here, and draw it in `Render()` , so I always miss some sprite. Because It only render = 1/2 time game update.

If it is an error How can I fix my game loop? And if It is not an error, what can I do to prevent missing sprites?

P/S : sorry for bad English.

# Answer
> 1 votes
I think documentation on : IDirect3DDevice9::EndScene method can enlight

"When this method succeeds, the scene has been queued up for rendering by the driver. **This is not a synchronous method**, so the scene is not guaranteed to have completed rendering when this method returns."

As the EndScene is not syncronous , you are not garanted that the next loop you're ready for a new BeginScene. Try using less FPS.

---
Tags: c++, directx9
---


# Question
Title: Unity 2d diffuse sprites not rendering on mobile
EDIT: Just an update, did change from sprite/diffuse to Diffuse and zordering of my level using t2dtk map stuff was backwards. Like the camera flipped around so i had to shuffle things around on the Z axis. Also things that were rendering in 2d with their y rotated 180 degrees no longer were so I had to change how the other engine I was using (Corgi engine) was moving projectiles.

This all worked then in the editor. When I pushed to the system, still nothing renders unless the rendering path is legacy vertex lit. And then it will render but dark like my directional light and point lights are meaningless. Apparently I am not cool enough to mess with Shaders/Unity 5 and mobile.

It seems like Mobile is having an issue rendering my diffuse sprites. I just made some of the sprites in my game diffuse so point lights would give them a nice lit up effect. This works great on PC but when I push the game to my mobile phone (a Galaxy Note 3) nothing that has that diffuse material renders at all. I am assuming it is just setting but I cannot figure out for the life me how to get this to work. I tried to muck with settings (rendering paths etc) nothing seemed to help. Of note: The stuff renders fine in Unity editor when the mobile target is selected even.

# Answer
> 1 votes
I'd put my money on shader problems here. Typically one "shader" script contains multiple options of CG programs, generally the ones with the higher hardware / software requirements go at the top of the script, and older / slower devices fallback to the best of the lesser shaders they can support. I'd take a peek at the "Diffuse" Shader Script you are using to see what exactly the fallbacks are doing. (In version 5.0 Unity actually classified nearly all of the previous shaders as "Legacy" and reorganized the remaining to better differentiate the new PBR stuff.)

http://docs.unity3d.com/Manual/SL-Fallback.html

# tldr; All of the back story aside...

You should be able to find less resource intensive shaders specifically designed for mobile under the Material : Shader \> Mobile \> Diffuse, from the drop down. Try this one:

---
Tags: unity, 2d
---


title: Zoom out more in Unity

text:
# Question
Title: Zoom out more in Unity
I am making a sphere with the radius of earth (6371000 meters). I have only limited zoom out and that makes it impossible to add something on the terrain. If I press F, it does not zoom out further than I could before. I tried to add a very large object like terrain and hitting F, but the zoom was still not sufficient.

I am using Unity 5.2.1

# Answer
As described in my comment above, there's actually a good reason Unity's editor doesn't like to zoom out to these scales, and forcing it to do so is likely to just reveal more problems.

Like many engines, Unity uses single-precision floating point numbers to represent object and vertex positions. Floating point representations can handle an immense range of values, but they lose precision as the numbers get larger.

At 1 Earth radius from the origin, positions can only be specified to a resolution of a quarter of a metre, which is likely to be too coarse for almost all gameplay. (Imagine if your camera was jumping a quarter metre every time you nudged it, or if objects were hovering a quarter metre above the ground because that's the closest non-intersecting point the physics simulation could find)

This doesn't get substantially better if you change units or work in miniature. Changing to 1 unit = 1 km makes the values 1000 times smaller, but an error in the last decimal place matters 1000 times as much, so it basically washes out.

The way this is normally dealt with is to keep the action of the game centred near the origin of the coordinate system (0,0,0), and shifting it back there when the player strays too far away. As long as everything in the world shifts together, the player won't perceive this movement.

This will probably require spawning just the visible parts of the Earth's surface on demand when your player is close to them. (And falling back on a scaled-down sphere proxy when the player is far away)

Since you can't use the editor to assemble the whole planet in your scene view, you'll need to look at other ways of describing what you want on your surface, like...

* storing it in chunks where each item is close to its local chunk origin
* generating surface content procedurally on demand
* storing your level data in a custom file format using higher-precision numbers so you still have precision over planetary scales
> 3 votes

---
Tags: unity
---


# Question
Title: How can I more efficiently paint grass onto a large terrain object in Unity?
I'm trying to paint a grass onto a large terrain and I want it to cover the entire terrain. Since the brush size can't go past 100 it would seem that I'm stuck painting the entire thing with a small brush relative to the terrain size.

How can I more efficiently paint grass onto a large terrain object?

# Answer
You can absolutely "paint" a texture programmatically onto the Alphamaps of the terrain. Take a look at the TerrainData component and the Alphamaps methods / properties

http://docs.unity3d.com/ScriptReference/TerrainData.SetAlphamaps.html

# Things to know going in:

With this info one could presumably blanket the whole terrain with one texture at run time... Or if clever enough / build a Custom Editor script with a button to call a method that does this before compile time. That way you could save that terrain as a prefab / save the scene and not have to rely on spending runtime resources to do something trivial... or really whatever your little pixelated hearts desire
> 1 votes

---
Tags: unity, terrain
---


title: Making walls in OpenGL

text:
# Question
Title: Making walls in OpenGL
How do I make walls in JOGL 2.0 in Eclipse? So far, I've tried it with listing vertices, until I realised that was a C method while I need to work it in java.

# Answer
There are OpenGL bindings for Java, a good one is LWJGL. And yes, the methods are like C but adapted to Java so you'll be good with that. To make a wall, you can list some vertices, put them in a vertex buffer object and with an element buffer object specify the order in which they must appear. http://open.gl is a good learning resource for modern OpenGL
> 0 votes

# Answer
If you have plenty of patience and time, you should go for a deep opengl tutorial like "Learning Modern 3D Graphic Programming" of Jason L. McKesson (aka Nicol Bolas). I ported his C samples to Jogl here. Another one very good is ogldev, from Etay Meiri, which I am still porting here.

If you need it *quick & dirty*, take a look to my jogl-samples. There you will find an Hello Triangle, an Hello Texture and tens of small tests regarding OpenGL calls and techniques.

Forgive my links, it is my ego ^^.

**Avoid** any deprecated stuff at your life cost, target OpenGL 3.3+. You won't regret, more info here.

If you need any further help, just ask.
> 0 votes

---
Tags: eclipse, jogl
---


# Question
Title: How to create a trail like this in Unity?
I want to create a trail like this game...

When the plane flies it creates this trail...

It's possible because the game itself was made in Unity...

But I can't find any options to do so...

Any help would be much appreciated...

# Answer
Check out Unity's Trail Renderer.
> 3 votes

---
Tags: unity
---


# Question
Title: How should I handle animation states in Mecanim?
I did a tutorial which associated an integer to each state and manually set transitions from one state to another based on that integer, but that seems really sloppy.

Is there a more elegant way? I want to be able to change animations from code.

# Answer
> 3 votes
I dont know if you have seen this but i found this very usefull

http://forum.unity3d.com/threads/212172-Animator-state-machine-for-top-down-2d-games-with-non-rotational-sprite-animation

From a Unity dev:

> One way to go about this is to have 2D blendtree for each movement (example: idle, walk, run, ...)

The unity dev explains further:

> Even though not their original purpose, the 2D blendtree to group 8 different directions of same animation is very convenient. This allows you to keep your state machine very simple (see screenshots). The "blend" is just a discrete change from one sprite anim to another, but that doesn't cause any harm.

# Answer
> 0 votes
In Unity 5 you can define behaviours that can be attached to animator states:

```
using UnityEngine;

// Add this to the state in your state machine.
// This behaviour is instantiated ONCE per animator asset NOT per animator component.
public class YourStateMachineBehaviour : StateMachineBehaviour
{
    // You can have fields here, but they are shared amongst all game objects
    // with animators referencing the same state machine asset.
    public int foo = 42;

    public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        var gameObject = animator.gameObject;

        // Do whatever you want here...
    }
}

```

Refer to the Unity documentation for further information: https://unity3d.com/learn/tutorials/modules/beginner/5-pre-order-beta/state-machine-behaviours

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


# Question
Title: Creating Unity games for older versions of Android?
In the Unity editor, the lowest available Android version for debugging is Android 2.3.1 In my case, I have a phone running an older version of Android and I intend to publish my game to a wide audience. With the lowest version being 2.3.1, I see a problem publishing my games to older smartphones which still occupy a considerable size of the market share. My question is: Is there a way to publish my game to older versions of Android? Or is it impossible?

# Answer
Quoting Bart from the same question on Stack Overflow:

> Versions later than Unity 4.2.x don't support Android versions earlier than 2.3.x. So if your project relies on functionality only present in 4.3.x and higher, you're out of luck.
>
> Otherwise you can still download a 4.2.x or earlier version of Unity and create your builds with that.
> 2 votes

---
Tags: unity, android
---


# Question
Title: Unity2D - Save everything in a scene before loading another and come back to it?
So I have am into this endless runner thing where everything is generated randomly from prefabs. Okay cool! But I am currently working on a bonus collectible which takes the player to another scene. After certain time, the player must reach at exactly the same position it left from.

But that's not the problem. I have figured out a way to save and load player's and camera's position using temporary prefabs.

My problem is : When the player collects the bonus thing in main scene and goes to the bonus scene and comes back, there's a sort of gltichiness or distortion in the game view. As if, the bonus scene is frozen and other scene is overlapping and everything is being stretched. But in inspector, everything including camera is in place.

In game view, on returning, the camera seems to be starting from beginning while in inspector its exactly where its supposed to be. Not only that, there's a lot of distortion, which I am 70% sure is because the level had to load all over again and there's no possible way of game knowing which prefabs were instantiated as they all are random.

Compiling up, my question is, how can I save everything in a scene before leaving and load it all again at once so it doesn't have to go through all of it again. Is there any less-complex way? I hope I have made my ques clear. Thank you.

# Answer
> 1 votes
PS: I haven't tested this but may be this can help. Can you do this. 1) make and empty Game object Positioned at (0,0,0). 2) Add all the existing Game objects in the Scene to this game object so this becomes the parent of all other Game objects. 3) write a script on this Game object and add this in the awake function

```
DontDestroyOnLoad (this);

```

# Answer
> 0 votes
Do you really have to go to another scene?

It just seems like you can put both of your bonus level, and your classic level in the same scene, and then work on the camera/player position, translate it, lerp it, move it whatever way you like with no glitches or loading to worry about.

Also, make sure you're cleaning up anything that's not useful too!

---
Tags: unity, c#, 2d, level-design
---


# Question
Title: Wrong behavior when trying to move on air
I´m using Andengine and jBox2D to implement a Mario-like platform videogame. Jumping and moving works fine. The problem comes in a very specific case:

1. I keep the "Move left" button pressed all the time
2. Player is on air and when moving left, it hits a wall and it stops moving left (while it keeps falling) This is correct.
3. When the player passes the wall, if the "Move left" button is pressed, it should start moving left while falling but it doesn't. If I lift my finger and press "Move left" again, it works.

The code to move left/right is:

```
_playerBody.setLinearVelocity(-mLinearVelocityX, _playerBody.getLinearVelocity().y);

```

The jump code is:

```
_playerBody.applyLinearImpulse(0, -mImpulseY, _playerBody.getPosition().x, // /////JUMP
            _playerBody.getPosition().y);

```

This is the code for the hud:

```
Sprite left = new Sprite(-10, CAMERA_HEIGHT - 150, mLeftTextureRegion) {
    @Override
        public boolean onAreaTouched(TouchEvent pEvent, float pX, float pY) {

            if (!pEvent.isActionOutside() && !isDead && !isPaused) {
                movePlayerLeft(player_self_sprite, player_self_body);
            }

            if (pEvent.isActionUp())  {
                if (isPlayerMoving) {
                    stopPlayer(player_self_sprite, player_self_body);
                    isPlayerMoving = false;
                }
            }
            return true;
        }
    };

```

# Answer
> 1 votes
I don't see the entire game loop and how the positions are updated. But it appears that your player is still in jump mode and x velocity is set to 0 as the previous impulse of -mLinearVelocityX is overridden at some point and the input is not refreshed. As you probably have an algorithm to detect a collision, try something like that:

if (contact\_with\_wall) x\_case = 0; else {x\_case=-mLinearVelocityX;}

```
_playerBody.applyLinearImpulse(x_case, -mImpulseY, _playerBody.getPosition().x, // /////JUMP
            _playerBody.getPosition().y);

```

# Answer
> 0 votes
It seems that when the collision on the wall occurs, your code is resetting the speed of the character to zero.

I see two possible solutions:

1. Do not reset the speed, but just relocate the position of the character out of the wall. This way, the speed before the collision is preserved and once the obstacle is out of the way, the character will return to move. I think Mega Man games are like that.
2. Have a method on state of the character to update every frame and in it check if the diracional is hold and then apply the speed.X of the character.

---
Tags: andengine
---


title: Monogame Startup Memory Spike

text:
# Question
Title: Monogame Startup Memory Spike
I am currently porting a game from WP7 using XNA to WP8.1 using MonoGame. I have been putting considerable effort into optimizing my game to be under the 185MB memory limit for low-memory phones.

I was making headway until I discovered a memory spike on startup. I continued to reduce the quality of my assets until the memory usage (while the game is running) is at about 140MB. However, on startup, the memory usage spikes to 205MB, sits there for about 10 seconds, and then drops to standard operating memory usage. It does this every time. Increasing or decreasing the asset sizes only changes how high the spike goes and the usage in general, but it does not change the 10 second delay at all.

One idea I thought about was to delay the user with a longer splash screen, giving me time to load all the assets without blowing the hatch. But this seems to me like detracting from the user experience out of convenience.

Any ideas? Has anyone else had this problem?

# Answer
* Try to compress your assets
* Load only the necessary things for the first scene (like Main Menu)
* Avoid stock splash screen and write your own. So I mean, don't load anything at start-up. Then e.g make an animating splash screen. And load your assets slowly when splash screen fades out.

Hope, one of them helps

(Sorry for bad English)
> 1 votes

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


# Question
Title: Supported Orientation, Monogame, Windows Phone 8
I am developing a game in which I need to rotate the screen on Landscape mode or Portrait, and lock it that way.

In Monogame, targeting Windows Phone **8.1** adding this code:

```
Graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight;
            Graphics.ApplyChanges();

```

Was enough, but in Monogame, targeting Windows Phone **8** I can switch from Portrait mode to Landscape, even if I put the code above in the game constructor.

How can I stop/freeze the user from chaning the orientations on a specific category in my game?

Thanks.

# Answer
> -1 votes
Go to your package manifest. There should be the options for screen orientation. Uncheck the portrait.

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


# Question
Title: In GLUT, how do I bind an action to a press of "any key"?
Well, this sound ridiculous but the logic is escaping me. I have drawn my cube in OpenGL and I want to translate it to the right **if any of the key on the keyboard is pressed**. I know how to do this for specific keys but not for all the keys in one function? Do I have to code this for every key?

I was thinking to use `glutSpecialFunc` and `glutKeyboardFunc`? Is there any shorter way of doing this?

# Answer
Using `glutSpecialFunc` and `glutKeyboardfunction` is correct way. Whenever a key is pressed one of the function register this.

For example:

```
void pressKey(unsigned char key, int x, int y){
if(key=='w') close program (for example);
else movecube;
}

int main(int argc, char **argv) {

    glutInit(&argc, argv);
    initGL();
    glutCreateWindow("WINDOW");
    glutSpecialFunc(pressKey);
    glutKeyboardFunc(pressKey);
    glutMainLoop();

    return 1;
}

```

Whenever a key is pressed `pressKey` function is called and cube is moved. Anyway this wont work for some keys (ALT, CTRL, SHIFT or CAPSLOCK).
> 1 votes

---
Tags: keyboard, glut, callbacks
---


title: XNA 4.0 - Using premade .xnb font files

text:
# Question
Title: XNA 4.0 - Using premade .xnb font files
Basically, for our college project, we need to use a font in xna. The only problem is that we are not allowed to install it due to admin rights.

Is it possible to use and load the .xnb file that gets created as the font. Using spritefont gives errors as it searches for the font in windows.

(The .xnb file will be created on someones personal machine beforehand.)

# Answer
Copy your compiled (.xnb) font file to your content. And make the same filename as .spritefont file.

If you can't compile any fonts, use third party applications compiling those files.

Edit: Spritefont files are used to explain to the compiler, how that .ttf file should be compiled. (font size, chars, etc.)
> 1 votes

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


# Question
Title: Algorithm for spending x points on y things divided by n people
I'm trying to devise an algorithm to spend a given amount of points on a randomly generated list of items each with their own cost in a way that results in having a number of items that is divisible by a given value (the number of points given is always divisible by this). Each item must be represented as equally as possible.

Points: 12
Divisor: 6
Items: Foo (1) & Bar (3)

The optimal result would be 3 Foo and 3 Bar (12 total points and 6 items).

That could be achieved by filling the space alternately starting with the smallest item but that algorithm won't work for other permutations of the starting values or if there are more items to spend points on, some of which may have the same value as other items but must be represented equally in the final result.

The algorithm can result in spending less points than are available but never more. There may not always be a 1 cost item to fill in any remainders.

Another example I can't solve...

Points: 24
Divisor: 8
Items: Foo (1), Nacho (1) , Pizza(2), Bar (3), Cake (4)

Just spending all of the points is easy but spending it in such a way that you end with a specific number of items that can be divided between the divisor has had me scratching my head all day.

# Answer
This sounds like a more complex version of the classic "animal legs" problem. Except in that case, you only have two animals to deal with, so you could work it out using elementary maths ("every time I swap a cow for a chicken, I get two more legs...").

But in this case you have more variables, so you'll need to resort to the algorithmic way. Recall that in the animal legs problem, you get something like this:

> number\_of\_chickens*2 + number\_of\_cows*4 = number\_of\_legs

> number\_of\_chickens + number\_of\_cows = number\_of\_heads

> number\_of\_legs and number\_of\_heads are known, so substitute the equations into each other.

In your example, there are many more variables - more "animals" - which looks something like this:

> number\_of\_foo + number\_of\_nachos + number\_of\_pizzas*2 + number\_of\_bars*3 + number\_of\_cakes\*4 = 24

> number\_of\_foo + number\_of\_nachos + number\_of\_pizzas + number\_of\_bars + number\_of\_cakes = 8

A typical way to solve this is to express this as a matrix and perform row reduction on it, the simplest method of which (both by hand and by computer algorithm) is Gaussian elimination. You may have been taught this in high school.

```
| 1 1 2 3 4 | 24 |
| 1 1 1 1 1 | 8  |

(swap row1 and row2)
| 1 1 1 1 1 | 8  |
| 1 1 2 3 4 | 24 |

(row2 = row2 - row1)
| 1 1 1 1 1 | 8  |
| 0 0 1 2 3 | 16 |

(row1 = row1 - row2)
| 1 1 0 -1 -2 | -8 |
| 0 0 1  2  3 | 16 |

```

Now that the equations are in reduced row echelon form, you can start plugging in values to see which ones work. Note that your matrix isn't completely reduced, which tells you there are many possible solutions.

Let's start with row 2: it is basically saying: `number_of_pizzas + number_of_bars*2 + number_of_cakes*3 = 16`. Obviously keep in mind that you can't have negative numbers of anything, which implies that you can't have more than 8 of anything. With that in mind, we can plug in 8 for the number of bars, which means 0 pizzas and 0 cakes:

> 0*1 + 8*2 + 0\*3 = 16

Now put those values into row 1:

> number\_of\_foo*1 + number\_of\_nachos*1 + 0*0 + 8*-1 + 0\*-2 = -8

> number\_of\_foo + number\_of\_nachos = 0

Now we have our first solution: 8 bars.

Going back to the matrix, since any set of values that satisfies those row equations work, we can also try 5 cakes, which forces us to choose 1 pizza:

> 1*1 + 0*2 + 5\*3 = 16

Into row 1:

> number\_of\_foo*1 + number\_of\_nachos*1 + 1*0 + 0*-1 + 5\*-2 = -8

> number\_of\_foo + number\_of\_nachos = 2

Now we have a second set of solutions, as long as the number of foo and nachos total 2 (they cost the same so it doesn't matter), and there's 1 pizza and 5 cakes.

Let's try one more, just to get the hang of it. We can have 4 cakes, and 2 bars, which leaves 0 pizzas:

> 0*1 + 2*2 + 4\*3 = 16

Into row 1:

> number\_of\_foo*1 + number\_of\_nachos*1 + 0*0 + 2*-1 + 4\*-2 = -8

> number\_of\_foo + number\_of\_nachos = 2

Again, we have 2 foo-or-nachos, but this time also 2 bars and 4 cakes.

You may be wondering why we're guessing the values at the end - isn't there an algorithmic way to solve this? Sure, there is, it's called integer programming which is unfortunately NP-hard. So guessing, or going through all the possibilities, should be good enough.
> 4 votes

# Answer
When you're dealing with small numbers, sometimes the brute-force approach is best. In this case, you can simply try all combinations of items and return the ones where the point sum is right.

The trick is to work out all the combinations (a.k.a. multiset), and in your case, repeat the whole process but with a multiple of your divisor, until the number of things is too high, because even if you only choose your smallest-point item only, the points will exceed your target.

To make this more concrete, consider your second example; first we try picking 8 items that total 24 points. Try again for 16 items, and for 24 items. Stop after this, because after 24 even if you pick only the smallest point items (Foo or Nacho), you would exceed your point target.

Here's some sample code; you can find ways to generate multisets ("combinations with repetitions") on rosettacode.

```
var items = [['Foo', 1], ['Nacho', 1], ['Pizza', 2], ['Bar', 3], ['Cake', 4]];
var smallestPoint = 1;
var points = 24;
var divisor = 8;

function pick(n, got, pos, from, out) {
    if (got.length == n) {
        out.push(got.slice());
        return;
    }
    for (var i = pos; i < from.length; i++) {
        got.push(from[i]);
        pick(n, got, i, from, out);
        got.pop();
    }
}

function itemPointsEqual(items, points) {
    var sum = 0;
    for (var i = 0; i < items.length; i++) {
        sum += items[i][1];
    }
    return sum == points;
}

function countItems(items) {
    var counts = {};
    for (var i = 0; i < items.length; i++) {
        var name = items[i][0];
        counts[name] = counts[name] ? counts[name] + 1 : 1;
    }
    var countNames = [];
    for (var name in counts) {
        countNames.push(counts[name] + ' ' + name + 's');
    }
    return countNames.join(', ');
}

function disp(x) {
    var e = document.createElement('p');
    e.innerHTML = x;
    document.getElementsByTagName('body')[0].appendChild(e);
}

for (var total = divisor; total <= points / smallestPoint; total += divisor) {
    var combos = [];
    pick(total, [], 0, items, combos);
    for (var i = 0; i < combos.length; i++) {
        if (itemPointsEqual(combos[i], points)) {
            disp('Combination: ' + countItems(combos[i]) +
                '; total items: ' + total);
        }
    }
}
```
> 1 votes

---
Tags: mathematics, algorithm, game-mechanics
---


# Question
Title: How can I hand out free copies of my otherwise-paid Play Store game?
With Google Play Services, is it possible to give people redeemable codes for an Android game I made, or give them special access or something like that? How do I do it?

# Answer
> 0 votes
This Quora post revealed itself after a quick google search. It seems to address the question you are asking. In short, you can add the users as "Testers" for your development account and this will enable them to download the app for free.

The question:

https://www.quora.com/Is-there-a-way-to-distribute-a-paid-Android-app-for-free-to-press-or-reviewers-If-so-how

The answer I found:

http://qr.ae/R4D1CC

---
Tags: android, google-play, google-play-services
---


# Question
Title: Procedural world  generation oriented on gameplay features
In large procedural landscape games, the land seems dull, but that's probably because the real world is largely dull, with only limited places where the scenery is dramatic or tactical.

Looking at world generation from this point of view, a landscape generator for a game (that is, not for the sake of scenery, but for the sake of gameplay) needs to **not** follow the rules of landscaping, but instead some rules married to the expectations of the gamer. For example, there could be a choke point / route generator that creates hills ravines, rivers and mountains between cities, rather than the natural way cities arise, scattered on the land based on resources or conditions generated by the mountains and rainfall patterns.

Is there any existing work being done like this? Start with cities or population centres and then add in terrain afterwards?

The reason I'm asking is that I'd previously pondered taking existing maps from fantasy fiction (my own and others), putting the information into the system as a base point, and then generating a good world to play in from it. This seems covered by existing technology, that is, where the designer puts in all the necessary information such as the city populations, resources, biomes, road networks and rivers, then allows the PCG fill in the gaps.

But now I'm wondering if it may be possible to have a content generator generate also the overall design. Generate the cities and population centres, balancing them so that there is a natural seeming need of commerce, then generate the positions and connectivity, then from the type of city produce the list of necessary resources that must be nearby, and only then, maybe given some rules on how to make the journey between cities both believable and interesting, generate the final content including the roads, the choke points, the bridges and tunnels, ferries and the terrain including the biomes and coastline necessary.

If this has been done before, I'd like to know, and would like to know what went wrong, and what went right.

# Answer
Here's a great example of procedural terrain generation, using parameters like moisture, height etc... http://www-cs-students.stanford.edu/~amitp/game-programming/polygon-map-generation/
> 12 votes

# Answer
I believe I've been staring back at this question for the last three days, while asking myself how the procedural generation of worlds or even galaxies can, at the same time, be deterministic(such as always generating the same content from the same seed), look natural, and still have unique, interesting, unusual or even beautiful features in its landscape.

I keep going back to the same generic answer that this is going highly dependent on the genre of the game and its own internal consistent history within the story. For example, post-apocalyptic genre, why would anyone build a metropolis with massive walls in the middle of a wasteland, and make everyone inside of it live miserably? Why colonize such planets? In high fantasy, why make a city on top of a floating island? Why do dwarves make cities inside of mountains? And your generic evil enemy comes from fiery land with active volcanoes? Rule of Cool?

So it all goes back to your own answer where you input information into the PCG and it fills the gap, and also to the other answer about generating worlds which match plot lines and the overall story.

So plot generates gameplay elements which generates suitable landscape.

That said, I wonder if a story that generates a tree of consistent plot lines, will generate the overall gameplay design you're looking for.

(PS: These same three days thinking also made me come with another answer to a problem that may rise: there should be an automated test tool to check if the generated game design is sound, eg, you should have a medieval army having a hard time to defeat a generated fortress)
> 4 votes

# Answer
When I was at Cryptic Studios we were working on something like this for mission/quest generation. The designers specified mission objectives somewhat abstractly and it laid those out with some randomness in "player travel order" and cut paths between them.

An early version shipped with Star Trek Online as Genesis Missions<sup>(archive)</sup>. At the time we were very excited about it but I have no idea how much it continued after I left, or if it's available in the end-user Foundry tools. (Which was the eventual goal.)
> 2 votes

# Answer
Only paper dealing with similar issues I could find off-hand is Stachniak and Stuerzlinger's "An Algorithm for Automated Fractal Terrain Deformation". It assumes you create the terrain first and deform it (or rather, let the algorithm pick the parameters to deform it with automatically) to fit your constraints later, so it doesn't answer the question directly. Still, the methods presented therein might prove useful for others with similar problems.
> 2 votes

# Answer
Wouldn't such an algorithm automatically generate more 'tactical' terrain when roads are generated between cities?

Assuming that roads can only have a certain elevetion change per distance, terrain height would be adapted to the heigth of the road, which would lead to generation of chokepoints whenever a road passes through a hill/ravine/whatever. Of course, the amount of change in terrain height would need to be limited too, or you'd have roads running straight through the highest peaks.
> 2 votes

# Answer
A typical approach for procedural terrain generation is to draw specific features by hand and use the generator to fill in the rest. VTerrain is bound to have something interesting on this topic.
> 1 votes

# Answer
Lighthouse 3D has a good survey of some simple algorithms for terrain generation. If you're starting with a map that contains cities or other interesting areas, you could use some of these techniques to generate whatever terrain you would like. For example, intelligent use of the fault algorithm could be used to create cliffs or valleys around your city that would act as choke points. Also, using the circle algorithm would be a great way to generate terrian for turret placement. These are just some examples, but using these simple algorithms would be a fairly easy way to generate interesting terrain around your cities.
> 1 votes

# Answer
Maybe I'm oversimplifying, but why ignore the fact that cities are built on advantageous terrain, or for that matter, any size of a civilized area for whatever reason? Maybe the terrain offers a tactical advantage for a military installment or perhaps there is a lumber mill at the intersection of a large forest and a river that has a larger village downstream. Even "holy" places are based on terrain even if for the simple fact that that particular section of land was at some point deemed holy, etc. No matter what the consequences are, the final resting place of the overwhelming majority of civilization exists in a physical spot for very terrain-based reasons. Even in the case of a city sprouting up simply because there's enough trade happening between two larger cities to warrant a middle-man, if you will, that city location would be chosen based on the path of least resistance. It would be placed somewhere that offered good flat farmland for the local food supply coupled with land that lends itself well to the construction of roads. I'm sure you've thought about this...

So, if you're going to build the cities first, sure, why not? Why not build the city, village, settlement or whatever, along with a decent chunk of surrounding terrain, built by hand, that supports that type of establishment?

Take procedural biomes as an example. They're usually applied to pseudo-random temperature, humidity and height maps. If you've already designed the city (or lumber-mill, etc.) then you likely have a firm concept of what the land needs to look like, which if I'm not misunderstanding, is exactly your point. Take a fantasy building like Orthanc, replete with floor-plans and surrounding terrain, which you've dutifully replicated. Well, we know, depending on timeline, Orthanc was surrounded by a huge forest populated with Ents (tree creatures), etc. If you're trying to replicate that, then applying a random terrain makes no sense to me. That being said, once you've created this setting for the tower itself and the surrounding forest what's between Orthanc and whatever your next city is?

Simple approach might be writing your procedural terrain generation, place your setting inside of a randomly generated terrain system and lerp your heights out around your fixed setting and viola you can place Orthanc in many different randomly generated worlds (should that be what your after).

I think however, you'd be best off with a combination of setting, terrain and defined biome and making sure Orthanc gets placed inside of a procedurally generated large forest biome. Depending on how you code it, you could set min/max biome, terrain, humidity, etc. for each pre-defined setting or building or city that you've sculpted. Would this be a small task in a full fledged photorealistic 3d world? Obviously not.

I think if I were to attempt this, I would research coastline procedural algorithms first. Taking the approach that almost all civilizations throughout history have followed any coastline, be it an ocean, sea or large lake. It's the path of least resistance for growth since there's likely abundant fishing, trees nearby for wood, and certainly faster travel even with rudimentary watercraft (at least one-way).

I would think you would have to build completely backwards. Think, pseudo-random dots on a map representing points of civilization possibly with a noise algorithm determining the populations of those civilizations before anything else is determined. OK, so 1 point comes out to a population of 1,000, another 2,000,000 (or whatever ratio depending on your world population of course). Why? Why are those numbers of populations there? A population of 1,000 might be the little lumber-mill community. Maybe it's a mining community if it's on the north side of the map should you be creating a 3d spherical world. It gets a little fuzzy here because I don't know if you're going infinite in all directions making NESW pointless in determining biomes or if you want a very real "Earth" world where extreme north and south are always frozen, etc.

However, if you plop down your civilizations, based on pseudo-random noise populations I think we can safely assume a few rules (but maybe not absolutes) like... The larger the civilization, most likely, the larger number of useful resources on hand and the terrain to support them. Precious minerals, woods, etc. ad nauseam have to be present or there must be a huge trade system in place to support such a vast enterprise. Based on that you can start generating highways from city to city and roads to the outlying settlements like a deep mining operation, etc. Pick points of civilization that would formulate good coastlines and drop the population points completely off the map where you need to fill your oceans (or maybe you have Atlantis's in your world, or offshore oil drills). Do the same for ellipsoid patterns inside those coastlines to represent your larger lakes, or forests, etc.

Filling in the terrain in-between again depends on your biome approach completely. If you have a infinite in every direction world then put Orthanc down wherever it fits population-wise, force it into a forest biome and build around it outward until you get to halfway to your next preset destination which your algorithm is doing the same procedural generation around. Lerp/Blend the two terrains together as they meet and yes this is an obvious oversimplification.

Without a real working knowledge of what you're actually trying to accomplish mechanically I can only throw out ideas and possibly bad ones. I think your approach has merit, even if it is completely fantastical in reality, because you're targeting what's always the most important factor in any game: Is the player having fun? Or, am I creating a random world that isn't boring and thus, not fun?

What would also get interesting, and this could be a part of the generation of civilizations in any game, terrain first or not, are what happens if you plop down 2 large cities next to each other? What does it mean? Are they at war? Are they massive trading operations between two flourishing nations? What kind of enemies lurk in the woods of that lumber-mill?

I do think one thing is certain if you're trying to build terrain based on "cities" and that is the terrain would be directly affected by the population of said city, both in landscape and natural resources (and perhaps even in beauty).

I'm not sure if I actually answered anything or if this was appropriate but it's a very interesting concept and I'd love to hear where you head with it.
> 1 votes

# Answer
I would do generate the game-play features concurrently as part of the same process. There are a number of ways to build terrain based on rules. This YouTube talk by the Path to Exile devs is a pretty good example: https://www.youtube.com/watch?v=GcM9Ynfzll0. Also, for a less pre-built aproach, this looks interesting: https://www.youtube.com/watch?v=RAtdFKiqs34. You could use perlin noise to generate heights for each voronoi vertex and go from there
> 0 votes

---
Tags: procedural-generation, world-design, content-generation
---


title: Networking/Packet Design

text:
# Question
Title: Networking/Packet Design
When using a Client-Server model, it's necessary for those two parts to communicate data back and forth. There is one specific area that I've been thinking about and unsure about. That being putting certain information in a main update packet, that is sent every *n* milliseconds, or send it once when it happens. An example would be a turn-based strategy game. When one player's turn ends, and the next player's turn starts, you could send one packet to notify the clients of the change, or every *n* milliseconds, tell the client whose turn it is and it can determine when it changes. These are the pros I see to these approaches:

Inside Update Packet:

* Harder to become desynced if packets are lost, whereas if sent as an individual packet and the client fails to receive it, could create big desync issues.

Individual Packet:

* Sends less data between the server and client since it only sends it once, instead of every *n* milliseconds.

I'm fairly new to game design, so I'm not sure if there is a general consensus about the proper way to do this. There may also be another solution that I haven't thought of. Any input would be great.

# Answer
> 2 votes
In general, you want to minimize the bandwidth you use and avoid latency spikes. Don't send data you don't have to.

There are pieces of data that will be constantly changing, such as position in a real-time game. These you can and probably should just send at a steady rate. If one of the packets gets lost it's no big deal as the client will just get one of the following ones anyway. This is one of the many reasons games often don't use TCP: it will stall delivery of messages until it successfully delivers what may already be stale data.

Other data infrequently changes, such as the current player's turn in your example. This data need only be *delivered* once. That may mean that it needs to be *sent* multiple times to deal with packet loss in a UDP-based protocol. In such a case, you need a way to know when data has been delivered successfully. TCP has that built-in, but UDP requires you to devise your own mechanism.

Requisite reading for beginners: http://gafferongames.com/networking-for-game-programmers/

# Answer
> 0 votes
A lot of this depends on how you're sending the packets: TCP or UDP.

TCP protocol establishes a connection with sequencing and acknowledgement that protects against errors like a lost packet by periodically resending until the receiver successfully sends back an acknowledgement, so you can safely assume one 'send' will get there eventually unless the connection is dropped, which should be an obvious error to catch.

UDP on the other hand has no connection, so no safeguards like this and could easily have lost packets. If you need to use this protocol, you could construct and send back acknowledgements of your own. Even if you send a hundred packets you can't guarantee any has been received without an acknowledgement of some kind, but this is essentially adding TCP-like behavior into UDP. Just use TCP if at all possible.

---
Tags: networking, software-engineering, turn-based
---


# Question
Title: Realistic angular velocity for rolling sphere in Unity 5.1
I'm trying to make a small 2D game with a rolling ball/sphere using Unity 5.1, but if find the angular velocity of the ball weird.

On this first image (https://i.stack.imgur.com/O1Ksb.jpg), you can see the sphere in 2D and in its initial position. On this second image (https://i.stack.imgur.com/HLHHT.jpg), the sphere was moved by rolling until it made a 90° turn.

But the distance traveled by the sphere is greater than it should, if you wanted to be to be realistic : you can see that the radius of the circle is equal to the size of the squares' sides, so the circle circumference should be equal to ~6.28 (in square side size). If the sphere was traveling realistically, it should travel ~1.57 (in square side size) to turn 90°. But in the second image, we can see that it take 3 and not 1.57 .

The controller of the sphere is simply adding a force when a left or right button is pressed :

```
public class PlayerController : MonoBehaviour
{
    public float speed;
    private Rigidbody2D rg2d;

    void Start()
    {
        rg2d = GetComponent<Rigidbody2D>();
    }

    void FixedUpdate()
    {
        float moveHorizontal = Input.GetAxisRaw("Horizontal");

        Vector2 movement = new Vector2(moveHorizontal, 0.0f);
        rg2d.AddForce(movement * speed * Time.deltaTime);
    }
}

```

So my question is : how can I make the angular velocity realistic in this situation? Or am I doing something wrong?

Thanks for taking the time, I really appreciate !

# Answer
> 1 votes
This is because the sphere has a zero friction and simply slides along the surface. To correct the problem, add PhysicsMaterial2D to your sphere and set `friction` value greater than zero:

---
Tags: unity, geometry
---


# Question
Title: OpenGL: Interpole keyframes of animated 3d object inside vertex shader
Lets say I have `N` vertex buffers that hold the `N` key frames of an animated 3d object, that was created by an application like blender. To smoothly interpolate these frames, I would like to bind two buffers to render the object with a vertex shader like this:

```
in vec4 inPos0;
in vec4 inPos1;

in vec3 inNormal0;
in vec3 inNormal1;

... other attributes...

uniform float time;

void main(){
    vec4 currentPos = mix(inPos0,inPos1,time);
    ... other calculations ...
}

```

To do this, the two buffers must be bound simultaneously, so I'd need to call `glVertexAttribPointer` every time, that a new keyframe should be used. This way buffer `I` can be bound to `inPos0` and buffer `I+1` to `inPos1`.

My question: Is this a good way to interpolate key frames? Or is there any builtin function to handle this scenario?

# Answer
The accepted way is using a skeletal animation.

This means creating bones and putting your vertexes relative to those bones. Then you can transform those bones using only a handful of matrices so that all vertexes can be transformed accordingly.

This technique is called GPU skinning or skeletal animation.
> 1 votes

---
Tags: opengl, animation
---


# Question
Title: Touch pad controls not working in apk, working from Unity Remote
I've come across something unusual with my HTC One M8, I'm not sure if it's phone specific, a bug in unity, or just poor setup on my part.

I've been using Unity Remote 4 to test in realtime, and it's really quite awesome. Don't think I've ever seen something quite so efficient for testing short of .NET and Windows Phone (and even then it's bloody close!)

Anywho, when in Unity Remote, obviously it's not an APK that's running but something that's running in some sort of virtual machine style environment, whereby the code is executed directly with massive links via USB. I tried, yesterday, to install my application as an apk, and for some reason the on screen controls didn't work. The boxes for them didn't appear (there is a dashed line around each control "area", and tapping and swiping simply did nothing.

I'm curious if this is because I've set the controls up as a "debug only" option, so I tried a debug build and still nothing. I tried a few other things like checking all the settings I could find to ensure nothing suggested that they were debug only, with no luck. Not sure where to turn.

If it helps at all, I'm using the "sample pack" (from the default assets) for mobile development, with a sprite as my "player", configured as a 2d sprite in a 2d side scroller game. I'm about to try it with the absolute default settings, literally just as a test, but I'm pretty confident that it won't make a blind difference.

# Answer
> 1 votes
Good to see you solved your issue. To avoid such problems, make extensive use of anchor points in Unity UI. That will make sure your UI elements stay where you intended.

# Answer
> 0 votes
It looks like this was an issue of positioning, for some reason the positioning is entirely rigid, so launching the game on my phone the buttons appeared in stupid positions due to the resolution being more than double that expected, further to that, the buttons were absolutely tiny (again due to non-relative sizing).

---
Tags: android, side-scroller
---


title: C# Design for Ability System

text:
# Question
Title: C# Design for Ability System
I'm a novice programmer but I have completed a pre-university in web prog so I am not a total noob. I'm using Unity, but this is just C# for now.

This is my first big project and I need some professional insight to make sure the design is not flawed. Currently working on abilities in an turn based rpg game.

What you might need to know: Abilities need to be learned/chosen, they may have requirements(levels, weapontype, more/etc.) New abilities will be added to the game with updates.

This is still the primitive stage, but very important to me because this project is more about learning to do it right rather than just getting it done.

Here are the following classes where we create abilities:

```
public abstract class Ability {
  public readonly int id, multi, manaCost;

 public Ability(int id, int multi, int manaCost) {
   this.id = id;
   this.multi = multi;
   this.manaCost = manaCost;
 }
 public virtual void resolve(Actor user, Actor target){}
 //Would create more methods with different parameters based on different abilities
 //Example for multi target ability
 public virtual void resolve(Actor user, Actor[] targets){}
}

```

Pretty simple stuff, Actor is just a in-game character. resolve is where the ability effects will be coded

```
using UnityEngine;
public class Freeze : Ability {
  public Freeze() : base(0, 0, 3) { }

  public override void resolve(Actor user, Actor target) {
    int damage = 2 * user.attribute[2];
    Debug.Log (damage);
    target.damage(damage);

    /*System.Random rnd = new System.Random();
    if(rnd.Next(100) <= 35)
    target.state = new Frozen();*/
  }
}

```

the way I was planning to use abilities is, in the main script of the battle system there would be an array that has all the abilities such as this:

```
Ability[] all_ability;
public void createAbilities(){
    all_ability = new Ability[2]; //size increased as we create more abilities
    all_ability[0] = new Freeze();
    all_ability[1] = new FirstStrike(); //and so on as we create more
}

```

The index of the array is also the id of the ability which allows us to easily access abilities.

So if an Actor wanted to use freeze, the id of freeze would be stored in Actor i.e. p1.actors\[0\].ability\_ids array

so let's say i've got what ability the player chose, it would be something like this

```
int aId = p1.actors[i].ability_ids[j]; //would return 0 assuming he chose freeze
all_ability[aId].resolve(p1.actors[i], p2.actors[k]);

```

Everything works so far, no errors, and damage gets calculated correctly but this is a very simple ability and still much more to add like damage counters, animations, status effects etc.

What should I look out for? is there a much easier way to do this I dont know about? I guess my main concern is, as we learn in web programming, it is said to be very bad to hard code values and everything should come from databases, but, is that also true for a game since each ability can be quite different? As you can see, everything is hard coded here. I guess I just want tips on things I may have done wrong/if there is a clear better way to do this. Thanks for any and all replies!

# Answer
> 3 votes
You sound like you're off to a good start! However, you asked a pretty general question, so I can only really offer some general pointers that might help!

To start with, I'd use a List instead of an array ( `using System.Collections.Generic`). You can still do `abilityList[index]` like with arrays, but you get the added benefit of not having to handle resizing if you run out of rooms (since it's handled by the `List<T>` class), and LINQ queries, if you're into that!

After that, you should make sure your Actor has an "AddAbilities" method. Then, on load (or creation), you can simply go down the list, adding the abilities appropriately (instead of hardcoding them). For instance, if your character load data for Darth Vader is:

`Force Lightning, Force Choke`

(Not knowing how you intend to store stuff, let's just assume you somehow parse out a list of strings)

```
foreach(string abil in savedCharAbilities)
{
  //You can use reflection or an AbilityFactory that takes a string parameter to create
  // an instnace of the class based on it's name.
  // If you have an enumeration of all of the possible abilities
  // (only do this if you have a small total amount!), you could set up a switch statement
  // to get your new Ability instead.

  character.AddAbility(createdAbility);
}

```

Finally, you may also want to look into making your abilities MonoBehaviors that implement an `Ability` Interface instead of inheriting from an abstract class - that way you can make use of Unity's built in `Enable` properties (for toggle-able abilties), it's `Update` method (for quickly changing effects), and Unity's `Invoke` call (which calls the passed method X seconds later, or every X seconds if you call `InvokePeriodic`).

# Answer
> 9 votes
> it is said to be very bad to hard code values and everything should come from databases, but, is that also true for a game

Yes. You should read up on *data-driven design* and use it everywhere it seems to make sense.

Ideally your ability system's code should only define the *logic* of abilities and then data files can define the specific abilities and their parameters. Your code might include a `DamageEffect`, `StatusEffect`, `SpawnEffect`, `ArmorEffect`, etc. Then in a data file you can have something like:

```
<ability name="freeze">
  <int name="cost">100</int>
  <int name="level">6</int>
  <effect type="DamageEffect">
    <int name="amount">100</int>
    <string name="type">ICE</string>
  </effect>
  <effect type="StatusEffect">
    <string name="type">STASIS</string>
    <int name="time">10</int>
  </effect>
  <effect type="ParticleEffect">
    <string name="particleSystemTemplate">frost_particles.vfx</string>
  </effect>
</ability>

```

Now you can add new abilities easily. Users can mod your game more easily. You can build a nice little tool to make adding new abilities much easier than editing code and recompiling, especially for any non-coders on your design team.

# Answer
> 2 votes
I am currently creating a versatile system for this and while it's not fully functional yet it looks promising. I just use a normal `Ability` class where basic things like the cost, name, etc are being stored. It will also hold a list of `AbilityActions` or I could say stack where each of these actions is performed in order. The trick here is to create these actions as basic as possible to keep it versatile. Some of my AbilityActions are:

* Projectile
* Damage
* StatusEffect
* AreaOfEffect

Based upon this I will create my abilities. I used a build pattern for my ability class to help myself out. Just look it up, it's easy to create. Here I create a stun shot.

```
Ability stunShot = new Ability(
  //Mandatory fields, this one costs energy
  new Ability.Build("Stun Shot", Ability.Type.Energy, cost)
  //Add anything that is needed.
  //I won't use range since I will get that from the user when it uses this ability.
  //The string I pass is used for the log later on to say something like
  //"You have been hit by a Stun Bullet"
  //Perhaps you want all your projectiles have static damage then add it to it's constructor.
  .addAction(new ProjectileAction(range, "Stun bullet")
  //So what do we need more? Yes a effect action
  //I have these made in the same way as the
  //so I can have stun and entangle both use
  //MoveEffect but to keep it simple here I just add a new StunEffect
  .addAction(new EffectAction(new StunEffect(duration))));
);

```

Here is a fireball spell:

```
Ability fireball = new Ability(new Ability.Build(
"FireBall", Ability.Type.Mana, cost) //Uses mana
.addAction(new ProjectileAction(maxRange, "ball of fire"))
.addAction(new AreaOfEffectAction(radius, "blast") //caught in "blast" cought in "ice storm" etc.
.addAction(new DamageAction(damage))
.addAction(new EffectAction(new BurningEffect())));

```

This could also be created from external data, then I would create the builder separately, feed it from your xml data and insert it in ability.

```
Ability.Build abilityBuilder = new ActionBuilder("fill with xml/json/database/etc");
if (xmlData = "Projectile")
{
  actionBuilder.addAction(new ProjectileAction("More xml data"));
}
//...etc, then put them in a map or dictionary.
abilityMap.put("ability name from XML", new Ability(abilityBuilder));
//And look them up by name or int or whatever you choose.
abilityMap.get("fireball");

```

So the fireball ability is created and the player chooses to use it on a target, in my case this can be a position to shoot at something he cannot see.

* player calls `fireball.perform(player, position)`.
* projectile action starts and once it is done (hits something) it provides a position or perhaps a creature it hits.
* The area of effect uses that position or the position of the creature to look for stuff that is caught in the radius. It will store or return a list of these when done.
* With this list we can apply damage to all the creatures or perhaps furniture and set them on fire with the effect.

I can create as many actions as I want but keep them basic so you can combine them with others. Well that is not really necessary but if I would give my `ShootAction` also damage then I could not use it for a stun shot that does no damage at all.

Getting the creatures effected by actions like `ShootAction()` or `AreaOfEffect` carried over to the next action can be handled in several ways. I first had a trigger on these types of actions so I would go back in the list to find the latest lists (for me only creatures) of things to effect.

Now I have this list in `Ability` and pass it to each action and modify it in these type of actions. This removed a bunch of if statements and backtracking but I need two perform methods for each Action. One that takes the actual user and position and one that takes the user and a list of creatures. If there are creatures in the list we will always use the latter. If for example the `DamageAction` ever gets a tile position it knows nothing has been hit.

I know the original answer is from 2013 but I think this will help a lot of people out. I am currently also prototyping this and if it all works together I will consider to clean it up and make it available.

---
Tags: c#, design-patterns
---


title: Platformer collision problems

text:
# Question
Title: Platformer collision problems
I am working on a platformer 2D, and i am currently focusing on collision. I have the actual rectangle(class: Rect) and i can detect if the player-model is intersepting it. However, when it comes from the side, that is when the problems appear: i can prevent it from going down after the interseption but i cant prevent it if it intersepts with the edges. how can I make a better collision system?

EDIT:

I have worked a little on a system, but it doesnt work. Help me improve this:

```
for(Platform p : game.platforms){
            if(Rect.intersects(getBounds(), p.getBounds())){
                coll = true;
                int px = p.x;
                int py = p.y;
                if((x + 100) >= px  && (x + 100) <= px + 10){
                    x = px - 101;
                    y += 100;
                    Toast.makeText(game.c, "if(x + 100) >= px  && (x + 100) <= px + 10)", Toast.LENGTH_LONG).show();
                } else if(y  <= (py + 1) && y  >= py + p.height + 10){
                    y = 0;
                    Toast.makeText(game.c, "if8y <= (py + 1) && y  >= py + p.height + 10)", Toast.LENGTH_LONG).show();
                } else if(y  >= py ){
                    y = py - 100;
                    Toast.makeText(game.c, "if(y >= py", Toast.LENGTH_LONG).show();
                }
            }
        }
        if(!coll){
            y += 6;

        }else{

            heightJumped = 0;
            canJump = true;
            isInAir = false;
            jumping = false;
        }
        coll = false;
    }

```

# Answer
This is my perfectly working 2d collision system (C++). Maybe it helps. I have also had the problem with wrong colliding from sides but finally solved it.

So, I have a rectangle of player with 64px width and height.
"posX" and "posY" are its center coordinates.
The parameters of the "colCheck" function are the sides of the rectangle which we want to check if colliding.

```
float difference = 0; //final difference between player and object (inside)

short Player::colCheck(float left2, float top2, float right2, float bottom2)
{
    short _returnVal = 0;     //Return value
    float left1 = posX-32;    //Player Left
    float right1 = posX+32;   //Player Right
    float top1 = posY-32;     //Player Top
    float bottom1 = posY+32;  //Player Bottom

    if(left1 < right2 && right1 > left2 && top1 < bottom2 && bottom1 > top2)
    {
        if(right1 > left2 && left1 < left2 && right1-left2 < bottom1-top2 && right1-left2 < bottom2-top1)
        {
            difference = right1-left2;
            _returnVal = 1;
            //Player collides from left side of the object
        }
        else if(left1 < right2 && right1 > right2 && right2-left1 < bottom1-top2 && right2-left1 < bottom2-top1)
        {
            difference = right2-left1;
            _returnVal = 2;
           //Player collides from right side of the object
        }
        else if(bottom1 > top2 && top1 < top2)
        {
            difference = bottom1-top2;
            _returnVal = 3;
           //Player collides from top side of the object
        }
        else if(top1 < bottom2 && bottom1 > bottom2)
        {
            difference = bottom2-top1;
            _returnVal = 4;
           //Player collides from bottom side of the object
        }
    }

    return _returnVal;
}

        //Parameter 'cols' (=collisions): cols [index] [side]
        //cols[x][0] -> left side
        //cols[x][1] -> top side
        //cols[x][2] -> right side
        //cols[x][3] -> bottom side
        //Parameter 'size': count of the collisions
        void Player::colReact(std::vector<std::vector<float>> cols, unsigned int size)
        {
            for(unsigned int i = 0; i < size; i++)
            {
                short ret = colCheck(cols[i][0], cols[i][1], cols[i][2], cols[i][3]); //check if collides and get the return value
                if(ret > 0) //if is colliding
                {
                    float changeX; //variable to add to players X coord.
                    float changeY; //variable to add to players Y coord.
                    if(ret == 1) //collides from left
                    {
                        changeX = -difference;
                        changeY = 0;
                    }
                    else if(ret == 2) //collides from right
                    {
                        changeX = difference;
                        changeY = 0;
                    }
                    else if(ret == 3) //collides from top
                    {
                        changeX = 0;
                        changeY = -difference;
                    }
                    else if(ret == 4) //collides from bottom
                    {
                        changeX = 0;
                        changeY = difference;
                    }
                    posX += changeX; //add the -difference value to players x coord.
                    posY += changeY; //add the -difference value to players y coord.
                }
            }
        }

```

Hope it's a helpful source.
> 1 votes

---
Tags: android, collision-detection
---


# Question
Title: Stencil Buffer not working as expected in OpenGL ES 2.0 (Android)
I'm trying to get to grips with the stencil buffer.

Apart from setting up viewport, camera, etc, my OpenGL ES 2.0 initialisation code is:

```
GLES20.glDisable(GLES20.GL_CULL_FACE);
GLES20.glDisable(GLES20.GL_DEPTH_TEST);
GLES20.glEnable(GLES20.GL_BLEND);
GLES20.glEnable(GLES20.GL_STENCIL_TEST);

GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
GLES20.glClearColor(0.2f, 0.8f, 1.0f, 0);
GLES20.glClearStencil(0);

```

My main code is below.

```
        GLES20.glEnable(GLES20.GL_STENCIL_TEST);
        GLES20.glColorMask(false, false, false, false);
        GLES20.glStencilFunc(GLES20.GL_NEVER, 1, 0xFF);
        GLES20.glStencilOp(GLES20.GL_REPLACE, GLES20.GL_KEEP, GLES20.GL_KEEP);

        GLES20.glStencilMask(0xFF);
        GLES20.glClear(GLES20.GL_STENCIL_BUFFER_BIT);

        // draw sprites
        player.draw();

        GLES20.glColorMask(true, true, true, true);
        GLES20.glDepthMask(true);
        GLES20.glStencilMask(0x00); // don't effect the stencil buffer
        GLES20.glStencilFunc(GLES20.GL_EQUAL, 0, 0xFF);
        // draw where stencils value is 0 if we want...

        GLES20.glStencilFunc(GLES20.GL_EQUAL, 1, 0xFF);
        // draw where stencils value is 1 if we want...

        level.draw();

        GLES20.glDisable(GLES20.GL_STENCIL_TEST);

```

However, this doesn't work. As expected this code does not draw the payer. The player (or the filled square surrounding the player) should be drawn to the stencil buffer. The next part of the code should draw the level, which should be clipped to the boundary of the player (or the square boundary of the player). What this code actually does is draw the whole level.

Why is the code not clipping the level to the profile of the player, or at least the square bounding the player ?

# Answer
The problem was I needed to set up the stencil buffer:

```
mGLSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 8);

```
> 0 votes

---
Tags: android, opengl-es2, frame-buffer, stencil
---


title: Multiple lights shadows

text:
# Question
Title: Multiple lights shadows
I'm trying to achieve multiple lights shadows. Currently my program works using only 1 spotlight as a light source that produces shadows. Well... I want to involve multiple lights to give a more realistic effect to my scene.

However, I'm facing a scenario which is a little bit unclear for me:

1. The steps I follow to create shadows is

a) Create FBO

b) Render scene from light's perspective using a depth texture attached to my FBO

c) Render the scene normally, using my texture from my FBO as a shadowmap texture in order to be able to sample it and creating finally shadows.
2. The steps I follow to create multiple shadows is

a) Create FBO1 and FBO2

b) Render scene from **1st** light's perspective using a depth texture attached to my **FBO1**

c) Render the scene normally, using my texture from my **FBO1** as a shadowmap texture in order to be able to sample it and creating finally shadows.

d) Render scene from **2nd** light's perspective using a depth texture attached to my **FBO2**

e) Render the scene normally, using my texture from my **FBO2** as a shadowmap texture in order to be able to sample it and creating finally shadows.

Now, the step 1) is pretty clear, works fine. When I manage to implement step 2), something happens: the shadows rendered will be the shadows of my last light (depending the order I call rendering methods). So in this case I get shadows only from my 2nd light.

If I reverse the order of calls (this order: **a -\> d -\> e -\> b -\> c**) and render first in my second FBO and then in my first FBO I get the shadows from my first light source. So basically I conclude: my shadows are not working simultaneously.

Is this the correct approach? (I've seen a solution which uses in fragment shader an array of shadowMaps, an array of lightSpace coordinates so this involves multiple uniforms... what do you think about this?)

Thanks

# Answer
> 4 votes
Are you using blending between your rendering passes?

It sounds like your rendering loop is going something like this:

1. Fill first explicitly defined shadow map
2. Render scene fully using the first light
3. Fill second explicitly defined shadow map
4. Re-render scene fully once again but using second light

Under that situation, the result of step 4 will essentially overlap the results of step 2. If multiple lights (& shadows) are desired, you need to enable blending (glEnable(GL\_BLEND);) between rendering passes.

If blending doesn't solve the problem, perhaps the issue is related to you not properly defining which texture should be used when rendering (ie not passing the correct texture handle).

---

The solution of using multiple shadow maps in a single fragment shader assumes that you are using a single shader to handle all of your lighting calculations. Under this situation, it would be possible to do the following:

1. Fill first explicitly defined shadow map
2. Fill second explicitly defined shadow map
3. Render scene fully

But one problem with this is that you have to always pre-define in your shader code the maximum amount of lights and shadows you want to use. This is incredibly restrictive.

A solution to this is to implement a deferred shading system. Instead of having a single shader program, you define one for every type of shading situation you need (like one for spot lights, one for point lights, etc), and then instead of shading the entire scene multiple times only the stuff on the screen gets shaded.

This alleviates the problem of having arrays of shadows and lights per shader, since a shader will now only contain everything a single light needs.

---
Tags: opengl, shadows
---


title: Separating rendering from HWND

text:
# Question
Title: Separating rendering from HWND
I'm considering separating my game simulation from the message loop. It seems odd to me to have other systems tied directly to the window in which my game is running. Most examples I see are implemented similar to the following (I'm glossing over details here, code is only meant to get the idea across)

```
... WndProc(...)
{
    //PeekMessage
    //Update input
    //Update timer
    //Update simulation
    //Update renderer
}
```

To increase separation of concerns, I'd like to move the update of input, simulation and renderer out of the specific window itself. This seems simple to accomplish

```
... WinMain(...)
{
    //Update window
    //Update input
    //Update timer
    //Update simulation
    //Update renderer
}

... WndProc(...)
{
    //PeekMessage
}

```

There is information that must be obtained from the window to be consumed by the rest of the game. Namely, input (if using the message system), window size, window focus, etc. I should be able to use callbacks or passing in references to state objects the window will update to get this information.

This approach allows me to separate each concern into it's own class. The window code is implemented in a `Window` class, input in `Input`, etc. I can use `WinMain` or a `Game` class to create each system and coordinate state between them.

Further, it allows me to divorce the renderer from the `HWND` itself. It seems smelly to me to have the renderer embedded directly within the `Window`. What if something happens to the window? What if I want to use the same renderer to output multiple views into separate windows (via `CreateAdditionalSwapChain`)?

The questions that arise from this:

Primary:

* It seems I can just rebuild the swap chain to hook up to a new window. Do scenarios exist where the `HWND` could be invalidated or destroyed but I want to retain my rendering context? Or is this overkill?

Secondary:

* Are there flaws to this approach I'm not considering?
* Are there better implementations I'm not considering?

# Answer
Take a look at the Direct3D Game templates on GitHub. The Win32 desktop HWND processing and message pump in Win32Game\_201x is isolated to a single module which can be replaced with something like the ICoreWindow render loop and message handling as is done in the UWPGame\_2015 template. All the templates use the same basic `Game` class which handles the Direct3D device creation and swapchain.

It's quite common for cross-platform engines to isolate the platform-specific main loop and window handling from the graphics rendering. That said, there are a lot of pitfalls here particularly with respect to multi-threading. See DirectX Graphics Infrastructure (DXGI): Best Practices if you plan to do threading in your application.
> 1 votes

---
Tags: directx, windows, architecture
---


title: Java LWJGL Windows 10 native files

text:
# Question
Title: Java LWJGL Windows 10 native files
Hello I made a simple game and I want to share it to my friend but he cant run it. I'm assuming it's because he has windows 10 and the LWJGL 2 native files don't support that (I've asumed that based on the .bat run file (a standard Java -jar a.jar line) wich crashed right before it is supposed to initialize windows 10). Maybe that isn't the problem but I don't see any other issue. Do the native files support newer systems? If not, then could you give me suggestions on getting new native files or something. Thanks

# Answer
What you have probably overlooked is the `-Djava.library.path` flag. This is a flag that must be set when running the `java` command to tell the JVM where the native files are located. Let's say you have this file hierarchy:

* natives/ (\*.dll, \*.so)
* yourGame.jar

You'd want to run the `.jar` with the following command:

```
java -Djava.library.path="natives/" -jar yourGame.jar

```

Make sure that you export the `.jar` as a "Runnable JAR File" so that all libraries are included.

You didn't need to do this setup on your own computer because you've already imported the native files in your IDE. When distributing your game though, I suggest a file with the given `java` command and a `pause` command (on Windows) so that the person who runs the game can easily send you a screenshot or copy-paste of any error or debugging information.

Source: Distributing Your LWJGL Application
> 1 votes

---
Tags: java, lwjgl, windows
---


# Question
Title: How do I restrict the movement of a point to within a radius of another?
I have a situation where a sprite's center point needs to be constrained within a certain boundary in 2D space. The boundary is circular, so the sprite is constrained within a radius. This radius is defined as a distance from the center of a certain point.

I've got this code, but it only tells me *when* the center has overstepped the allowed radius:

```
float distance = Vector2.Distance(centerPosition, spritePosition));
if (distance > allowedDistance) {
    // Point is outside allowed range
}

```

I would like to also return the sprite's center to the closest point within that radius whenever it oversteps the bounds.

How can I do that?

# Answer
> 5 votes
Take the position of the object, minus the origin of the circle. This will give you a vector from the origin to the object. The length of this vector is the distance to the object. Multiply this vector by the circle's radius divided by the distance to the object. Set the object's position to the circle's origin plus this vector.

Psuedo-Code:

```
Vector FromCircleToObject = Object.Position - Circle.Origin;
FromCircleToObject *= Circle.Radius / FromCircleToObject.Length;
Object.Position = Circle.Origin + FromCircleToObject;

```

You can optimize this by using the vector's length squared. This saves you a square root. If you use the vector's length squared, you must use the circle's radius squared. Luckily, squaring is cheaper than square rooting, so there's still an optimization to be had.

# Answer
> 2 votes
What you need to do is reset the sprite's position back to it's greatest extent.

You can do this by taking the vector from the centre to the sprites position, normalising it and then multiplying that by the allowed distance. However, that involves a square root which *may* be too slow for your game.

Another approach is to limit the sprite to a box around the centre position so your test would become:

```
if (spritePosition.x > centrePosition.x + allowedDistance)
{
    spritePosition.x = centrePosition.x + allowedDistance;
}
else if (spritePosition.x < centrePosition.x - allowedDistance)
{
    spritePosition.x = centrePosition.x - allowedDistance;
}

```

and the same for the `y`.

**This obviously doesn't give the same effect** but *may* be quicker. You'd have to profile them both to see and also check the behaviour to see if was acceptable.

# Answer
> 2 votes
For anyone struggling to visualise it:

If the *distance* between *A* and *B* is less than the *radius*, we can quit early. *B* is already within *radius* of *A*, so everything is fine.

Otherwise, find the vector *u*, from *A* to *B*. Divide *u* by the *distance* to get the unit vector *û*. Multiply that by the *radius* to get a vector to the furthest point from *A* toward *B* that is still within *radius* of *A*.

# Answer
> 0 votes
So, your sprite has a rectangular shape? If so, you are effectively asking, "How do I move a rectangle that intersects with a circle inside the circle so that the rectangle no longer intersects". I assume then that the rectangle is in fact smaller than your circle and the sprite position represents the center of the sprite. If it doesn't, you can convert from top-left to center by simply adding 1/2 the width, height, that is:

```
center.X = spritePosition.x + spriteImageSize.x/2;
center.Y = spritePosition.y + spriteImageSize.y/2;

```

In that case, you need to consider the 4 points of the sprite. Check if the first one is outside, and if it is, move it so it isn't. I don't have a formal proof, but I conjecture that it is impossible for you to move a corner inside the circle such that it puts another corner outside that was previously inside. This depends strongly on the fact that the rectangle fits inside the circle.

The code would be something like this:

```
TL = sprite.getTopLeft();
if(outside(TL, circle)) {
newPoint = moveInside(TL); //see how to move a point inside
delta = newPoint - TL; //figure out how much we moved
spritePosition += delta; //move the center of the sprite
}

//repeat for TR, BL, BR -- IF YOU MOVE THE SPRITE, YOU MUST RECOMPUTE THE CORNERS!

```

If you don't need that level of detail and you'd rather treat the sprite as an infinitely small single point, then you simply need to detect when it is outside the circle and set it so that it is inside. See ChrisF's response on how to do that.

---
Tags: c#, mathematics, vector, geometry, collision-resolution
---


title: Toggling Mouse Lock

text:
# Question
Title: Toggling Mouse Lock
I've been having some trouble toggling on and off the `Cursor.lockMode` and `Cursor.visible`. My goal is that when you are playing, the cursor is locked and invisible, and when you press escape, a pause menu pops up (already done that) and the mouse is visible and moveable again. I have tried using an `if` statement in the Update void, but that only ran for one frame. Does anyone have any answers? I'm a little new to c# so cut me some slack.

Code (c#):

```
using UnityEngine;
using System.Collections;

public class CursorHideShow : MonoBehaviour {

void Start () {
    Cursor.lockState = CursorLockMode.Locked;
    Cursor.visible = false;
}

void Update () {
    if (Input.GetButtonDown ("Cancel")) {
        Cursor.lockState = CursorLockMode.None;
        Cursor.visible = true;
    }
    if (Input.GetButtonDown ("Cancel")) {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }
}

```

}

# Answer
**First things first:**
Your `Update()` method is never unlocking the cursor or making it visible since you are immediately locking and setting it invisible afterward in the same frame, using the same conditional (`if` check). Why it works for even one frame, I don't know.

To toggle the cursor state, you need something like this..

```
void Update () {
    if (Input.GetButtonDown("Cancel")) {
        Cursor.visible = !Cursor.visible; // toggle visibility
        if (Cursor.visible) { // if visible, unlock
            Cursor.lockState = CursorLockMode.None;
        } else {
            Cursor.lockState = CursorLockMode.Locked;
        }
    }
}

```

**Two:**
Can't confirm myself, but this may be a bug in Unity5.
Unity Forum - Cursor Lockstate Troubles
> 2 votes

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


# Question
Title: How irregularly shaped rooms should be placed in a dungeon
I have made a procedurally generated dungeon that places every room successfully so it is accessible via at least one other room. A 'successfully' placed room is a room who's wall cells are right net to another room's wall cells. This is because there are no corridors in my dungeon, but doorways, 2 cells thick:

```
       ###########
       #.........#     // Where '[]' is the Doorway.
########.........#
#.....[].........#
#.....############
#.....#
#######

```

However I have now moved on to procedurally generate irregular shaped rooms, such as 'L' shaped rooms, 'T' shaped rooms, and so on.

I am wondering how I can place, for example, a square room next to an 'L' shaped room, without wasting any space: i.e.:

```
     ##########
     #........#
######........#
#...[]........#
#...###########
#...#
#...#######
#.........#
#.........#
###########

```

This is not possible with my previous algorithm because it only took into account the room's bounds, where as now an 'L' shaped room's bounds contains empty space that a square room could possibly fit.

# Answer
I would say that your own answer might be a good start. Still, I would do it a bit differently. So, here are a few suggestions/additions.

1) You could first determine the possible positions of doors in each room, then use those as joint points. You connect Room A to Room B by a given door of A to a given door of B and then test if the result meets your conditions (for instance, that there is no overlap between the interior of the rooms, etc). This way can be cheaper than walking each room against each other.

2) If rooms are irregular but never super very complex in shape (like the simple shapes of T, L, U, E, squared, rectangles, etc) AND if you want perfect fit between rooms, you can use rooms vertices as point-joints for checking. It means, you choose a vector from room A boundary and make it match a vector of room B. Like you can see in figure below, you have to make sure at least one edge overlaps, so to avoid the first case shown. Also, you have to make sure that only edges overlap, i.e. no interior area, so to avoid the second case shown. So either the third or the fourth cases shown would be accepted and rooms would them be connected:

3) No matter the solution (including your own), depending on your preferences, you might want to try to leave as least open spaces as possible without rooms. For instance, in your example, it would mean starting the test for the position of room A in the empty space of the bounding box of B. One way to do that could be by identifying the vertices/edges/doors/whatever of B that lay within the base polygon of the bonding box of B, not at its edges. And then start there.

With some approaches, like the one shown in the figure above, i.e. using vertices as joint points, you can also find such specific match by doing the following. If you discard the cases where inner areas overlap, and only accept the cases where at least two edges overlap, then you can only have the last case shown in the figure.

4) If you choose to position the rooms near to each other and then walk one against the other testing for collisions, the first thing you should do is place both rooms near each other but in a way that they do not overlap, before moving one against the other. Doing that you save performance since you will need to move them less and also perform less collision checks. The best way to do that (specially if you have a big scene) is with spatial partitioning.

5) With any of solutions above, if you have really very complexly shaped rooms, one possibility is the following. If you don't mind using an additional mini-polygon as a corridor, just place the rooms very close to each other but not colliding (e.g. via spatial partitioning + walking one room), and then place the small corridor between then (even if it overlaps a bit) and use the common area between them as the passage:

Hope it helps, at least as food for thought.
> 4 votes

# Answer
I think I've managed to solve it:

* First generate your rooms:

```
             @#########@    // ' ' = Don't place any cell here
@#######@    #.........#    // '.' = Place floor cell here
#.......#    #.........#    // '@' = Place wall cell here
#.......#    @####@....#    // '#' = Place wall cell here AND
#.......#         #....#    //       mark as a possible doorway location.
@#######@         #....#
                  @####@

```
* Now we have two rooms ready for placement. NB: When creating the '#' cells, they must have a way of telling which direction the doorway is leading out to, this is so rooms can be placed in the correct position and avoid overlapping as much as possible. This could be represented by an integer or vector. E.g.: (-1, 0) for left.
* Move room A next to a random room (in this case room B) by changing a random door cell's position to one of room B's door cell positions. The rest of the room's cells should then be moved relative to this door cell's position. If any of room A's floor cells overlap with any other room's floor cells, repeat this step.
* Where the two cells overlap, place a doorway/turn that cell into a floor cell.

```
   @#########@
   #.........#    // Even though the cells marked '%' are technically
   #.........#    // no longer feasible doorway cells, a new room should
   @%%%%@....#    // still not be able to place itself there as there
@##%%%%%@....#    // would be overlapping floor cells, which cancels
#............#    // a movement.
#.......@####@
#.......#
@#######@

```

Voila! (I shall try to implement this and then edit this answer accordingly - either delete it or confirm success)
> 2 votes

---
Tags: procedural-generation, level-design, roguelikes
---


# Question
Title: How to get direction and velocity of movement of an object dragged with the mouse in Unty (C#)
I have an object that is dragged by the mouse (X and Z positions) over a table, with the following simple code:

```
 Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
 if(Physics.Raycast(ray, out hit));
 pos = new Vector3(hit.point.x,myobject.transform.localScale.y/2,hit.point.z);
 myobject.GetComponent<Rigidbody>().MovePosition(pos);

```

The dragging works as expected. What I am struggling with is how can one retrieve the direction and velocity of such a movement, i.e. the direction and the velocity of that object when moved by being dragged by the mouse (I use Unity, C#). I have searched online, but only found the common ways to retrieve velocity and movement when using standard Rigidbody movement, not when dragged by the mouse.

# Answer
> 3 votes
The velocity is the difference between the new position and the last position.
`velocity = newPos - oldPos`

The vector direction is the normalized velocity.
`direction = velocity.normalized`

Rigidbody should update velocity each frame, even if you are using MovePosition(), however, if you need to know what the velocity will be before the object is actually moved, then you will have to calculate it.

```
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit));
oldPos = myobject.transform.position;
newPos = new Vector3(hit.point.x,myobject.transform.localScale.y/2,hit.point.z);
myobject.GetComponent<Rigidbody>().MovePosition(pos);

Vector3 velocity = (newPos - oldPos);
Vector3 direction = velocity.normalized;

```

If you want the angle of the direction vector (or velocity, works the same) in 3D space, then you can use Vector3.Angle().

```
float worldDegrees = Vector3.Angle(Vector3.forward, direction); // angle relative to world space
float localDegrees = Vector3.Angle(myobject.transform.forward, direction); // angle relative to last heading of myobject

```

---
Tags: unity, c#, movement, mouse, direction
---


title: How i can control button input android?

text:
# Question
Title: How i can control button input android?
i am android programmer and i want control button input in android for example i made a game that when you press back button in android mobile nothing happens but i want quite from game.

This is how you can use the android back button in Unity games.

In C#

```
void Update()
{
   if (Application.platform == RuntimePlatform.Android)
   {
    if (Input.GetKeyDown(KeyCode.Escape))
        Application.Quit();
   }
}

```

or in JS

```
function Update()
{
   if (Application.platform == RuntimePlatform.Android)
   {
    if (Input.GetKeyDown(KeyCode.Escape))
        Application.Quit();
   }
}

```

but how i can contorl other buttons

# Answer
```
function Update () {
    if (Input.GetKey(KeyCode.Home)){
        // Home button pressed
        // Write everything you want to do here
    }
    if (Input.GetKey(KeyCode.Escape)){
        // Escape button pressed
    }
    if(Input.GetKey(KeyCode.Menu)){
        Application.Quit();
    }
}

```
> 1 votes

---
Tags: android, unityscript
---